diff --git a/.gitmodules b/.gitmodules index 98a34651..4e701d07 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ [submodule "linphone/oRTP"] - path = linphone/oRTP + path = oRTP url = git://git.linphone.org/ortp.git [submodule "linphone/mediastreamer2"] - path = linphone/mediastreamer2 + path = mediastreamer2 url = git://git.linphone.org/mediastreamer2.git diff --git a/linphone/ABOUT-NLS b/ABOUT-NLS similarity index 100% rename from linphone/ABOUT-NLS rename to ABOUT-NLS diff --git a/linphone/AUTHORS b/AUTHORS similarity index 100% rename from linphone/AUTHORS rename to AUTHORS diff --git a/linphone/BUGS b/BUGS similarity index 100% rename from linphone/BUGS rename to BUGS diff --git a/linphone/COPYING b/COPYING similarity index 100% rename from linphone/COPYING rename to COPYING diff --git a/linphone/ChangeLog b/ChangeLog similarity index 100% rename from linphone/ChangeLog rename to ChangeLog diff --git a/linphone/Makefile.am b/Makefile.am similarity index 100% rename from linphone/Makefile.am rename to Makefile.am diff --git a/linphone/NEWS b/NEWS similarity index 100% rename from linphone/NEWS rename to NEWS diff --git a/linphone/README b/README similarity index 100% rename from linphone/README rename to README diff --git a/linphone/README.M68k.txt b/README.M68k.txt similarity index 100% rename from linphone/README.M68k.txt rename to README.M68k.txt diff --git a/linphone/README.arm b/README.arm similarity index 100% rename from linphone/README.arm rename to README.arm diff --git a/linphone/README.macos b/README.macos similarity index 100% rename from linphone/README.macos rename to README.macos diff --git a/linphone/README.mingw b/README.mingw similarity index 100% rename from linphone/README.mingw rename to README.mingw diff --git a/linphone/TODO b/TODO similarity index 100% rename from linphone/TODO rename to TODO diff --git a/linphone/autogen.sh b/autogen.sh similarity index 100% rename from linphone/autogen.sh rename to autogen.sh diff --git a/linphone/build/wince/liblinphone.sln b/build/wince/liblinphone.sln similarity index 100% rename from linphone/build/wince/liblinphone.sln rename to build/wince/liblinphone.sln diff --git a/linphone/build/wince/liblinphone.vcproj b/build/wince/liblinphone.vcproj similarity index 100% rename from linphone/build/wince/liblinphone.vcproj rename to build/wince/liblinphone.vcproj diff --git a/linphone/build/wince/linphonec/linphonec.vcproj b/build/wince/linphonec/linphonec.vcproj similarity index 100% rename from linphone/build/wince/linphonec/linphonec.vcproj rename to build/wince/linphonec/linphonec.vcproj diff --git a/linphone/config.rpath b/config.rpath similarity index 100% rename from linphone/config.rpath rename to config.rpath diff --git a/linphone/configure.in b/configure.in similarity index 100% rename from linphone/configure.in rename to configure.in diff --git a/linphone/console/.gitignore b/console/.gitignore similarity index 100% rename from linphone/console/.gitignore rename to console/.gitignore diff --git a/linphone/console/Makefile.am b/console/Makefile.am similarity index 100% rename from linphone/console/Makefile.am rename to console/Makefile.am diff --git a/linphone/console/TODO b/console/TODO similarity index 100% rename from linphone/console/TODO rename to console/TODO diff --git a/linphone/console/commands.c b/console/commands.c similarity index 100% rename from linphone/console/commands.c rename to console/commands.c diff --git a/linphone/console/example/linphonec b/console/example/linphonec similarity index 100% rename from linphone/console/example/linphonec rename to console/example/linphonec diff --git a/linphone/console/linphonec.c b/console/linphonec.c similarity index 100% rename from linphone/console/linphonec.c rename to console/linphonec.c diff --git a/linphone/console/linphonec.h b/console/linphonec.h similarity index 100% rename from linphone/console/linphonec.h rename to console/linphonec.h diff --git a/linphone/console/shell.c b/console/shell.c similarity index 100% rename from linphone/console/shell.c rename to console/shell.c diff --git a/linphone/console/sipomatic.c b/console/sipomatic.c similarity index 100% rename from linphone/console/sipomatic.c rename to console/sipomatic.c diff --git a/linphone/console/sipomatic.h b/console/sipomatic.h similarity index 100% rename from linphone/console/sipomatic.h rename to console/sipomatic.h diff --git a/linphone/console/wav2raw.c b/console/wav2raw.c similarity index 100% rename from linphone/console/wav2raw.c rename to console/wav2raw.c diff --git a/linphone/coreapi/.gitignore b/coreapi/.gitignore similarity index 100% rename from linphone/coreapi/.gitignore rename to coreapi/.gitignore diff --git a/linphone/coreapi/Makefile.am b/coreapi/Makefile.am similarity index 100% rename from linphone/coreapi/Makefile.am rename to coreapi/Makefile.am diff --git a/linphone/coreapi/address.c b/coreapi/address.c similarity index 100% rename from linphone/coreapi/address.c rename to coreapi/address.c diff --git a/linphone/coreapi/authentication.c b/coreapi/authentication.c similarity index 100% rename from linphone/coreapi/authentication.c rename to coreapi/authentication.c diff --git a/linphone/coreapi/chat.c b/coreapi/chat.c similarity index 100% rename from linphone/coreapi/chat.c rename to coreapi/chat.c diff --git a/linphone/coreapi/enum.c b/coreapi/enum.c similarity index 100% rename from linphone/coreapi/enum.c rename to coreapi/enum.c diff --git a/linphone/coreapi/enum.h b/coreapi/enum.h similarity index 100% rename from linphone/coreapi/enum.h rename to coreapi/enum.h diff --git a/linphone/coreapi/exevents.c b/coreapi/exevents.c similarity index 100% rename from linphone/coreapi/exevents.c rename to coreapi/exevents.c diff --git a/linphone/coreapi/exevents.h b/coreapi/exevents.h similarity index 100% rename from linphone/coreapi/exevents.h rename to coreapi/exevents.h diff --git a/linphone/coreapi/fonis.c b/coreapi/fonis.c similarity index 100% rename from linphone/coreapi/fonis.c rename to coreapi/fonis.c diff --git a/linphone/coreapi/friend.c b/coreapi/friend.c similarity index 100% rename from linphone/coreapi/friend.c rename to coreapi/friend.c diff --git a/linphone/coreapi/general_state.c b/coreapi/general_state.c similarity index 100% rename from linphone/coreapi/general_state.c rename to coreapi/general_state.c diff --git a/linphone/coreapi/help/Doxyfile.in b/coreapi/help/Doxyfile.in similarity index 100% rename from linphone/coreapi/help/Doxyfile.in rename to coreapi/help/Doxyfile.in diff --git a/linphone/coreapi/help/Makefile.am b/coreapi/help/Makefile.am similarity index 100% rename from linphone/coreapi/help/Makefile.am rename to coreapi/help/Makefile.am diff --git a/linphone/coreapi/help/doxygen.dox.in b/coreapi/help/doxygen.dox.in similarity index 100% rename from linphone/coreapi/help/doxygen.dox.in rename to coreapi/help/doxygen.dox.in diff --git a/linphone/coreapi/linphonecore.c b/coreapi/linphonecore.c similarity index 100% rename from linphone/coreapi/linphonecore.c rename to coreapi/linphonecore.c diff --git a/linphone/coreapi/linphonecore.h b/coreapi/linphonecore.h similarity index 100% rename from linphone/coreapi/linphonecore.h rename to coreapi/linphonecore.h diff --git a/linphone/coreapi/lpconfig.c b/coreapi/lpconfig.c similarity index 100% rename from linphone/coreapi/lpconfig.c rename to coreapi/lpconfig.c diff --git a/linphone/coreapi/lpconfig.h b/coreapi/lpconfig.h similarity index 100% rename from linphone/coreapi/lpconfig.h rename to coreapi/lpconfig.h diff --git a/linphone/coreapi/misc.c b/coreapi/misc.c similarity index 100% rename from linphone/coreapi/misc.c rename to coreapi/misc.c diff --git a/linphone/coreapi/plugins/buddylookup/AUTHORS b/coreapi/plugins/buddylookup/AUTHORS similarity index 100% rename from linphone/coreapi/plugins/buddylookup/AUTHORS rename to coreapi/plugins/buddylookup/AUTHORS diff --git a/linphone/coreapi/plugins/buddylookup/COPYING b/coreapi/plugins/buddylookup/COPYING similarity index 100% rename from linphone/coreapi/plugins/buddylookup/COPYING rename to coreapi/plugins/buddylookup/COPYING diff --git a/linphone/coreapi/plugins/buddylookup/ChangeLog b/coreapi/plugins/buddylookup/ChangeLog similarity index 100% rename from linphone/coreapi/plugins/buddylookup/ChangeLog rename to coreapi/plugins/buddylookup/ChangeLog diff --git a/linphone/coreapi/plugins/buddylookup/INSTALL b/coreapi/plugins/buddylookup/INSTALL similarity index 100% rename from linphone/coreapi/plugins/buddylookup/INSTALL rename to coreapi/plugins/buddylookup/INSTALL diff --git a/linphone/coreapi/plugins/buddylookup/Makefile.am b/coreapi/plugins/buddylookup/Makefile.am similarity index 100% rename from linphone/coreapi/plugins/buddylookup/Makefile.am rename to coreapi/plugins/buddylookup/Makefile.am diff --git a/linphone/coreapi/plugins/buddylookup/NEWS b/coreapi/plugins/buddylookup/NEWS similarity index 100% rename from linphone/coreapi/plugins/buddylookup/NEWS rename to coreapi/plugins/buddylookup/NEWS diff --git a/linphone/coreapi/plugins/buddylookup/README b/coreapi/plugins/buddylookup/README similarity index 100% rename from linphone/coreapi/plugins/buddylookup/README rename to coreapi/plugins/buddylookup/README diff --git a/linphone/coreapi/plugins/buddylookup/autogen.sh b/coreapi/plugins/buddylookup/autogen.sh similarity index 100% rename from linphone/coreapi/plugins/buddylookup/autogen.sh rename to coreapi/plugins/buddylookup/autogen.sh diff --git a/linphone/coreapi/plugins/buddylookup/configure.ac b/coreapi/plugins/buddylookup/configure.ac similarity index 100% rename from linphone/coreapi/plugins/buddylookup/configure.ac rename to coreapi/plugins/buddylookup/configure.ac diff --git a/linphone/coreapi/plugins/buddylookup/src/Makefile.am b/coreapi/plugins/buddylookup/src/Makefile.am similarity index 100% rename from linphone/coreapi/plugins/buddylookup/src/Makefile.am rename to coreapi/plugins/buddylookup/src/Makefile.am diff --git a/linphone/coreapi/plugins/buddylookup/src/lookup.c b/coreapi/plugins/buddylookup/src/lookup.c similarity index 100% rename from linphone/coreapi/plugins/buddylookup/src/lookup.c rename to coreapi/plugins/buddylookup/src/lookup.c diff --git a/linphone/coreapi/presence.c b/coreapi/presence.c similarity index 100% rename from linphone/coreapi/presence.c rename to coreapi/presence.c diff --git a/linphone/coreapi/private.h b/coreapi/private.h similarity index 100% rename from linphone/coreapi/private.h rename to coreapi/private.h diff --git a/linphone/coreapi/proxy.c b/coreapi/proxy.c similarity index 100% rename from linphone/coreapi/proxy.c rename to coreapi/proxy.c diff --git a/linphone/coreapi/sdphandler.c b/coreapi/sdphandler.c similarity index 100% rename from linphone/coreapi/sdphandler.c rename to coreapi/sdphandler.c diff --git a/linphone/coreapi/sdphandler.h b/coreapi/sdphandler.h similarity index 100% rename from linphone/coreapi/sdphandler.h rename to coreapi/sdphandler.h diff --git a/linphone/coreapi/siplogin.c b/coreapi/siplogin.c similarity index 100% rename from linphone/coreapi/siplogin.c rename to coreapi/siplogin.c diff --git a/linphone/coreapi/sipsetup.c b/coreapi/sipsetup.c similarity index 100% rename from linphone/coreapi/sipsetup.c rename to coreapi/sipsetup.c diff --git a/linphone/coreapi/sipsetup.h b/coreapi/sipsetup.h similarity index 100% rename from linphone/coreapi/sipsetup.h rename to coreapi/sipsetup.h diff --git a/linphone/gen-gtkfilelist.sh b/gen-gtkfilelist.sh similarity index 100% rename from linphone/gen-gtkfilelist.sh rename to gen-gtkfilelist.sh diff --git a/linphone/gtk+-2.16.2.filelist b/gtk+-2.16.2.filelist similarity index 100% rename from linphone/gtk+-2.16.2.filelist rename to gtk+-2.16.2.filelist diff --git a/linphone/gtk+-2.16.6.filelist b/gtk+-2.16.6.filelist similarity index 100% rename from linphone/gtk+-2.16.6.filelist rename to gtk+-2.16.6.filelist diff --git a/linphone/gtk+-2.18.5.filelist b/gtk+-2.18.5.filelist similarity index 100% rename from linphone/gtk+-2.18.5.filelist rename to gtk+-2.18.5.filelist diff --git a/linphone/gtk-glade/.gitignore b/gtk-glade/.gitignore similarity index 100% rename from linphone/gtk-glade/.gitignore rename to gtk-glade/.gitignore diff --git a/linphone/gtk-glade/Makefile.am b/gtk-glade/Makefile.am similarity index 100% rename from linphone/gtk-glade/Makefile.am rename to gtk-glade/Makefile.am diff --git a/linphone/gtk-glade/about.glade b/gtk-glade/about.glade similarity index 100% rename from linphone/gtk-glade/about.glade rename to gtk-glade/about.glade diff --git a/linphone/gtk-glade/buddylookup.c b/gtk-glade/buddylookup.c similarity index 100% rename from linphone/gtk-glade/buddylookup.c rename to gtk-glade/buddylookup.c diff --git a/linphone/gtk-glade/buddylookup.glade b/gtk-glade/buddylookup.glade similarity index 100% rename from linphone/gtk-glade/buddylookup.glade rename to gtk-glade/buddylookup.glade diff --git a/linphone/gtk-glade/call_logs.glade b/gtk-glade/call_logs.glade similarity index 100% rename from linphone/gtk-glade/call_logs.glade rename to gtk-glade/call_logs.glade diff --git a/linphone/gtk-glade/calllogs.c b/gtk-glade/calllogs.c similarity index 100% rename from linphone/gtk-glade/calllogs.c rename to gtk-glade/calllogs.c diff --git a/linphone/gtk-glade/chat.c b/gtk-glade/chat.c similarity index 100% rename from linphone/gtk-glade/chat.c rename to gtk-glade/chat.c diff --git a/linphone/gtk-glade/chatroom.glade b/gtk-glade/chatroom.glade similarity index 100% rename from linphone/gtk-glade/chatroom.glade rename to gtk-glade/chatroom.glade diff --git a/linphone/gtk-glade/contact.glade b/gtk-glade/contact.glade similarity index 100% rename from linphone/gtk-glade/contact.glade rename to gtk-glade/contact.glade diff --git a/linphone/gtk-glade/fonis.c b/gtk-glade/fonis.c similarity index 100% rename from linphone/gtk-glade/fonis.c rename to gtk-glade/fonis.c diff --git a/linphone/gtk-glade/friendlist.c b/gtk-glade/friendlist.c similarity index 100% rename from linphone/gtk-glade/friendlist.c rename to gtk-glade/friendlist.c diff --git a/linphone/gtk-glade/gtkrc b/gtk-glade/gtkrc similarity index 100% rename from linphone/gtk-glade/gtkrc rename to gtk-glade/gtkrc diff --git a/linphone/gtk-glade/incall_view.c b/gtk-glade/incall_view.c similarity index 100% rename from linphone/gtk-glade/incall_view.c rename to gtk-glade/incall_view.c diff --git a/linphone/gtk-glade/incoming_call.glade b/gtk-glade/incoming_call.glade similarity index 100% rename from linphone/gtk-glade/incoming_call.glade rename to gtk-glade/incoming_call.glade diff --git a/linphone/gtk-glade/linphone.h b/gtk-glade/linphone.h similarity index 100% rename from linphone/gtk-glade/linphone.h rename to gtk-glade/linphone.h diff --git a/linphone/gtk-glade/linphone.ico b/gtk-glade/linphone.ico similarity index 100% rename from linphone/gtk-glade/linphone.ico rename to gtk-glade/linphone.ico diff --git a/linphone/gtk-glade/linphone.iss b/gtk-glade/linphone.iss similarity index 100% rename from linphone/gtk-glade/linphone.iss rename to gtk-glade/linphone.iss diff --git a/linphone/gtk-glade/linphone.png b/gtk-glade/linphone.png similarity index 100% rename from linphone/gtk-glade/linphone.png rename to gtk-glade/linphone.png diff --git a/linphone/gtk-glade/linphone.rc b/gtk-glade/linphone.rc similarity index 100% rename from linphone/gtk-glade/linphone.rc rename to gtk-glade/linphone.rc diff --git a/linphone/gtk-glade/linphone2.png b/gtk-glade/linphone2.png similarity index 100% rename from linphone/gtk-glade/linphone2.png rename to gtk-glade/linphone2.png diff --git a/linphone/gtk-glade/log.glade b/gtk-glade/log.glade similarity index 100% rename from linphone/gtk-glade/log.glade rename to gtk-glade/log.glade diff --git a/linphone/gtk-glade/logging.c b/gtk-glade/logging.c similarity index 100% rename from linphone/gtk-glade/logging.c rename to gtk-glade/logging.c diff --git a/linphone/gtk-glade/loginframe.c b/gtk-glade/loginframe.c similarity index 100% rename from linphone/gtk-glade/loginframe.c rename to gtk-glade/loginframe.c diff --git a/linphone/gtk-glade/main.c b/gtk-glade/main.c similarity index 100% rename from linphone/gtk-glade/main.c rename to gtk-glade/main.c diff --git a/linphone/gtk-glade/main.glade b/gtk-glade/main.glade similarity index 100% rename from linphone/gtk-glade/main.glade rename to gtk-glade/main.glade diff --git a/linphone/gtk-glade/p2pwizard.glade b/gtk-glade/p2pwizard.glade similarity index 100% rename from linphone/gtk-glade/p2pwizard.glade rename to gtk-glade/p2pwizard.glade diff --git a/linphone/gtk-glade/parameters.glade b/gtk-glade/parameters.glade similarity index 100% rename from linphone/gtk-glade/parameters.glade rename to gtk-glade/parameters.glade diff --git a/linphone/gtk-glade/password.glade b/gtk-glade/password.glade similarity index 100% rename from linphone/gtk-glade/password.glade rename to gtk-glade/password.glade diff --git a/linphone/gtk-glade/propertybox.c b/gtk-glade/propertybox.c similarity index 100% rename from linphone/gtk-glade/propertybox.c rename to gtk-glade/propertybox.c diff --git a/linphone/gtk-glade/setupwizard.c b/gtk-glade/setupwizard.c similarity index 100% rename from linphone/gtk-glade/setupwizard.c rename to gtk-glade/setupwizard.c diff --git a/linphone/gtk-glade/sip_account.glade b/gtk-glade/sip_account.glade similarity index 100% rename from linphone/gtk-glade/sip_account.glade rename to gtk-glade/sip_account.glade diff --git a/linphone/gtk-glade/stock_people.png b/gtk-glade/stock_people.png similarity index 100% rename from linphone/gtk-glade/stock_people.png rename to gtk-glade/stock_people.png diff --git a/linphone/gtk-glade/support.c b/gtk-glade/support.c similarity index 100% rename from linphone/gtk-glade/support.c rename to gtk-glade/support.c diff --git a/linphone/gtk-glade/update.c b/gtk-glade/update.c similarity index 100% rename from linphone/gtk-glade/update.c rename to gtk-glade/update.c diff --git a/linphone/gtk-glade/utils.c b/gtk-glade/utils.c similarity index 100% rename from linphone/gtk-glade/utils.c rename to gtk-glade/utils.c diff --git a/linphone/gtk-glade/waiting.glade b/gtk-glade/waiting.glade similarity index 100% rename from linphone/gtk-glade/waiting.glade rename to gtk-glade/waiting.glade diff --git a/linphone/intl/ChangeLog b/intl/ChangeLog similarity index 100% rename from linphone/intl/ChangeLog rename to intl/ChangeLog diff --git a/linphone/intl/Makefile.in b/intl/Makefile.in similarity index 100% rename from linphone/intl/Makefile.in rename to intl/Makefile.in diff --git a/linphone/intl/VERSION b/intl/VERSION similarity index 100% rename from linphone/intl/VERSION rename to intl/VERSION diff --git a/linphone/intl/bindtextdom.c b/intl/bindtextdom.c similarity index 100% rename from linphone/intl/bindtextdom.c rename to intl/bindtextdom.c diff --git a/linphone/intl/cat-compat.c b/intl/cat-compat.c similarity index 100% rename from linphone/intl/cat-compat.c rename to intl/cat-compat.c diff --git a/linphone/intl/dcgettext.c b/intl/dcgettext.c similarity index 100% rename from linphone/intl/dcgettext.c rename to intl/dcgettext.c diff --git a/linphone/intl/dgettext.c b/intl/dgettext.c similarity index 100% rename from linphone/intl/dgettext.c rename to intl/dgettext.c diff --git a/linphone/intl/explodename.c b/intl/explodename.c similarity index 100% rename from linphone/intl/explodename.c rename to intl/explodename.c diff --git a/linphone/intl/finddomain.c b/intl/finddomain.c similarity index 100% rename from linphone/intl/finddomain.c rename to intl/finddomain.c diff --git a/linphone/intl/gettext.c b/intl/gettext.c similarity index 100% rename from linphone/intl/gettext.c rename to intl/gettext.c diff --git a/linphone/intl/gettext.h b/intl/gettext.h similarity index 100% rename from linphone/intl/gettext.h rename to intl/gettext.h diff --git a/linphone/intl/gettextP.h b/intl/gettextP.h similarity index 100% rename from linphone/intl/gettextP.h rename to intl/gettextP.h diff --git a/linphone/intl/hash-string.h b/intl/hash-string.h similarity index 100% rename from linphone/intl/hash-string.h rename to intl/hash-string.h diff --git a/linphone/intl/intl-compat.c b/intl/intl-compat.c similarity index 100% rename from linphone/intl/intl-compat.c rename to intl/intl-compat.c diff --git a/linphone/intl/l10nflist.c b/intl/l10nflist.c similarity index 100% rename from linphone/intl/l10nflist.c rename to intl/l10nflist.c diff --git a/linphone/intl/libgettext.h b/intl/libgettext.h similarity index 100% rename from linphone/intl/libgettext.h rename to intl/libgettext.h diff --git a/linphone/intl/linux-msg.sed b/intl/linux-msg.sed similarity index 100% rename from linphone/intl/linux-msg.sed rename to intl/linux-msg.sed diff --git a/linphone/intl/loadinfo.h b/intl/loadinfo.h similarity index 100% rename from linphone/intl/loadinfo.h rename to intl/loadinfo.h diff --git a/linphone/intl/loadmsgcat.c b/intl/loadmsgcat.c similarity index 100% rename from linphone/intl/loadmsgcat.c rename to intl/loadmsgcat.c diff --git a/linphone/intl/localealias.c b/intl/localealias.c similarity index 100% rename from linphone/intl/localealias.c rename to intl/localealias.c diff --git a/linphone/intl/po2tbl.sed.in b/intl/po2tbl.sed.in similarity index 100% rename from linphone/intl/po2tbl.sed.in rename to intl/po2tbl.sed.in diff --git a/linphone/intl/textdomain.c b/intl/textdomain.c similarity index 100% rename from linphone/intl/textdomain.c rename to intl/textdomain.c diff --git a/linphone/intl/xopen-msg.sed b/intl/xopen-msg.sed similarity index 100% rename from linphone/intl/xopen-msg.sed rename to intl/xopen-msg.sed diff --git a/linphone/intltool-extract.in b/intltool-extract.in similarity index 100% rename from linphone/intltool-extract.in rename to intltool-extract.in diff --git a/linphone/intltool-merge.in b/intltool-merge.in similarity index 100% rename from linphone/intltool-merge.in rename to intltool-merge.in diff --git a/linphone/intltool-update.in b/intltool-update.in similarity index 100% rename from linphone/intltool-update.in rename to intltool-update.in diff --git a/linphone/linphone-deps.filelist b/linphone-deps.filelist similarity index 100% rename from linphone/linphone-deps.filelist rename to linphone-deps.filelist diff --git a/linphone/linphone.iss.in b/linphone.iss.in similarity index 100% rename from linphone/linphone.iss.in rename to linphone.iss.in diff --git a/linphone/linphone.kdevelop b/linphone.kdevelop similarity index 100% rename from linphone/linphone.kdevelop rename to linphone.kdevelop diff --git a/linphone/linphone.spec.in b/linphone.spec.in similarity index 100% rename from linphone/linphone.spec.in rename to linphone.spec.in diff --git a/linphone/mingw-envsetup.sh b/linphone/mingw-envsetup.sh deleted file mode 100644 index 9f79d897..00000000 --- a/linphone/mingw-envsetup.sh +++ /dev/null @@ -1,5 +0,0 @@ -export PATH=$PATH:"${PROGRAMFILES}\GnuWin32\bin":"${PROGRAMFILES}\Inno Setup 5" -export PERL=/c/Perl/bin/perl.exe -export INTLTOOL_PERL=/c/Perl/bin/perl.exe - - diff --git a/linphone/m4/.gitignore b/m4/.gitignore similarity index 100% rename from linphone/m4/.gitignore rename to m4/.gitignore diff --git a/linphone/m4/Makefile.am b/m4/Makefile.am similarity index 100% rename from linphone/m4/Makefile.am rename to m4/Makefile.am diff --git a/linphone/m4/codeset.m4 b/m4/codeset.m4 similarity index 100% rename from linphone/m4/codeset.m4 rename to m4/codeset.m4 diff --git a/linphone/m4/exosip.m4 b/m4/exosip.m4 similarity index 100% rename from linphone/m4/exosip.m4 rename to m4/exosip.m4 diff --git a/linphone/m4/gettext.m4 b/m4/gettext.m4 similarity index 100% rename from linphone/m4/gettext.m4 rename to m4/gettext.m4 diff --git a/linphone/m4/glibc2.m4 b/m4/glibc2.m4 similarity index 100% rename from linphone/m4/glibc2.m4 rename to m4/glibc2.m4 diff --git a/linphone/m4/glibc21.m4 b/m4/glibc21.m4 similarity index 100% rename from linphone/m4/glibc21.m4 rename to m4/glibc21.m4 diff --git a/linphone/m4/iconv.m4 b/m4/iconv.m4 similarity index 100% rename from linphone/m4/iconv.m4 rename to m4/iconv.m4 diff --git a/linphone/m4/ilbc.m4 b/m4/ilbc.m4 similarity index 100% rename from linphone/m4/ilbc.m4 rename to m4/ilbc.m4 diff --git a/linphone/m4/intdiv0.m4 b/m4/intdiv0.m4 similarity index 100% rename from linphone/m4/intdiv0.m4 rename to m4/intdiv0.m4 diff --git a/linphone/m4/intl.m4 b/m4/intl.m4 similarity index 100% rename from linphone/m4/intl.m4 rename to m4/intl.m4 diff --git a/linphone/m4/intldir.m4 b/m4/intldir.m4 similarity index 100% rename from linphone/m4/intldir.m4 rename to m4/intldir.m4 diff --git a/linphone/m4/intmax.m4 b/m4/intmax.m4 similarity index 100% rename from linphone/m4/intmax.m4 rename to m4/intmax.m4 diff --git a/linphone/m4/inttypes-pri.m4 b/m4/inttypes-pri.m4 similarity index 100% rename from linphone/m4/inttypes-pri.m4 rename to m4/inttypes-pri.m4 diff --git a/linphone/m4/inttypes.m4 b/m4/inttypes.m4 similarity index 100% rename from linphone/m4/inttypes.m4 rename to m4/inttypes.m4 diff --git a/linphone/m4/inttypes_h.m4 b/m4/inttypes_h.m4 similarity index 100% rename from linphone/m4/inttypes_h.m4 rename to m4/inttypes_h.m4 diff --git a/linphone/m4/isc-posix.m4 b/m4/isc-posix.m4 similarity index 100% rename from linphone/m4/isc-posix.m4 rename to m4/isc-posix.m4 diff --git a/linphone/m4/lcmessage.m4 b/m4/lcmessage.m4 similarity index 100% rename from linphone/m4/lcmessage.m4 rename to m4/lcmessage.m4 diff --git a/linphone/m4/lib-ld.m4 b/m4/lib-ld.m4 similarity index 100% rename from linphone/m4/lib-ld.m4 rename to m4/lib-ld.m4 diff --git a/linphone/m4/lib-link.m4 b/m4/lib-link.m4 similarity index 100% rename from linphone/m4/lib-link.m4 rename to m4/lib-link.m4 diff --git a/linphone/m4/lib-prefix.m4 b/m4/lib-prefix.m4 similarity index 100% rename from linphone/m4/lib-prefix.m4 rename to m4/lib-prefix.m4 diff --git a/linphone/m4/lock.m4 b/m4/lock.m4 similarity index 100% rename from linphone/m4/lock.m4 rename to m4/lock.m4 diff --git a/linphone/m4/longdouble.m4 b/m4/longdouble.m4 similarity index 100% rename from linphone/m4/longdouble.m4 rename to m4/longdouble.m4 diff --git a/linphone/m4/longlong.m4 b/m4/longlong.m4 similarity index 100% rename from linphone/m4/longlong.m4 rename to m4/longlong.m4 diff --git a/linphone/m4/nls.m4 b/m4/nls.m4 similarity index 100% rename from linphone/m4/nls.m4 rename to m4/nls.m4 diff --git a/linphone/m4/ortp.m4 b/m4/ortp.m4 similarity index 100% rename from linphone/m4/ortp.m4 rename to m4/ortp.m4 diff --git a/linphone/m4/osip.m4 b/m4/osip.m4 similarity index 100% rename from linphone/m4/osip.m4 rename to m4/osip.m4 diff --git a/linphone/m4/po.m4 b/m4/po.m4 similarity index 100% rename from linphone/m4/po.m4 rename to m4/po.m4 diff --git a/linphone/m4/printf-posix.m4 b/m4/printf-posix.m4 similarity index 100% rename from linphone/m4/printf-posix.m4 rename to m4/printf-posix.m4 diff --git a/linphone/m4/progtest.m4 b/m4/progtest.m4 similarity index 100% rename from linphone/m4/progtest.m4 rename to m4/progtest.m4 diff --git a/linphone/m4/readline.m4 b/m4/readline.m4 similarity index 100% rename from linphone/m4/readline.m4 rename to m4/readline.m4 diff --git a/linphone/m4/signed.m4 b/m4/signed.m4 similarity index 100% rename from linphone/m4/signed.m4 rename to m4/signed.m4 diff --git a/linphone/m4/size_max.m4 b/m4/size_max.m4 similarity index 100% rename from linphone/m4/size_max.m4 rename to m4/size_max.m4 diff --git a/linphone/m4/stdint_h.m4 b/m4/stdint_h.m4 similarity index 100% rename from linphone/m4/stdint_h.m4 rename to m4/stdint_h.m4 diff --git a/linphone/m4/uintmax_t.m4 b/m4/uintmax_t.m4 similarity index 100% rename from linphone/m4/uintmax_t.m4 rename to m4/uintmax_t.m4 diff --git a/linphone/m4/ulonglong.m4 b/m4/ulonglong.m4 similarity index 100% rename from linphone/m4/ulonglong.m4 rename to m4/ulonglong.m4 diff --git a/linphone/m4/video.m4 b/m4/video.m4 similarity index 100% rename from linphone/m4/video.m4 rename to m4/video.m4 diff --git a/linphone/m4/visibility.m4 b/m4/visibility.m4 similarity index 100% rename from linphone/m4/visibility.m4 rename to m4/visibility.m4 diff --git a/linphone/m4/wchar_t.m4 b/m4/wchar_t.m4 similarity index 100% rename from linphone/m4/wchar_t.m4 rename to m4/wchar_t.m4 diff --git a/linphone/m4/wint_t.m4 b/m4/wint_t.m4 similarity index 100% rename from linphone/m4/wint_t.m4 rename to m4/wint_t.m4 diff --git a/linphone/m4/xsize.m4 b/m4/xsize.m4 similarity index 100% rename from linphone/m4/xsize.m4 rename to m4/xsize.m4 diff --git a/linphone/media_api/.gitignore b/media_api/.gitignore similarity index 100% rename from linphone/media_api/.gitignore rename to media_api/.gitignore diff --git a/linphone/media_api/DESIGN.txt b/media_api/DESIGN.txt similarity index 100% rename from linphone/media_api/DESIGN.txt rename to media_api/DESIGN.txt diff --git a/linphone/media_api/Makefile.am b/media_api/Makefile.am similarity index 100% rename from linphone/media_api/Makefile.am rename to media_api/Makefile.am diff --git a/linphone/media_api/apitest.c b/media_api/apitest.c similarity index 100% rename from linphone/media_api/apitest.c rename to media_api/apitest.c diff --git a/linphone/media_api/apitest.h b/media_api/apitest.h similarity index 100% rename from linphone/media_api/apitest.h rename to media_api/apitest.h diff --git a/linphone/media_api/basiccall.c b/media_api/basiccall.c similarity index 100% rename from linphone/media_api/basiccall.c rename to media_api/basiccall.c diff --git a/linphone/media_api/basiccall.h b/media_api/basiccall.h similarity index 100% rename from linphone/media_api/basiccall.h rename to media_api/basiccall.h diff --git a/linphone/media_api/callmember.c b/media_api/callmember.c similarity index 100% rename from linphone/media_api/callmember.c rename to media_api/callmember.c diff --git a/linphone/media_api/callmember.h b/media_api/callmember.h similarity index 100% rename from linphone/media_api/callmember.h rename to media_api/callmember.h diff --git a/linphone/media_api/ccl b/media_api/ccl similarity index 100% rename from linphone/media_api/ccl rename to media_api/ccl diff --git a/linphone/media_api/common.h b/media_api/common.h similarity index 100% rename from linphone/media_api/common.h rename to media_api/common.h diff --git a/linphone/media_api/media_api.c b/media_api/media_api.c similarity index 100% rename from linphone/media_api/media_api.c rename to media_api/media_api.c diff --git a/linphone/media_api/media_api.h b/media_api/media_api.h similarity index 100% rename from linphone/media_api/media_api.h rename to media_api/media_api.h diff --git a/linphone/media_api/mediaflow.c b/media_api/mediaflow.c similarity index 100% rename from linphone/media_api/mediaflow.c rename to media_api/mediaflow.c diff --git a/linphone/media_api/mediaflow.h b/media_api/mediaflow.h similarity index 100% rename from linphone/media_api/mediaflow.h rename to media_api/mediaflow.h diff --git a/p2pproxy/.classpath b/p2pproxy/.classpath deleted file mode 100644 index d4307def..00000000 --- a/p2pproxy/.classpath +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/p2pproxy/.cvsignore b/p2pproxy/.cvsignore deleted file mode 100644 index da41270a..00000000 --- a/p2pproxy/.cvsignore +++ /dev/null @@ -1,5 +0,0 @@ -eclipsebuild -.settings -antbuild* -P2pNetwork-* -sipp2 diff --git a/p2pproxy/.gcjbuilder b/p2pproxy/.gcjbuilder deleted file mode 100644 index 1084bf2f..00000000 --- a/p2pproxy/.gcjbuilder +++ /dev/null @@ -1,21 +0,0 @@ - - 0 - 0 - - 0 - - - - 0 - - 2 - - - - - - - debug - p2pproxy - make - \ No newline at end of file diff --git a/p2pproxy/.project b/p2pproxy/.project deleted file mode 100644 index fbea5077..00000000 --- a/p2pproxy/.project +++ /dev/null @@ -1,24 +0,0 @@ - - - p2pproxy - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - - - jni_src - 2 - jni_src - - - diff --git a/p2pproxy/AUTHORS b/p2pproxy/AUTHORS deleted file mode 100644 index e69de29b..00000000 diff --git a/p2pproxy/COPYING b/p2pproxy/COPYING deleted file mode 100644 index 94a9ed02..00000000 --- a/p2pproxy/COPYING +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/p2pproxy/ChangeLog b/p2pproxy/ChangeLog deleted file mode 100644 index e69de29b..00000000 diff --git a/p2pproxy/INSTALL b/p2pproxy/INSTALL deleted file mode 100644 index 8b82ade0..00000000 --- a/p2pproxy/INSTALL +++ /dev/null @@ -1,291 +0,0 @@ -Installation Instructions -************************* - -Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005, -2006, 2007, 2008 Free Software Foundation, Inc. - - This file is free documentation; the Free Software Foundation gives -unlimited permission to copy, distribute and modify it. - -Basic Installation -================== - - Briefly, the shell commands `./configure; make; make install' should -configure, build, and install this package. The following -more-detailed instructions are generic; see the `README' file for -instructions specific to this package. - - The `configure' shell script attempts to guess correct values for -various system-dependent variables used during compilation. It uses -those values to create a `Makefile' in each directory of the package. -It may also create one or more `.h' files containing system-dependent -definitions. Finally, it creates a shell script `config.status' that -you can run in the future to recreate the current configuration, and a -file `config.log' containing compiler output (useful mainly for -debugging `configure'). - - It can also use an optional file (typically called `config.cache' -and enabled with `--cache-file=config.cache' or simply `-C') that saves -the results of its tests to speed up reconfiguring. Caching is -disabled by default to prevent problems with accidental use of stale -cache files. - - If you need to do unusual things to compile the package, please try -to figure out how `configure' could check whether to do them, and mail -diffs or instructions to the address given in the `README' so they can -be considered for the next release. If you are using the cache, and at -some point `config.cache' contains results you don't want to keep, you -may remove or edit it. - - The file `configure.ac' (or `configure.in') is used to create -`configure' by a program called `autoconf'. You need `configure.ac' if -you want to change it or regenerate `configure' using a newer version -of `autoconf'. - -The simplest way to compile this package is: - - 1. `cd' to the directory containing the package's source code and type - `./configure' to configure the package for your system. - - Running `configure' might take a while. While running, it prints - some messages telling which features it is checking for. - - 2. Type `make' to compile the package. - - 3. Optionally, type `make check' to run any self-tests that come with - the package. - - 4. Type `make install' to install the programs and any data files and - documentation. - - 5. You can remove the program binaries and object files from the - source code directory by typing `make clean'. To also remove the - files that `configure' created (so you can compile the package for - a different kind of computer), type `make distclean'. There is - also a `make maintainer-clean' target, but that is intended mainly - for the package's developers. If you use it, you may have to get - all sorts of other programs in order to regenerate files that came - with the distribution. - - 6. Often, you can also type `make uninstall' to remove the installed - files again. - -Compilers and Options -===================== - - Some systems require unusual options for compilation or linking that -the `configure' script does not know about. Run `./configure --help' -for details on some of the pertinent environment variables. - - You can give `configure' initial values for configuration parameters -by setting variables in the command line or in the environment. Here -is an example: - - ./configure CC=c99 CFLAGS=-g LIBS=-lposix - - *Note Defining Variables::, for more details. - -Compiling For Multiple Architectures -==================================== - - You can compile the package for more than one kind of computer at the -same time, by placing the object files for each architecture in their -own directory. To do this, you can use GNU `make'. `cd' to the -directory where you want the object files and executables to go and run -the `configure' script. `configure' automatically checks for the -source code in the directory that `configure' is in and in `..'. - - With a non-GNU `make', it is safer to compile the package for one -architecture at a time in the source code directory. After you have -installed the package for one architecture, use `make distclean' before -reconfiguring for another architecture. - - On MacOS X 10.5 and later systems, you can create libraries and -executables that work on multiple system types--known as "fat" or -"universal" binaries--by specifying multiple `-arch' options to the -compiler but only a single `-arch' option to the preprocessor. Like -this: - - ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ - CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ - CPP="gcc -E" CXXCPP="g++ -E" - - This is not guaranteed to produce working output in all cases, you -may have to build one architecture at a time and combine the results -using the `lipo' tool if you have problems. - -Installation Names -================== - - By default, `make install' installs the package's commands under -`/usr/local/bin', include files under `/usr/local/include', etc. You -can specify an installation prefix other than `/usr/local' by giving -`configure' the option `--prefix=PREFIX'. - - You can specify separate installation prefixes for -architecture-specific files and architecture-independent files. If you -pass the option `--exec-prefix=PREFIX' to `configure', the package uses -PREFIX as the prefix for installing programs and libraries. -Documentation and other data files still use the regular prefix. - - In addition, if you use an unusual directory layout you can give -options like `--bindir=DIR' to specify different values for particular -kinds of files. Run `configure --help' for a list of the directories -you can set and what kinds of files go in them. - - If the package supports it, you can cause programs to be installed -with an extra prefix or suffix on their names by giving `configure' the -option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. - -Optional Features -================= - - Some packages pay attention to `--enable-FEATURE' options to -`configure', where FEATURE indicates an optional part of the package. -They may also pay attention to `--with-PACKAGE' options, where PACKAGE -is something like `gnu-as' or `x' (for the X Window System). The -`README' should mention any `--enable-' and `--with-' options that the -package recognizes. - - For packages that use the X Window System, `configure' can usually -find the X include and library files automatically, but if it doesn't, -you can use the `configure' options `--x-includes=DIR' and -`--x-libraries=DIR' to specify their locations. - -Particular systems -================== - - On HP-UX, the default C compiler is not ANSI C compatible. If GNU -CC is not installed, it is recommended to use the following options in -order to use an ANSI C compiler: - - ./configure CC="cc -Ae" - -and if that doesn't work, install pre-built binaries of GCC for HP-UX. - - On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot -parse its `' header file. The option `-nodtk' can be used as -a workaround. If GNU CC is not installed, it is therefore recommended -to try - - ./configure CC="cc" - -and if that doesn't work, try - - ./configure CC="cc -nodtk" - -Specifying the System Type -========================== - - There may be some features `configure' cannot figure out -automatically, but needs to determine by the type of machine the package -will run on. Usually, assuming the package is built to be run on the -_same_ architectures, `configure' can figure that out, but if it prints -a message saying it cannot guess the machine type, give it the -`--build=TYPE' option. TYPE can either be a short name for the system -type, such as `sun4', or a canonical name which has the form: - - CPU-COMPANY-SYSTEM - -where SYSTEM can have one of these forms: - - OS KERNEL-OS - - See the file `config.sub' for the possible values of each field. If -`config.sub' isn't included in this package, then this package doesn't -need to know the machine type. - - If you are _building_ compiler tools for cross-compiling, you should -use the option `--target=TYPE' to select the type of system they will -produce code for. - - If you want to _use_ a cross compiler, that generates code for a -platform different from the build platform, you should specify the -"host" platform (i.e., that on which the generated programs will -eventually be run) with `--host=TYPE'. - -Sharing Defaults -================ - - If you want to set default values for `configure' scripts to share, -you can create a site shell script called `config.site' that gives -default values for variables like `CC', `cache_file', and `prefix'. -`configure' looks for `PREFIX/share/config.site' if it exists, then -`PREFIX/etc/config.site' if it exists. Or, you can set the -`CONFIG_SITE' environment variable to the location of the site script. -A warning: not all `configure' scripts look for a site script. - -Defining Variables -================== - - Variables not defined in a site shell script can be set in the -environment passed to `configure'. However, some packages may run -configure again during the build, and the customized values of these -variables may be lost. In order to avoid this problem, you should set -them in the `configure' command line, using `VAR=value'. For example: - - ./configure CC=/usr/local2/bin/gcc - -causes the specified `gcc' to be used as the C compiler (unless it is -overridden in the site shell script). - -Unfortunately, this technique does not work for `CONFIG_SHELL' due to -an Autoconf bug. Until the bug is fixed you can use this workaround: - - CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash - -`configure' Invocation -====================== - - `configure' recognizes the following options to control how it -operates. - -`--help' -`-h' - Print a summary of all of the options to `configure', and exit. - -`--help=short' -`--help=recursive' - Print a summary of the options unique to this package's - `configure', and exit. The `short' variant lists options used - only in the top level, while the `recursive' variant lists options - also present in any nested packages. - -`--version' -`-V' - Print the version of Autoconf used to generate the `configure' - script, and exit. - -`--cache-file=FILE' - Enable the cache: use and save the results of the tests in FILE, - traditionally `config.cache'. FILE defaults to `/dev/null' to - disable caching. - -`--config-cache' -`-C' - Alias for `--cache-file=config.cache'. - -`--quiet' -`--silent' -`-q' - Do not print messages saying which checks are being made. To - suppress all normal output, redirect it to `/dev/null' (any error - messages will still be shown). - -`--srcdir=DIR' - Look for the package's source code in directory DIR. Usually - `configure' can determine that directory automatically. - -`--prefix=DIR' - Use DIR as the installation prefix. *Note Installation Names:: - for more details, including other options available for fine-tuning - the installation locations. - -`--no-create' -`-n' - Run the configure checks, but stop before creating any output - files. - -`configure' also accepts some other, not widely useful, options. Run -`configure --help' for more details. - diff --git a/p2pproxy/Makefile.am b/p2pproxy/Makefile.am deleted file mode 100644 index aaa51ae7..00000000 --- a/p2pproxy/Makefile.am +++ /dev/null @@ -1,19 +0,0 @@ -EXTRA_DIST=dependencies dependencies-src src test-src - -SUBDIRS=launcher plugin-src - -ALL_JARS= \ - $(top_builddir)/antbuild/dist/p2pproxy_0.1/bcprov-jdk14.jar $(top_builddir)/antbuild/dist/p2pproxy_0.1/log4j.jar \ - $(top_builddir)/antbuild/dist/p2pproxy_0.1/javax.servlet.jar $(top_builddir)/antbuild/dist/p2pproxy_0.1/org.mortbay.jetty.jar \ - $(top_builddir)/antbuild/dist/p2pproxy_0.1/jstun-0.7.0.jar $(top_builddir)/antbuild/dist/p2pproxy_0.1/p2pproxy.jar \ - $(top_builddir)/antbuild/dist/p2pproxy_0.1/junit-4.3.1.jar $(top_builddir)/antbuild/dist/p2pproxy_0.1/sip.jar - -$(ALL_JARS): src/org/linphone/p2pproxy/*/*.java - $(ANT) dist - -jarsdir=$(datadir)/java/fonis - -jars_DATA=$(ALL_JARS) - -clean-local: - $(ANT) clean diff --git a/p2pproxy/NEWS b/p2pproxy/NEWS deleted file mode 100644 index e69de29b..00000000 diff --git a/p2pproxy/README b/p2pproxy/README deleted file mode 100644 index e69de29b..00000000 diff --git a/p2pproxy/autogen.sh b/p2pproxy/autogen.sh deleted file mode 100755 index d342f286..00000000 --- a/p2pproxy/autogen.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/sh - -#AM_VERSION=1.10 -#1.9 was the recommended version -if test -n "$AM_VERSION" ; then - ACLOCAL=aclocal-${AM_VERSION} - AUTOMAKE=automake-${AM_VERSION} -else - ACLOCAL=aclocal - AUTOMAKE=automake -fi - -echo "Generating build scripts in this mediastreamer plugin" -set -x -libtoolize --copy --force -$ACLOCAL -$AUTOMAKE --force-missing --add-missing --copy -autoconf -rm -rf config.cache - diff --git a/p2pproxy/bin/p2pproxy-cmd.bat b/p2pproxy/bin/p2pproxy-cmd.bat deleted file mode 100644 index f1fc5f0c..00000000 --- a/p2pproxy/bin/p2pproxy-cmd.bat +++ /dev/null @@ -1,2 +0,0 @@ -@echo off -"%JAVA_HOME%\bin\java.exe" -cp p2pproxy.jar org.linphone.p2pproxy.core.utils.AccountManagerCli %1 %2 %3 %4 %5 %6 %7 %8 %9 \ No newline at end of file diff --git a/p2pproxy/bin/p2pproxy-cmd.sh b/p2pproxy/bin/p2pproxy-cmd.sh deleted file mode 100644 index 1598057d..00000000 --- a/p2pproxy/bin/p2pproxy-cmd.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -exec ${JAVA_HOME}/bin/java -cp p2pproxy.jar org.linphone.p2pproxy.core.utils.AccountManagerCli $* \ No newline at end of file diff --git a/p2pproxy/bin/p2pproxy.bat b/p2pproxy/bin/p2pproxy.bat deleted file mode 100644 index 21eaf933..00000000 --- a/p2pproxy/bin/p2pproxy.bat +++ /dev/null @@ -1,2 +0,0 @@ -@echo off -"%JAVA_HOME%\bin\java.exe" -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=6789 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -jar p2pproxy.jar %1 %2 %3 %4 %5 %6 %7 %8 %9 \ No newline at end of file diff --git a/p2pproxy/bin/p2pproxy.sh b/p2pproxy/bin/p2pproxy.sh deleted file mode 100644 index 91f31916..00000000 --- a/p2pproxy/bin/p2pproxy.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/sh -if [ -z "$P2P_JMX_PORT"] ; then - P2P_JMX_PORT=6789 -fi -exec ${JAVA_HOME}/bin/java -Dcom.sun.management.jmxremote \ - -Dcom.sun.management.jmxremote.port=${P2P_JMX_PORT} \ - -Dcom.sun.management.jmxremote.authenticate=false \ - -Dcom.sun.management.jmxremote.ssl=false \ - -jar p2pproxy.jar $* \ No newline at end of file diff --git a/p2pproxy/build.xml b/p2pproxy/build.xml deleted file mode 100644 index 02d3a759..00000000 --- a/p2pproxy/build.xml +++ /dev/null @@ -1,195 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/p2pproxy/configure.ac b/p2pproxy/configure.ac deleted file mode 100644 index fffaf614..00000000 --- a/p2pproxy/configure.ac +++ /dev/null @@ -1,134 +0,0 @@ -dnl Process this file with autoconf to produce a configure script. -AC_INIT([p2pproxy],[0.0.1]) - -AM_INIT_AUTOMAKE([tar-ustar]) - -AC_CANONICAL_SYSTEM - -AC_MSG_CHECKING([warning make an error on compilation]) -AC_ARG_ENABLE(strict, -[ --enable-strict Enable error on compilation warning [default=no]], -[wall_werror=$enableval], -[wall_werror=no] -) - - -dnl Checks for programs. -AC_PROG_CC -AC_PROG_LIBTOOL -AC_DISABLE_STATIC - - -CFLAGS="$CFLAGS -Wall" - - -dnl Checks for header files. -AC_HEADER_STDC - -dnl Checks for typedefs, structures, and compiler characteristics. -AC_C_CONST -AC_C_INLINE -AC_HEADER_TIME -AC_WORDS_BIGENDIAN -if test x$ac_cv_c_bigendian = xyes ; then - CFLAGS="$CFLAGS -D_BIGENDIAN" -fi - -if test $GCC = yes && test $wall_werror = yes; then - CFLAGS="$CFLAGS -Werror " -fi - -AC_ARG_WITH(java, - [ --with-java Sets directory of java home, [default=/usr/lib/jvm/java-6-sun] ], - [ javadir=${withval}],[javadir=/usr/lib/jvm/java-6-sun/]) - -AC_SUBST(javadir) - -AC_PATH_PROG(ANT,ant,false) - -AC_PATH_PROG(SWIG,swig,false) - -if test x$ANT = xfalse ; then - AC_MSG_ERROR([ant not found: you must install ant to build this package.]) -fi - -if test x$prefix = xNONE ; then - jarsdir="/usr/local/share/java/fonis" -else - jarsdir="$prefix/share/java/fonis" -fi - -AC_DEFINE_UNQUOTED(P2PPROXY_INSTALLDIR,"$jarsdir",[path of jars]) - -PKG_CHECK_MODULES(LIBLINPHONE, linphone >= 3.0.0) - -LINPHONE_PLUGINS_DIR="\$(libdir)/liblinphone/plugins/" -AC_SUBST(LINPHONE_PLUGINS_DIR) - -dnl ################################################## -dnl # Check for ESP Packager -dnl ################################################## - -AC_PATH_PROG(EPM,epm,false) -AC_PATH_PROG(MKEPMLIST,mkepmlist,false) -AC_PATH_PROG(EPMINSTALL,epminstall,false) -AM_CONDITIONAL(WITH_EPM,test $EPM != false && test $MKEPMLIST != false && test $EPMINSTALL != false) - - -# Preferred packaging system, as per EPM terminology -case $target in -*-*-linux*) - if test -f /etc/debian_version ; then - EPM_PKG_EXT=deb - else - EPM_PKG_EXT=rpm - fi - ;; -*-hp-hpux*) - EPM_PKG_EXT=depot.gz;; -*-dec-osf*) - EPM_PKG_EXT=setld;; -esac -AC_SUBST(EPM_PKG_EXT) - -# System software User & Group names -case $target in -*-*-linux*) - SYS_USER=root - SYS_GROUP=root - ;; -*-*-hpux*|*-dec-osf*) - SYS_USER=bin - SYS_GROUP=bin - ;; -esac -AC_SUBST(SYS_USER) -AC_SUBST(SYS_GROUP) - -# CPU Architecture -case $target_cpu in -i?86) ARCH=i386;; -*) ARCH=$target_cpu;; -esac -AC_SUBST(ARCH) - -# Various other packaging variables, that can be over-ridden ad `make -# package' time -SUMMARY="A SIP P2P proxy and toolkit" -AC_SUBST(SUMMARY) -PACKAGER=anonymous -AC_SUBST(PACKAGER) -LICENSE=GPL -AC_SUBST(LICENSE) -VENDOR=Linphone -AC_SUBST(VENDOR) -RELEASE=1 -AC_SUBST(RELEASE) - - -AC_OUTPUT( -Makefile -launcher/Makefile -launcher/src/Makefile -plugin-src/Makefile -) diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ChangeRequest.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ChangeRequest.java deleted file mode 100644 index bf83df66..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ChangeRequest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import de.javawi.jstun.util.*; - -public class ChangeRequest extends MessageAttribute { - /* - * 0 1 2 3 - * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A B 0| - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - */ - boolean changeIP = false; - boolean changePort = false; - - public ChangeRequest() { - super(MessageAttribute.MessageAttributeType.ChangeRequest); - } - - public boolean isChangeIP() { - return changeIP; - } - - public boolean isChangePort() { - return changePort; - } - - public void setChangeIP() { - changeIP = true; - } - - public void setChangePort() { - changePort = true; - } - - public byte[] getBytes() throws UtilityException { - byte[] result = new byte[8]; - // message attribute header - // type - System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); - // length - System.arraycopy(Utility.integerToTwoBytes(4), 0, result, 2, 2); - - // change request header - if (changeIP) result[7] = Utility.integerToOneByte(4); - if (changePort) result[7] = Utility.integerToOneByte(2); - if (changeIP && changePort) result[7] = Utility.integerToOneByte(6); - return result; - } - - public static ChangeRequest parse(byte[] data) throws MessageAttributeParsingException { - try { - if (data.length < 4) { - throw new MessageAttributeParsingException("Data array too short"); - } - ChangeRequest cr = new ChangeRequest(); - int status = Utility.oneByteToInteger(data[3]); - switch (status) { - case 0: break; - case 2: cr.setChangePort(); break; - case 4: cr.setChangeIP(); break; - case 6: cr.setChangeIP(); cr.setChangePort(); break; - default: throw new MessageAttributeParsingException("Status parsing error"); - } - return cr; - } catch (UtilityException ue) { - throw new MessageAttributeParsingException("Parsing error"); - } - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ChangedAddress.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ChangedAddress.java deleted file mode 100644 index ce06b603..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ChangedAddress.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import java.util.logging.Logger; - - -public class ChangedAddress extends MappedResponseChangedSourceAddressReflectedFrom { - private static Logger logger = Logger.getLogger("de.javawi.stun.attribute.ChangedAddress"); - - public ChangedAddress() { - super(MessageAttribute.MessageAttributeType.ChangedAddress); - } - - public static MessageAttribute parse(byte[] data) throws MessageAttributeParsingException { - ChangedAddress ca = new ChangedAddress(); - MappedResponseChangedSourceAddressReflectedFrom.parse(ca, data); - logger.finer("Message Attribute: Changed Address parsed: " + ca.toString() + "."); - return ca; - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Data.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Data.java deleted file mode 100644 index 71452ad2..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Data.java +++ /dev/null @@ -1,20 +0,0 @@ -package de.javawi.jstun.attribute; - -import java.util.logging.Logger; - -import de.javawi.jstun.util.UtilityException; - -public class Data extends MessageAttribute { - private static Logger logger = Logger.getLogger(Data.class.getName()); - @Override - public byte[] getBytes() throws UtilityException { - // TODO Auto-generated method stub - return null; - } - public static MessageAttribute parse(byte[] data) throws MessageAttributeParsingException { - Data ma = new Data(); - - logger.finer("Message Attribute: Data Address parsed: " + ma.toString() + "."); - return ma; - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Dummy.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Dummy.java deleted file mode 100644 index 8e780dcc..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Dummy.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import de.javawi.jstun.util.Utility; -import de.javawi.jstun.util.UtilityException; - -public class Dummy extends MessageAttribute { - int lengthValue; - public Dummy() { - super(MessageAttributeType.Dummy); - } - - public void setLengthValue(int length) { - this.lengthValue = length; - } - - public byte[] getBytes() throws UtilityException { - byte[] result = new byte[lengthValue + 4]; - // message attribute header - // type - System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); - // length - System.arraycopy(Utility.integerToTwoBytes(lengthValue), 0, result, 2, 2); - return result; - } - - public static Dummy parse(byte[] data) { - Dummy dummy = new Dummy(); - dummy.setLengthValue(data.length); - return dummy; - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ErrorCode.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ErrorCode.java deleted file mode 100644 index 04436dd7..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ErrorCode.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import de.javawi.jstun.util.Utility; -import de.javawi.jstun.util.UtilityException; - -public class ErrorCode extends MessageAttribute { - /* - * 0 1 2 3 - * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | 0 |Class| Number | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | Reason Phrase (variable) .. - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - */ - - int responseCode; - String reason; - - public ErrorCode() { - super(MessageAttribute.MessageAttributeType.ErrorCode); - } - - public void setResponseCode(int responseCode) throws MessageAttributeException { - switch (responseCode) { - case 400: reason = "Bad Request"; break; - case 401: reason = "Unauthorized"; break; - case 420: reason = "Unkown Attribute"; break; - case 430: reason = "Stale Credentials"; break; - case 431: reason = "Integrity Check Failure"; break; - case 432: reason = "Missing Username"; break; - case 433: reason = "Use TLS"; break; - case 500: reason = "Server Error"; break; - case 600: reason = "Global Failure"; break; - default: throw new MessageAttributeException("Response Code is not valid"); - } - this.responseCode = responseCode; - } - - public int getResponseCode() { - return responseCode; - } - - public String getReason() { - return reason; - } - - public byte[] getBytes() throws UtilityException { - int length = reason.length(); - // length adjustment - if ((length % 4) != 0) { - length += 4 - (length % 4); - } - // message attribute header - length += 4; - byte[] result = new byte[length]; - // message attribute header - // type - System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); - // length - System.arraycopy(Utility.integerToTwoBytes(length-4), 0, result, 2, 2); - - // error code header - int classHeader = (int) Math.floor(((double)responseCode)/100); - result[6] = Utility.integerToOneByte(classHeader); - result[7] = Utility.integerToOneByte(responseCode%100); - byte[] reasonArray = reason.getBytes(); - System.arraycopy(reasonArray, 0, result, 8, reasonArray.length); - return result; - } - - public static ErrorCode parse(byte[] data) throws MessageAttributeParsingException { - try { - if (data.length < 4) { - throw new MessageAttributeParsingException("Data array too short"); - } - byte classHeaderByte = data[3]; - int classHeader = Utility.oneByteToInteger(classHeaderByte); - if ((classHeader < 1) || (classHeader > 6)) throw new MessageAttributeParsingException("Class parsing error"); - byte numberByte = data[4]; - int number = Utility.oneByteToInteger(numberByte); - if ((number < 0) || (number > 99)) throw new MessageAttributeParsingException("Number parsing error"); - int responseCode = (classHeader * 100) + number; - ErrorCode result = new ErrorCode(); - result.setResponseCode(responseCode); - return result; - } catch (UtilityException ue) { - throw new MessageAttributeParsingException("Parsing error"); - } catch (MessageAttributeException mae) { - throw new MessageAttributeParsingException("Parsing error"); - } - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MappedAddress.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MappedAddress.java deleted file mode 100644 index bdb84acf..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MappedAddress.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import java.util.logging.Logger; - - -public class MappedAddress extends MappedResponseChangedSourceAddressReflectedFrom { - private static Logger logger = Logger.getLogger("de.javawi.stun.attribute.MappedAddress"); - public MappedAddress() { - super(MessageAttribute.MessageAttributeType.MappedAddress); - } - - public static MessageAttribute parse(byte[] data) throws MessageAttributeParsingException { - MappedAddress ma = new MappedAddress(); - MappedResponseChangedSourceAddressReflectedFrom.parse(ma, data); - logger.finer("Message Attribute: Mapped Address parsed: " + ma.toString() + "."); - return ma; - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MappedResponseChangedSourceAddressReflectedFrom.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MappedResponseChangedSourceAddressReflectedFrom.java deleted file mode 100644 index 252e9605..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MappedResponseChangedSourceAddressReflectedFrom.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import de.javawi.jstun.util.*; - -public class MappedResponseChangedSourceAddressReflectedFrom extends MessageAttribute { - int port; - Address address; - - /* - * 0 1 2 3 - * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * |x x x x x x x x| Family | Port | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | Address | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - */ - public MappedResponseChangedSourceAddressReflectedFrom() { - super(); - try { - port = 0; - address = new Address("0.0.0.0"); - } catch (UtilityException ue) { - ue.getMessage(); - ue.printStackTrace(); - } - } - - public MappedResponseChangedSourceAddressReflectedFrom(MessageAttribute.MessageAttributeType type) { - super(type); - } - - public int getPort() { - return port; - } - - public Address getAddress() { - return address; - } - - public void setPort(int port) throws MessageAttributeException { - if ((port > 65536) || (port < 0)) { - throw new MessageAttributeException("Port value " + port + " out of range."); - } - this.port = port; - } - - public void setAddress(Address address) { - this.address = address; - } - - public byte[] getBytes() throws UtilityException { - byte[] result = new byte[12]; - // message attribute header - // type - System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); - // length - System.arraycopy(Utility.integerToTwoBytes(8), 0, result, 2, 2); - - // mappedaddress header - // family - result[5] = Utility.integerToOneByte(0x01); - // port - System.arraycopy(Utility.integerToTwoBytes(port), 0, result, 6, 2); - // address - System.arraycopy(address.getBytes(), 0, result, 8, 4); - return result; - } - - protected static MappedResponseChangedSourceAddressReflectedFrom parse(MappedResponseChangedSourceAddressReflectedFrom ma, byte[] data) throws MessageAttributeParsingException { - try { - if (data.length < 8) { - throw new MessageAttributeParsingException("Data array too short"); - } - int family = Utility.oneByteToInteger(data[1]); - if (family != 0x01) throw new MessageAttributeParsingException("Family " + family + " is not supported"); - byte[] portArray = new byte[2]; - System.arraycopy(data, 2, portArray, 0, 2); - ma.setPort(Utility.twoBytesToInteger(portArray)); - int firstOctet = Utility.oneByteToInteger(data[4]); - int secondOctet = Utility.oneByteToInteger(data[5]); - int thirdOctet = Utility.oneByteToInteger(data[6]); - int fourthOctet = Utility.oneByteToInteger(data[7]); - ma.setAddress(new Address(firstOctet, secondOctet, thirdOctet, fourthOctet)); - return ma; - } catch (UtilityException ue) { - throw new MessageAttributeParsingException("Parsing error"); - } catch (MessageAttributeException mae) { - throw new MessageAttributeParsingException("Port parsing error"); - } - } - - public String toString() { - return "Address " +address.toString() + ", Port " + port; - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttribute.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttribute.java deleted file mode 100644 index 2c1f1ef7..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttribute.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import java.util.logging.*; - -import de.javawi.jstun.util.*; - - -public abstract class MessageAttribute implements MessageAttributeInterface { - private static Logger logger = Logger.getLogger("de.javawi.stun.util.MessageAttribute"); - MessageAttributeType type; - - public MessageAttribute() { - } - - public MessageAttribute(MessageAttributeType type) { - setType(type); - } - - public void setType(MessageAttributeType type) { - this.type = type; - } - - public MessageAttribute.MessageAttributeType getType() { - return type; - } - - public static int typeToInteger(MessageAttributeType type) { - if (type == MessageAttributeType.MappedAddress) return MAPPEDADDRESS; - if (type == MessageAttributeType.ResponseAddress) return RESPONSEADDRESS; - if (type == MessageAttributeType.ChangeRequest) return CHANGEREQUEST; - if (type == MessageAttributeType.SourceAddress) return SOURCEADDRESS; - if (type == MessageAttributeType.ChangedAddress) return CHANGEDADDRESS; - if (type == MessageAttributeType.Username) return USERNAME; - if (type == MessageAttributeType.Password) return PASSWORD; - if (type == MessageAttributeType.MessageIntegrity) return MESSAGEINTEGRITY; - if (type == MessageAttributeType.ErrorCode) return ERRORCODE; - if (type == MessageAttributeType.UnknownAttribute) return UNKNOWNATTRIBUTE; - if (type == MessageAttributeType.ReflectedFrom) return REFLECTEDFROM; - if (type == MessageAttributeType.Dummy) return DUMMY; - //turn - if (type == MessageAttributeType.ChannelNumber) return CHANNELNUMBER; - if (type == MessageAttributeType.LifeTime) return LIFETIME; - if (type == MessageAttributeType.Bandwidth ) return BANDWIDTH; - if (type == MessageAttributeType.PeerAddress ) return PEERADDRESS; - if (type == MessageAttributeType.Data ) return DATA; - if (type == MessageAttributeType.RelayAddress ) return RELAYADDRESS; - if (type == MessageAttributeType.RequestedProps ) return REQUESTEDPROPS; - if (type == MessageAttributeType.RequestedTransport ) return REQUESTEDTRANSPORT; - if (type == MessageAttributeType.ReservationToken ) return RESERVATIONTOKEN; - return -1; - } - - public static MessageAttributeType intToType(long type) { - if (type == MAPPEDADDRESS) return MessageAttributeType.MappedAddress; - if (type == RESPONSEADDRESS) return MessageAttributeType.ResponseAddress; - if (type == CHANGEREQUEST) return MessageAttributeType.ChangeRequest; - if (type == SOURCEADDRESS) return MessageAttributeType.SourceAddress; - if (type == CHANGEDADDRESS) return MessageAttributeType.ChangedAddress; - if (type == USERNAME) return MessageAttributeType.Username; - if (type == PASSWORD) return MessageAttributeType.Password; - if (type == MESSAGEINTEGRITY) return MessageAttributeType.MessageIntegrity; - if (type == ERRORCODE) return MessageAttributeType.ErrorCode; - if (type == UNKNOWNATTRIBUTE) return MessageAttributeType.UnknownAttribute; - if (type == REFLECTEDFROM) return MessageAttributeType.ReflectedFrom; - if (type == DUMMY) return MessageAttributeType.Dummy; - //turn - if (type == CHANNELNUMBER) return MessageAttributeType.ChannelNumber; - if (type == LIFETIME) return MessageAttributeType.LifeTime; - if (type == BANDWIDTH) return MessageAttributeType.Bandwidth; - if (type == PEERADDRESS) return MessageAttributeType.PeerAddress; - if (type == DATA) return MessageAttributeType.Data; - if (type == RELAYADDRESS) return MessageAttributeType.RelayAddress; - if (type == REQUESTEDPROPS) return MessageAttributeType.RequestedProps; - if (type == REQUESTEDTRANSPORT) return MessageAttributeType.RequestedTransport; - if (type == RESERVATIONTOKEN) return MessageAttributeType.ReservationToken; - return null; - } - - abstract public byte[] getBytes() throws UtilityException; - //abstract public MessageAttribute parse(byte[] data) throws MessageAttributeParsingException; - - public int getLength() throws UtilityException { - int length = getBytes().length; - return length; - } - - public static MessageAttribute parseCommonHeader(byte[] data) throws MessageAttributeParsingException { - try { - byte[] typeArray = new byte[2]; - System.arraycopy(data, 0, typeArray, 0, 2); - int type = Utility.twoBytesToInteger(typeArray); - byte[] lengthArray = new byte[2]; - System.arraycopy(data, 2, lengthArray, 0, 2); - int lengthValue = Utility.twoBytesToInteger(lengthArray); - byte[] valueArray = new byte[lengthValue]; - System.arraycopy(data, 4, valueArray, 0, lengthValue); - MessageAttribute ma; - switch (type) { - case MAPPEDADDRESS: ma = MappedAddress.parse(valueArray); break; - case RESPONSEADDRESS: ma = ResponseAddress.parse(valueArray); break; - case CHANGEREQUEST: ma = ChangeRequest.parse(valueArray); break; - case SOURCEADDRESS: ma = SourceAddress.parse(valueArray); break; - case CHANGEDADDRESS: ma = ChangedAddress.parse(valueArray); break; - case USERNAME: ma = Username.parse(valueArray); break; - case PASSWORD: ma = Password.parse(valueArray); break; - case MESSAGEINTEGRITY: ma = MessageIntegrity.parse(valueArray); break; - case ERRORCODE: ma = ErrorCode.parse(valueArray); break; - case UNKNOWNATTRIBUTE: ma = UnknownAttribute.parse(valueArray); break; - case REFLECTEDFROM: ma = ReflectedFrom.parse(valueArray); break; - default: - if (type <= 0x7fff) { - throw new UnknownMessageAttributeException("Unkown mandatory message attribute", intToType(type)); - } else { - logger.finer("MessageAttribute with type " + type + " unkown."); - ma = Dummy.parse(valueArray); - break; - } - } - return ma; - } catch (UtilityException ue) { - throw new MessageAttributeParsingException("Parsing error"); - } - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttributeException.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttributeException.java deleted file mode 100644 index a8109cfd..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttributeException.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -public class MessageAttributeException extends Exception { - private static final long serialVersionUID = 3258131345099404850L; - - public MessageAttributeException(String mesg) { - super(mesg); - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttributeInterface.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttributeInterface.java deleted file mode 100644 index 8c55d780..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttributeInterface.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -public interface MessageAttributeInterface { - public enum MessageAttributeType { MappedAddress - , ResponseAddress - , ChangeRequest - , SourceAddress - , ChangedAddress - , Username - , Password - , MessageIntegrity - , ErrorCode - , UnknownAttribute - , ReflectedFrom - , Dummy - , ChannelNumber - , LifeTime - , Bandwidth - , PeerAddress - , Data - , RelayAddress - , RequestedProps - , RequestedTransport - , ReservationToken}; - final static int MAPPEDADDRESS = 0x0001; - final static int RESPONSEADDRESS = 0x0002; - final static int CHANGEREQUEST = 0x0003; - final static int SOURCEADDRESS = 0x0004; - final static int CHANGEDADDRESS = 0x0005; - final static int USERNAME = 0x0006; - final static int PASSWORD = 0x0007; - final static int MESSAGEINTEGRITY = 0x0008; - final static int ERRORCODE = 0x0009; - final static int UNKNOWNATTRIBUTE = 0x000a; - final static int REFLECTEDFROM = 0x000b; - final static int DUMMY = 0x0000; -// turn attributes -// 0x000C: CHANNEL-NUMBER -// 0x000D: LIFETIME -// 0x0010: BANDWIDTH -// 0x0012: PEER-ADDRESS -// 0x0013: DATA -// 0x0016: RELAY-ADDRESS -// 0x0018: REQUESTED-PROPS -// 0x0019: REQUESTED-TRANSPORT -// 0x0022: RESERVATION-TOKEN - final static int CHANNELNUMBER = 0x000C; - final static int LIFETIME = 0x000D; - final static int BANDWIDTH = 0x0010; - final static int PEERADDRESS = 0x0012; - final static int DATA = 0x0013; - final static int RELAYADDRESS = 0x0016; - final static int REQUESTEDPROPS = 0x0018; - final static int REQUESTEDTRANSPORT = 0x0019; - final static int RESERVATIONTOKEN = 0x0022; - -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttributeParsingException.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttributeParsingException.java deleted file mode 100644 index d2027897..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageAttributeParsingException.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -public class MessageAttributeParsingException extends MessageAttributeException { - private static final long serialVersionUID = 3258409534426263605L; - - public MessageAttributeParsingException(String mesg) { - super(mesg); - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageIntegrity.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageIntegrity.java deleted file mode 100644 index 7aa7df3d..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/MessageIntegrity.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -public class MessageIntegrity extends MessageAttribute { - // incomplete message integrity implementation - public MessageIntegrity() { - super(MessageAttribute.MessageAttributeType.MessageIntegrity); - } - - public byte[] getBytes() { - return new byte[0]; - } - - public static MessageIntegrity parse(byte[] data) { - return new MessageIntegrity(); - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Password.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Password.java deleted file mode 100644 index 679a193d..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Password.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import de.javawi.jstun.util.Utility; -import de.javawi.jstun.util.UtilityException; - -public class Password extends MessageAttribute { - String password; - - public Password() { - super(MessageAttribute.MessageAttributeType.Password); - } - - public Password(String password) { - super(MessageAttribute.MessageAttributeType.Password); - setPassword(password); - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public byte[] getBytes() throws UtilityException { - int length = password.length(); - // password header - if ((length % 4) != 0) { - length += 4 - (length % 4); - } - // message attribute header - length += 4; - byte[] result = new byte[length]; - // message attribute header - // type - System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); - // length - System.arraycopy(Utility.integerToTwoBytes(length - 4), 0, result, 2, 2); - - // password header - byte[] temp = password.getBytes(); - System.arraycopy(temp, 0, result, 4, temp.length); - return result; - } - - public static Password parse(byte[] data) { - Password result = new Password(); - String password = new String(data); - result.setPassword(password); - return result; - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ReflectedFrom.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ReflectedFrom.java deleted file mode 100644 index e2983143..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ReflectedFrom.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import java.util.logging.Logger; - -public class ReflectedFrom extends MappedResponseChangedSourceAddressReflectedFrom { - private static Logger logger = Logger.getLogger("de.javawi.stun.attribute.ReflectedFrom"); - - public ReflectedFrom() { - super(MessageAttribute.MessageAttributeType.ReflectedFrom); - } - - public static ReflectedFrom parse(byte[] data) throws MessageAttributeParsingException { - ReflectedFrom result = new ReflectedFrom(); - MappedResponseChangedSourceAddressReflectedFrom.parse(result, data); - logger.finer("Message Attribute: ReflectedFrom parsed: " + result.toString() + "."); - return result; - } - - -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ResponseAddress.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ResponseAddress.java deleted file mode 100644 index 40c73bd0..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/ResponseAddress.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import java.util.logging.Logger; - - -public class ResponseAddress extends MappedResponseChangedSourceAddressReflectedFrom { - private static Logger logger = Logger.getLogger("de.javawi.stun.attribute.ResponseAddress"); - public ResponseAddress() { - super(MessageAttribute.MessageAttributeType.ResponseAddress); - } - - public static MessageAttribute parse(byte[] data) throws MessageAttributeParsingException { - ResponseAddress ra = new ResponseAddress(); - MappedResponseChangedSourceAddressReflectedFrom.parse(ra, data); - logger.finer("Message Attribute: Response Address parsed: " + ra.toString() + "."); - return ra; - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/SourceAddress.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/SourceAddress.java deleted file mode 100644 index 070d7d8d..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/SourceAddress.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import java.util.logging.Logger; - - -public class SourceAddress extends MappedResponseChangedSourceAddressReflectedFrom { - private static Logger logger = Logger.getLogger("de.javawi.stun.attribute.SourceAddress"); - public SourceAddress() { - super(MessageAttribute.MessageAttributeType.SourceAddress); - } - - public static MessageAttribute parse(byte[] data) throws MessageAttributeParsingException { - SourceAddress sa = new SourceAddress(); - MappedResponseChangedSourceAddressReflectedFrom.parse(sa, data); - logger.finer("Message Attribute: Source Address parsed: " + sa.toString() + "."); - return sa; - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/UnknownAttribute.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/UnknownAttribute.java deleted file mode 100644 index 04f1abb8..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/UnknownAttribute.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import java.util.*; - -import de.javawi.jstun.util.Utility; -import de.javawi.jstun.util.UtilityException; - -public class UnknownAttribute extends MessageAttribute { - /* - * 0 1 2 3 - * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | Attribute 1 Type | Attribute 2 Type | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | Attribute 3 Type | Attribute 4 Type ... - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - */ - - Vector unkown = new Vector(); - - public UnknownAttribute() { - super(MessageAttribute.MessageAttributeType.UnknownAttribute); - } - - public void addAttribute(MessageAttributeType attribute) { - unkown.add(attribute); - } - - public byte[] getBytes() throws UtilityException { - int length = 0; - if (unkown.size()%2 == 1) { - length = 2 * (unkown.size() + 1) + 4; - } else { - length = 2 * unkown.size() + 4; - } - byte[] result = new byte[length]; - // message attribute header - // type - System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); - // length - System.arraycopy(Utility.integerToTwoBytes(length - 4), 0, result, 2, 2); - - // unkown attribute header - Iterator it = unkown.iterator(); - while(it.hasNext()) { - MessageAttributeType attri = it.next(); - System.arraycopy(Utility.integerToTwoBytes(typeToInteger(attri)), 0, result, 4, 2); - } - // padding - if (unkown.size()%2 == 1) { - System.arraycopy(Utility.integerToTwoBytes(typeToInteger(unkown.elementAt(1))), 0, result, 4, 2); - } - return result; - } - - public static UnknownAttribute parse(byte[] data) throws MessageAttributeParsingException { - try { - UnknownAttribute result = new UnknownAttribute(); - if (data.length % 4 != 0) throw new MessageAttributeParsingException("Data array too short"); - for (int i = 0; i < data.length; i += 4) { - byte[] temp = new byte[4]; - System.arraycopy(data, i, temp, 0, 4); - long attri = Utility.fourBytesToLong(temp); - result.addAttribute(MessageAttribute.intToType(attri)); - } - return result; - } catch (UtilityException ue) { - throw new MessageAttributeParsingException("Parsing error"); - } - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/UnknownMessageAttributeException.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/UnknownMessageAttributeException.java deleted file mode 100644 index 4ddd4922..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/UnknownMessageAttributeException.java +++ /dev/null @@ -1,18 +0,0 @@ -package de.javawi.jstun.attribute; - -import de.javawi.jstun.attribute.MessageAttributeInterface.MessageAttributeType; - -public class UnknownMessageAttributeException extends MessageAttributeParsingException { - private static final long serialVersionUID = 5375193544145543299L; - - private MessageAttributeType type; - - public UnknownMessageAttributeException(String mesg, MessageAttributeType type) { - super(mesg); - this.type = type; - } - - public MessageAttributeType getType() { - return type; - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Username.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Username.java deleted file mode 100644 index 1afaec7b..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/attribute/Username.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.attribute; - -import de.javawi.jstun.util.Utility; -import de.javawi.jstun.util.UtilityException; - -public class Username extends MessageAttribute { - String username; - - public Username() { - super(MessageAttribute.MessageAttributeType.Username); - } - - public Username(String username) { - super(MessageAttribute.MessageAttributeType.Username); - setUsername(username); - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public byte[] getBytes() throws UtilityException { - int length = username.length(); - // username header - if ((length % 4) != 0) { - length += 4 - (length % 4); - } - // message attribute header - length += 4; - byte[] result = new byte[length]; - // message attribute header - // type - System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); - // length - System.arraycopy(Utility.integerToTwoBytes(length-4), 0, result, 2, 2); - - // username header - byte[] temp = username.getBytes(); - System.arraycopy(temp, 0, result, 4, temp.length); - return result; - } - - public static Username parse(byte[] data) { - Username result = new Username(); - String username = new String(data); - result.setUsername(username); - return result; - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeader.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeader.java deleted file mode 100644 index 1e6dab58..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeader.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.header; - -import de.javawi.jstun.attribute.*; -import de.javawi.jstun.util.*; - -import java.util.*; -import java.util.logging.*; - -public class MessageHeader implements MessageHeaderInterface { - /* - * 0 1 2 3 - * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | STUN Message Type | Message Length | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * Transaction ID - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - */ - private static Logger logger = Logger.getLogger("de.javawi.stun.header.MessageHeader"); - MessageHeaderType type; - byte[] id = new byte[16]; - - TreeMap ma = new TreeMap(); - - public MessageHeader() { - super(); - } - - public MessageHeader(MessageHeaderType type) { - super(); - setType(type); - } - - public void setType(MessageHeaderType type) { - this.type = type; - } - - public MessageHeaderType getType() { - return type; - } - - public static int typeToInteger(MessageHeaderType type) { - if (type == MessageHeaderType.BindingRequest) return BINDINGREQUEST; - if (type == MessageHeaderType.BindingResponse) return BINDINGRESPONSE; - if (type == MessageHeaderType.BindingErrorResponse) return BINDINGERRORRESPONSE; - if (type == MessageHeaderType.SharedSecretRequest) return SHAREDSECRETREQUEST; - if (type == MessageHeaderType.SharedSecretResponse) return SHAREDSECRETRESPONSE; - if (type == MessageHeaderType.SharedSecretErrorResponse) return SHAREDSECRETERRORRESPONSE; - //turn headers - if (type == MessageHeaderType.AllocateRequest) return ALLOCATEREQUEST; - if (type == MessageHeaderType.AllocateResponse) return ALLOCATERESPONSE; - if (type == MessageHeaderType.AllocateErrorResponse) return ALLOCATEERRORRESPONSE; - if (type == MessageHeaderType.RefreshRequest) return REFRESHREQUEST; - if (type == MessageHeaderType.RefreshResponse) return REFRESHRESPONSE; - if (type == MessageHeaderType.RefreshErrorResponse) return REFRESHERRORRESPONSE; - if (type == MessageHeaderType.ChannelBindRequest) return CHANNELBINDREQUEST; - if (type == MessageHeaderType.ChannelBindResponse) return CHANNELBINDRESPONSE; - if (type == MessageHeaderType.ChannelBindErrorResponse) return CHANNELBINDERRORRESPONSE; - - - return -1; - } - - public void setTransactionID(byte[] id) { - System.arraycopy(id, 0, this.id, 0, 16); - } - - public void generateTransactionID() throws UtilityException { - System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 0, 2); - System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 2, 2); - System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 4, 2); - System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 6, 2); - System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 8, 2); - System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 10, 2); - System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 12, 2); - System.arraycopy(Utility.integerToTwoBytes((int)(Math.random() * 65536)), 0, id, 14, 2); - } - - public byte[] getTransactionID() { - byte[] idCopy = new byte[id.length]; - System.arraycopy(id, 0, idCopy, 0, id.length); - return idCopy; - } - - public boolean equalTransactionID(MessageHeader header) { - byte[] idHeader = header.getTransactionID(); - if (idHeader.length != 16) return false; - if ((idHeader[0] == id[0]) && (idHeader[1] == id[1]) && (idHeader[2] == id[2]) && (idHeader[3] == id[3]) && - (idHeader[4] == id[4]) && (idHeader[5] == id[5]) && (idHeader[6] == id[6]) && (idHeader[7] == id[7]) && - (idHeader[8] == id[8]) && (idHeader[9] == id[9]) && (idHeader[10] == id[10]) && (idHeader[11] == id[11]) && - (idHeader[12] == id[12]) && (idHeader[13] == id[13]) && (idHeader[14] == id[14]) && (idHeader[15] == id[15])) { - return true; - } else { - return false; - } - } - - public void addMessageAttribute(MessageAttribute attri) { - ma.put(attri.getType(), attri); - } - - public MessageAttribute getMessageAttribute(MessageAttribute.MessageAttributeType type) { - return ma.get(type); - } - - public byte[] getBytes() throws UtilityException { - int length = 20; - Iterator it = ma.keySet().iterator(); - while (it.hasNext()) { - MessageAttribute attri = ma.get(it.next()); - length += attri.getLength(); - } - // add attribute size + attributes.getSize(); - byte[] result = new byte[length]; - System.arraycopy(Utility.integerToTwoBytes(typeToInteger(type)), 0, result, 0, 2); - System.arraycopy(Utility.integerToTwoBytes(length-20), 0, result, 2, 2); - System.arraycopy(id, 0, result, 4, 16); - - // arraycopy of attributes - int offset = 20; - it = ma.keySet().iterator(); - while (it.hasNext()) { - MessageAttribute attri = ma.get(it.next()); - System.arraycopy(attri.getBytes(), 0, result, offset, attri.getLength()); - offset += attri.getLength(); - } - return result; - } - - public int getLength() throws UtilityException { - return getBytes().length; - } - - public void parseAttributes(byte[] data) throws MessageAttributeParsingException { - try { - byte[] lengthArray = new byte[2]; - System.arraycopy(data, 2, lengthArray, 0, 2); - int length = Utility.twoBytesToInteger(lengthArray); - System.arraycopy(data, 4, id, 0, 16); - byte[] cuttedData; - int offset = 20; - while (length > 0) { - cuttedData = new byte[length]; - System.arraycopy(data, offset, cuttedData, 0, length); - MessageAttribute ma = MessageAttribute.parseCommonHeader(cuttedData); - addMessageAttribute(ma); - length -= ma.getLength(); - offset += ma.getLength(); - } - } catch (UtilityException ue) { - throw new MessageAttributeParsingException("Parsing error"); - } - } - - public static MessageHeader parseHeader(byte[] data) throws MessageHeaderParsingException { - try { - MessageHeader mh = new MessageHeader(); - byte[] typeArray = new byte[2]; - System.arraycopy(data, 0, typeArray, 0, 2); - int type = Utility.twoBytesToInteger(typeArray); - switch (type) { - case BINDINGREQUEST: mh.setType(MessageHeaderType.BindingRequest); logger.finer("Binding Request received."); break; - case BINDINGRESPONSE: mh.setType(MessageHeaderType.BindingResponse); logger.finer("Binding Response received."); break; - case BINDINGERRORRESPONSE: mh.setType(MessageHeaderType.BindingErrorResponse); logger.finer("Binding Error Response received."); break; - case SHAREDSECRETREQUEST: mh.setType(MessageHeaderType.SharedSecretRequest); logger.finer("Shared Secret Request received."); break; - case SHAREDSECRETRESPONSE: mh.setType(MessageHeaderType.SharedSecretResponse); logger.finer("Shared Secret Response received."); break; - case SHAREDSECRETERRORRESPONSE: mh.setType(MessageHeaderType.SharedSecretErrorResponse); logger.finer("Shared Secret Error Response received.");break; - //turn - case ALLOCATEREQUEST: mh.setType(MessageHeaderType.AllocateRequest); logger.finer("Allocate Request received."); break; - case ALLOCATERESPONSE: mh.setType(MessageHeaderType.AllocateResponse); logger.finer("Allocate Response received."); break; - case ALLOCATEERRORRESPONSE: mh.setType(MessageHeaderType.AllocateErrorResponse); logger.finer("Allocate Errro received."); break; - case REFRESHREQUEST: mh.setType(MessageHeaderType.RefreshRequest); logger.finer("Refresh Request received."); break; - case REFRESHRESPONSE: mh.setType(MessageHeaderType.RefreshResponse); logger.finer("Refresh Response received."); break; - case REFRESHERRORRESPONSE: mh.setType(MessageHeaderType.RefreshErrorResponse); logger.finer("Refresh Error received."); break; - case CHANNELBINDREQUEST: mh.setType(MessageHeaderType.ChannelBindRequest); logger.finer("ChannelBind Request received."); break; - case CHANNELBINDRESPONSE: mh.setType(MessageHeaderType.ChannelBindResponse); logger.finer("ChannelBind Response received."); break; - case CHANNELBINDERRORRESPONSE: mh.setType(MessageHeaderType.ChannelBindErrorResponse); logger.finer("ChannelBind Error received."); break; - default: throw new MessageHeaderParsingException("Message type " + type + "is not supported"); - } - return mh; - } catch (UtilityException ue) { - throw new MessageHeaderParsingException("Parsing error"); - } - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeaderException.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeaderException.java deleted file mode 100644 index f4a9fa49..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeaderException.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.header; - -public class MessageHeaderException extends Exception { - private static final long serialVersionUID = 3689066248944103737L; - - public MessageHeaderException(String mesg) { - super(mesg); - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeaderInterface.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeaderInterface.java deleted file mode 100644 index 1b7a2cfe..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeaderInterface.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.header; - -public interface MessageHeaderInterface { - public enum MessageHeaderType { BindingRequest - , BindingResponse - , BindingErrorResponse - , SharedSecretRequest - , SharedSecretResponse - , SharedSecretErrorResponse - , AllocateRequest - , AllocateResponse - , AllocateErrorResponse - , RefreshRequest - , RefreshResponse - , RefreshErrorResponse - , ChannelBindRequest - , ChannelBindResponse - , ChannelBindErrorResponse - ,SendIndication - ,DataIndication}; - final static int BINDINGREQUEST = 0x0001; - final static int BINDINGRESPONSE = 0x0101; - final static int BINDINGERRORRESPONSE = 0x0111; - final static int SHAREDSECRETREQUEST = 0x0002; - final static int SHAREDSECRETRESPONSE = 0x0102; - final static int SHAREDSECRETERRORRESPONSE = 0x0112; - -// TURN defines ten new Message Types: -//Request/Response Transactions -//0x003 : Allocate -//0x004 : Refresh -//0x009 : ChannelBind -//0x006 : Send -//0x007 : Data - - - final static int ALLOCATEREQUEST = 0x0003; - final static int ALLOCATERESPONSE = 0x0103; - final static int ALLOCATEERRORRESPONSE = 0x0113; - final static int REFRESHREQUEST = 0x0004; - final static int REFRESHRESPONSE = 0x0104; - final static int REFRESHERRORRESPONSE = 0x0114; - final static int CHANNELBINDREQUEST = 0x0009; - final static int CHANNELBINDRESPONSE = 0x0109; - final static int CHANNELBINDERRORRESPONSE = 0x0119; - final static int SENDINDICATION = 0x0006; - final static int DATAINDICATION = 0x0007; - - -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeaderParsingException.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeaderParsingException.java deleted file mode 100644 index d5192ef2..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/header/MessageHeaderParsingException.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.header; - -public class MessageHeaderParsingException extends MessageHeaderException { - private static final long serialVersionUID = 3544393617029607478L; - - public MessageHeaderParsingException(String mesg) { - super(mesg); - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/BindingLifetimeTest.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/BindingLifetimeTest.java deleted file mode 100644 index 1dca91b4..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/BindingLifetimeTest.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.test; - -import java.util.logging.*; -import java.util.*; -import java.io.*; -import java.net.*; - -import de.javawi.jstun.attribute.*; -import de.javawi.jstun.header.*; -import de.javawi.jstun.util.UtilityException; - -public class BindingLifetimeTest { - private static Logger logger = Logger.getLogger("de.javawi.stun.test.BindingLifetimeTest"); - String stunServer; - int port; - int timeout = 300; //ms - MappedAddress ma; - Timer timer; - DatagramSocket initialSocket; - - // start value for binary search - should be carefully choosen - int upperBinarySearchLifetime = 345000; // ms - int lowerBinarySearchLifetime = 0; - int binarySearchLifetime = ( upperBinarySearchLifetime + lowerBinarySearchLifetime ) / 2; - - // lifetime value - int lifetime = -1; // -1 means undefined. - boolean completed = false; - - public BindingLifetimeTest(String stunServer, int port) { - super(); - this.stunServer = stunServer; - this.port = port; - timer = new Timer(true); - } - - public void test() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException { - initialSocket = new DatagramSocket(); - initialSocket.connect(InetAddress.getByName(stunServer), port); - initialSocket.setSoTimeout(timeout); - - if (bindingCommunicationInitialSocket()) { - return; - } - BindingLifetimeTask task = new BindingLifetimeTask(); - timer.schedule(task, binarySearchLifetime); - logger.finer("Timer scheduled initially: " + binarySearchLifetime + "."); - } - - private boolean bindingCommunicationInitialSocket() throws UtilityException, IOException, MessageHeaderParsingException, MessageAttributeParsingException { - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - ChangeRequest changeRequest = new ChangeRequest(); - sendMH.addMessageAttribute(changeRequest); - byte[] data = sendMH.getBytes(); - - DatagramPacket send = new DatagramPacket(data, data.length, InetAddress.getByName(stunServer), port); - initialSocket.send(send); - logger.finer("Binding Request sent."); - - MessageHeader receiveMH = new MessageHeader(); - while (!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - initialSocket.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - ma = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress); - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - logger.config("Message header contains an Errorcode message attribute."); - return true; - } - if (ma == null) { - logger.config("Response does not contain a Mapped Address message attribute."); - return true; - } - return false; - } - - public int getLifetime() { - return lifetime; - } - - public boolean isCompleted() { - return completed; - } - - public void setUpperBinarySearchLifetime(int upperBinarySearchLifetime) { - this.upperBinarySearchLifetime = upperBinarySearchLifetime; - binarySearchLifetime = ( upperBinarySearchLifetime + lowerBinarySearchLifetime ) / 2; - } - - class BindingLifetimeTask extends TimerTask { - - public BindingLifetimeTask() { - super(); - } - - public void run() { - try { - lifetimeQuery(); - } catch (Exception e) { - logger.config("Unhandled Exception. BindLifetimeTasks stopped."); - e.printStackTrace(); - } - } - - public void lifetimeQuery() throws UtilityException, MessageAttributeException, MessageHeaderParsingException, MessageAttributeParsingException, IOException { - try { - DatagramSocket socket = new DatagramSocket(); - socket.connect(InetAddress.getByName(stunServer), port); - socket.setSoTimeout(timeout); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - ChangeRequest changeRequest = new ChangeRequest(); - ResponseAddress responseAddress = new ResponseAddress(); - responseAddress.setAddress(ma.getAddress()); - responseAddress.setPort(ma.getPort()); - sendMH.addMessageAttribute(changeRequest); - sendMH.addMessageAttribute(responseAddress); - byte[] data = sendMH.getBytes(); - - DatagramPacket send = new DatagramPacket(data, data.length, InetAddress.getByName(stunServer), port); - socket.send(send); - logger.finer("Binding Request sent."); - - MessageHeader receiveMH = new MessageHeader(); - while (!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - initialSocket.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - logger.config("Message header contains errorcode message attribute."); - return; - } - logger.finer("Binding Response received."); - if (upperBinarySearchLifetime == (lowerBinarySearchLifetime + 1)) { - logger.config("BindingLifetimeTest completed. UDP binding lifetime: " + binarySearchLifetime + "."); - completed = true; - return; - } - lifetime = binarySearchLifetime; - logger.finer("Lifetime update: " + lifetime + "."); - lowerBinarySearchLifetime = binarySearchLifetime; - binarySearchLifetime = ( upperBinarySearchLifetime + lowerBinarySearchLifetime ) / 2; - if (binarySearchLifetime > 0) { - BindingLifetimeTask task = new BindingLifetimeTask(); - timer.schedule(task, binarySearchLifetime); - logger.finer("Timer scheduled: " + binarySearchLifetime + "."); - } else { - completed = true; - } - } catch (SocketTimeoutException ste) { - logger.finest("Read operation at query socket timeout."); - if (upperBinarySearchLifetime == (lowerBinarySearchLifetime + 1)) { - logger.config("BindingLifetimeTest completed. UDP binding lifetime: " + binarySearchLifetime + "."); - completed = true; - return; - } - upperBinarySearchLifetime = binarySearchLifetime; - binarySearchLifetime = ( upperBinarySearchLifetime + lowerBinarySearchLifetime ) / 2; - if (binarySearchLifetime > 0) { - if (bindingCommunicationInitialSocket()) { - return; - } - BindingLifetimeTask task = new BindingLifetimeTask(); - timer.schedule(task, binarySearchLifetime); - logger.finer("Timer scheduled: " + binarySearchLifetime + "."); - } else { - completed = true; - } - } - } - } -} - diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/DiscoveryInfo.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/DiscoveryInfo.java deleted file mode 100644 index abaab15e..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/DiscoveryInfo.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.test; - -import java.net.*; - -public class DiscoveryInfo { - private InetAddress testIP; - private boolean error = false; - private int errorResponseCode = 0; - private String errorReason; - private boolean openAccess = false; - private boolean blockedUDP = false; - private boolean fullCone = false; - private boolean restrictedCone = false; - private boolean portRestrictedCone = false; - private boolean symmetric = false; - private boolean symmetricUDPFirewall = false; - private InetAddress publicIP; - - public DiscoveryInfo(InetAddress testIP) { - this.testIP = testIP; - } - - public boolean isError() { - return error; - } - - public void setError(int responseCode, String reason) { - this.error = true; - this.errorResponseCode = responseCode; - this.errorReason = reason; - } - - public boolean isOpenAccess() { - if (error) return false; - return openAccess; - } - - public void setOpenAccess() { - this.openAccess = true; - } - - public boolean isBlockedUDP() { - if (error) return false; - return blockedUDP; - } - - public void setBlockedUDP() { - this.blockedUDP = true; - } - - public boolean isFullCone() { - if (error) return false; - return fullCone; - } - - public void setFullCone() { - this.fullCone = true; - } - - public boolean isPortRestrictedCone() { - if (error) return false; - return portRestrictedCone; - } - - public void setPortRestrictedCone() { - this.portRestrictedCone = true; - } - - public boolean isRestrictedCone() { - if (error) return false; - return restrictedCone; - } - - public void setRestrictedCone() { - this.restrictedCone = true; - } - - public boolean isSymmetric() { - if (error) return false; - return symmetric; - } - - public void setSymmetric() { - this.symmetric = true; - } - - public boolean isSymmetricUDPFirewall() { - if (error) return false; - return symmetricUDPFirewall; - } - - public void setSymmetricUDPFirewall() { - this.symmetricUDPFirewall = true; - } - - public InetAddress getPublicIP() { - return publicIP; - } - - public InetAddress getLocalIP() { - return testIP; - } - - public void setPublicIP(InetAddress publicIP) { - this.publicIP = publicIP; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("Network interface: "); - try { - sb.append(NetworkInterface.getByInetAddress(testIP).getName()); - } catch (SocketException se) { - sb.append("unknown"); - } - sb.append("\n"); - sb.append("Local IP address: "); - sb.append(testIP.getHostAddress()); - sb.append("\n"); - if (error) { - sb.append(errorReason + " - Responsecode: " + errorResponseCode); - return sb.toString(); - } - sb.append("Result: "); - if (openAccess) sb.append("Open access to the Internet.\n"); - if (blockedUDP) sb.append("Firewall blocks UDP.\n"); - if (fullCone) sb.append("Full Cone NAT handles connections.\n"); - if (restrictedCone) sb.append("Restricted Cone NAT handles connections.\n"); - if (portRestrictedCone) sb.append("Port restricted Cone NAT handles connections.\n"); - if (symmetric) sb.append("Symmetric Cone NAT handles connections.\n"); - if (symmetricUDPFirewall) sb.append ("Symmetric UDP Firewall handles connections.\n"); - if (!openAccess && !blockedUDP && !fullCone && !restrictedCone && !portRestrictedCone && !symmetric && !symmetricUDPFirewall) sb.append("unkown\n"); - sb.append("Public IP address: "); - if (publicIP != null) { - sb.append(publicIP.getHostAddress()); - } else { - sb.append("unknown"); - } - sb.append("\n"); - return sb.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/DiscoveryTest.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/DiscoveryTest.java deleted file mode 100644 index 4f940adf..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/DiscoveryTest.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.test; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.util.logging.Logger; - - - - - -import de.javawi.jstun.attribute.ChangeRequest; -import de.javawi.jstun.attribute.ChangedAddress; -import de.javawi.jstun.attribute.ErrorCode; -import de.javawi.jstun.attribute.MappedAddress; -import de.javawi.jstun.attribute.MessageAttribute; -import de.javawi.jstun.attribute.MessageAttributeException; -import de.javawi.jstun.attribute.MessageAttributeParsingException; -import de.javawi.jstun.header.MessageHeader; -import de.javawi.jstun.header.MessageHeaderParsingException; -import de.javawi.jstun.util.UtilityException; - -public class DiscoveryTest { - private static Logger logger = Logger.getLogger("de.javawi.stun.test.DiscoveryTest"); - InetAddress iaddress; - String stunServer; - int port; - int timeoutInitValue = 300; //ms - MappedAddress ma = null; - ChangedAddress ca = null; - boolean nodeNatted = true; - DatagramSocket socketTest1 = null; - DiscoveryInfo di = null; - - public DiscoveryTest(InetAddress iaddress , String stunServer, int port) { - super(); - this.iaddress = iaddress; - this.stunServer = stunServer; - this.port = port; - } - - public DiscoveryInfo test() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException{ - ma = null; - ca = null; - nodeNatted = true; - socketTest1 = null; - di = new DiscoveryInfo(iaddress); - - if (test1()) { - if (test2()) { - if (test1Redo()) { - test3(); - } - } - } - - socketTest1.close(); - - return di; - } - - private boolean test1() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageHeaderParsingException { - int timeSinceFirstTransmission = 0; - int timeout = timeoutInitValue; - while (true) { - try { - // Test 1 including response - socketTest1 = new DatagramSocket(new InetSocketAddress(iaddress, 0)); - socketTest1.setReuseAddress(true); - socketTest1.connect(InetAddress.getByName(stunServer), port); - socketTest1.setSoTimeout(timeout); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - - ChangeRequest changeRequest = new ChangeRequest(); - sendMH.addMessageAttribute(changeRequest); - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - socketTest1.send(send); - logger.finer("Test 1: Binding Request sent."); - - MessageHeader receiveMH = new MessageHeader(); - while (!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - socketTest1.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - - ma = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress); - ca = (ChangedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ChangedAddress); - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - di.setError(ec.getResponseCode(), ec.getReason()); - logger.config("Message header contains an Errorcode message attribute."); - return false; - } - if ((ma == null) || (ca == null)) { - di.setError(700, "The server is sending an incomplete response (Mapped Address and Changed Address message attributes are missing). The client should not retry."); - logger.config("Response does not contain a Mapped Address or Changed Address message attribute."); - return false; - } else { - di.setPublicIP(ma.getAddress().getInetAddress()); - if ((ma.getPort() == socketTest1.getLocalPort()) && (ma.getAddress().getInetAddress().equals(socketTest1.getLocalAddress()))) { - logger.fine("Node is not natted."); - nodeNatted = false; - } else { - logger.fine("Node is natted."); - } - return true; - } - } catch (SocketTimeoutException ste) { - if (timeSinceFirstTransmission < 7900) { - logger.finer("Test 1: Socket timeout while receiving the response."); - timeSinceFirstTransmission += timeout; - int timeoutAddValue = (timeSinceFirstTransmission * 2); - if (timeoutAddValue > 1600) timeoutAddValue = 1600; - timeout = timeoutAddValue; - } else { - // node is not capable of udp communication - logger.finer("Test 1: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); - di.setBlockedUDP(); - logger.fine("Node is not capable of UDP communication."); - return false; - } - } - } - } - - private boolean test2() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException { - int timeSinceFirstTransmission = 0; - int timeout = timeoutInitValue; - while (true) { - try { - // Test 2 including response - DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0)); - sendSocket.connect(InetAddress.getByName(stunServer), port); - sendSocket.setSoTimeout(timeout); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - - ChangeRequest changeRequest = new ChangeRequest(); - changeRequest.setChangeIP(); - changeRequest.setChangePort(); - sendMH.addMessageAttribute(changeRequest); - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - sendSocket.send(send); - logger.finer("Test 2: Binding Request sent."); - - int localPort = sendSocket.getLocalPort(); - InetAddress localAddress = sendSocket.getLocalAddress(); - - sendSocket.close(); - - DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress); - receiveSocket.connect(ca.getAddress().getInetAddress(), ca.getPort()); - receiveSocket.setSoTimeout(timeout); - - MessageHeader receiveMH = new MessageHeader(); - while(!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - receiveSocket.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - di.setError(ec.getResponseCode(), ec.getReason()); - logger.config("Message header contains an Errorcode message attribute."); - return false; - } - if (!nodeNatted) { - di.setOpenAccess(); - logger.fine("Node has open access to the Internet (or, at least the node is behind a full-cone NAT without translation)."); - } else { - di.setFullCone(); - logger.fine("Node is behind a full-cone NAT."); - } - return false; - } catch (SocketTimeoutException ste) { - if (timeSinceFirstTransmission < 7900) { - logger.finer("Test 2: Socket timeout while receiving the response."); - timeSinceFirstTransmission += timeout; - int timeoutAddValue = (timeSinceFirstTransmission * 2); - if (timeoutAddValue > 1600) timeoutAddValue = 1600; - timeout = timeoutAddValue; - } else { - logger.finer("Test 2: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); - if (!nodeNatted) { - di.setSymmetricUDPFirewall(); - logger.fine("Node is behind a symmetric UDP firewall."); - return false; - } else { - // not is natted - // redo test 1 with address and port as offered in the changed-address message attribute - return true; - } - } - } - } - } - - private boolean test1Redo() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageHeaderParsingException{ - int timeSinceFirstTransmission = 0; - int timeout = timeoutInitValue; - while (true) { - // redo test 1 with address and port as offered in the changed-address message attribute - try { - // Test 1 with changed port and address values - socketTest1.connect(ca.getAddress().getInetAddress(), ca.getPort()); - socketTest1.setSoTimeout(timeout); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - - ChangeRequest changeRequest = new ChangeRequest(); - sendMH.addMessageAttribute(changeRequest); - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - socketTest1.send(send); - logger.finer("Test 1 redo with changed address: Binding Request sent."); - - MessageHeader receiveMH = new MessageHeader(); - while (!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - socketTest1.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - MappedAddress ma2 = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress); - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - di.setError(ec.getResponseCode(), ec.getReason()); - logger.config("Message header contains an Errorcode message attribute."); - return false; - } - if (ma2 == null) { - di.setError(700, "The server is sending an incomplete response (Mapped Address message attribute is missing). The client should not retry."); - logger.config("Response does not contain a Mapped Address message attribute."); - return false; - } else { - if ((ma.getPort() != ma2.getPort()) || (!(ma.getAddress().getInetAddress().equals(ma2.getAddress().getInetAddress())))) { - di.setSymmetric(); - logger.fine("Node is behind a symmetric NAT."); - return false; - } - } - return true; - } catch (SocketTimeoutException ste2) { - if (timeSinceFirstTransmission < 7900) { - logger.config("Test 1 redo with changed address: Socket timeout while receiving the response."); - timeSinceFirstTransmission += timeout; - int timeoutAddValue = (timeSinceFirstTransmission * 2); - if (timeoutAddValue > 1600) timeoutAddValue = 1600; - timeout = timeoutAddValue; - } else { - logger.config("Test 1 redo with changed address: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); - return false; - } - } - } - } - - private void test3() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException { - int timeSinceFirstTransmission = 0; - int timeout = timeoutInitValue; - while (true) { - try { - // Test 3 including response - DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0)); - sendSocket.connect(InetAddress.getByName(stunServer), port); - sendSocket.setSoTimeout(timeout); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - - ChangeRequest changeRequest = new ChangeRequest(); - changeRequest.setChangePort(); - sendMH.addMessageAttribute(changeRequest); - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - sendSocket.send(send); - logger.finer("Test 3: Binding Request sent."); - - int localPort = sendSocket.getLocalPort(); - InetAddress localAddress = sendSocket.getLocalAddress(); - - sendSocket.close(); - - DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress); - receiveSocket.connect(InetAddress.getByName(stunServer), ca.getPort()); - receiveSocket.setSoTimeout(timeout); - - MessageHeader receiveMH = new MessageHeader(); - while (!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - receiveSocket.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - di.setError(ec.getResponseCode(), ec.getReason()); - logger.config("Message header contains an Errorcode message attribute."); - return; - } - if (nodeNatted) { - di.setRestrictedCone(); - logger.fine("Node is behind a restricted NAT."); - return; - } - } catch (SocketTimeoutException ste) { - if (timeSinceFirstTransmission < 7900) { - logger.finer("Test 3: Socket timeout while receiving the response."); - timeSinceFirstTransmission += timeout; - int timeoutAddValue = (timeSinceFirstTransmission * 2); - if (timeoutAddValue > 1600) timeoutAddValue = 1600; - timeout = timeoutAddValue; - } else { - logger.finer("Test 3: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); - di.setPortRestrictedCone(); - logger.fine("Node is behind a port restricted NAT."); - return; - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/BindingLifetimeTestDemo.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/BindingLifetimeTestDemo.java deleted file mode 100644 index 37e20f84..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/BindingLifetimeTestDemo.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.test.demo; - -import java.util.logging.FileHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.logging.SimpleFormatter; - -import de.javawi.jstun.test.BindingLifetimeTest; - -public class BindingLifetimeTestDemo { - public static void main(String args[]) { - try { - Handler fh = new FileHandler("logging.txt"); - fh.setFormatter(new SimpleFormatter()); - Logger.getLogger("de.javawi.stun").addHandler(fh); - Logger.getLogger("de.javawi.stun").setLevel(Level.ALL); - BindingLifetimeTest test = new BindingLifetimeTest("iphone-stun.freenet.de", 3478); - // iphone-stun.freenet.de:3478 - // larry.gloo.net:3478 - // stun.xten.net:3478 - test.test(); - boolean continueWhile = true; - while(continueWhile) { - Thread.sleep(5000); - if (test.getLifetime() != -1) { - System.out.println("Lifetime: " + test.getLifetime() + " Finished: " + test.isCompleted()); - if (test.isCompleted()) continueWhile = false; - } - } - } catch (Exception e) { - System.out.println(e.getMessage()); - e.printStackTrace(); - } - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/DiscoveryTestDemo.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/DiscoveryTestDemo.java deleted file mode 100644 index 76a6c17e..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/DiscoveryTestDemo.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.test.demo; - -import java.net.BindException; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.util.Enumeration; -import java.util.logging.FileHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.logging.SimpleFormatter; - -import de.javawi.jstun.test.DiscoveryTest; - -public class DiscoveryTestDemo implements Runnable { - InetAddress iaddress; - - public DiscoveryTestDemo(InetAddress iaddress) { - this.iaddress = iaddress; - } - - public void run() { - try { - DiscoveryTest test = new DiscoveryTest(iaddress, "jstun.javawi.de", 3478); - //DiscoveryTest test = new DiscoveryTest(iaddress, "stun.sipgate.net", 10000); - // iphone-stun.freenet.de:3478 - // larry.gloo.net:3478 - // stun.xten.net:3478 - // stun.sipgate.net:10000 - System.out.println(test.test()); - } catch (BindException be) { - System.out.println(iaddress.toString() + ": " + be.getMessage()); - } catch (Exception e) { - System.out.println(e.getMessage()); - e.printStackTrace(); - } - } - - public static void main(String args[]) { - try { - Handler fh = new FileHandler("logging.txt"); - fh.setFormatter(new SimpleFormatter()); - Logger.getLogger("de.javawi.stun").addHandler(fh); - Logger.getLogger("de.javawi.stun").setLevel(Level.ALL); - - Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); - while (ifaces.hasMoreElements()) { - NetworkInterface iface = ifaces.nextElement(); - Enumeration iaddresses = iface.getInetAddresses(); - while (iaddresses.hasMoreElements()) { - InetAddress iaddress = iaddresses.nextElement(); - if (Class.forName("java.net.Inet4Address").isInstance(iaddress)) { - if ((!iaddress.isLoopbackAddress()) && (!iaddress.isLinkLocalAddress())) { - Thread thread = new Thread(new DiscoveryTestDemo(iaddress)); - thread.start(); - } - } - } - } - } catch (Exception e) { - System.out.println(e.getMessage()); - } - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/StunServer.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/StunServer.java deleted file mode 100644 index b72ffe7c..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/StunServer.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.test.demo; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.Vector; -import java.util.logging.FileHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.logging.SimpleFormatter; - -import de.javawi.jstun.attribute.ChangeRequest; -import de.javawi.jstun.attribute.ChangedAddress; -import de.javawi.jstun.attribute.MappedAddress; -import de.javawi.jstun.attribute.MessageAttributeException; -import de.javawi.jstun.attribute.MessageAttributeParsingException; -import de.javawi.jstun.attribute.ResponseAddress; -import de.javawi.jstun.attribute.SourceAddress; -import de.javawi.jstun.attribute.UnknownAttribute; -import de.javawi.jstun.attribute.UnknownMessageAttributeException; -import de.javawi.jstun.attribute.MessageAttributeInterface.MessageAttributeType; -import de.javawi.jstun.header.MessageHeader; -import de.javawi.jstun.header.MessageHeaderParsingException; -import de.javawi.jstun.header.MessageHeaderInterface.MessageHeaderType; -import de.javawi.jstun.util.Address; -import de.javawi.jstun.util.UtilityException; - -/* - * This class implements a STUN server as described in RFC 3489. - * The server requires a machine that is dual-homed to be functional. - */ -public class StunServer { - private static Logger logger = Logger.getLogger("de.javawi.stun.test.StunServer"); - Vector sockets; - - public StunServer(int primaryPort, InetAddress primary, int secondaryPort, InetAddress secondary) throws SocketException { - sockets = new Vector(); - sockets.add(new DatagramSocket(primaryPort, primary)); - sockets.add(new DatagramSocket(secondaryPort, primary)); - sockets.add(new DatagramSocket(primaryPort, secondary)); - sockets.add(new DatagramSocket(secondaryPort, secondary)); - } - - public void start() throws SocketException { - for (DatagramSocket socket : sockets) { - socket.setReceiveBufferSize(2000); - StunServerReceiverThread ssrt = new StunServerReceiverThread(socket); - ssrt.start(); - } - } - - /* - * Inner class to handle incoming packets and react accordingly. - * I decided not to start a thread for every received Binding Request, because the time - * required to receive a Binding Request, parse it, generate a Binding Response and send - * it varies only between 2 and 4 milliseconds. This amount of time is small enough so - * that no extra thread is needed for incoming Binding Request. - */ - class StunServerReceiverThread extends Thread { - private DatagramSocket receiverSocket; - private DatagramSocket changedPort; - private DatagramSocket changedIP; - private DatagramSocket changedPortIP; - - StunServerReceiverThread(DatagramSocket datagramSocket) { - this.receiverSocket = datagramSocket; - for (DatagramSocket socket : sockets) { - if ((socket.getLocalPort() != receiverSocket.getLocalPort()) && - (socket.getLocalAddress().equals(receiverSocket.getLocalAddress()))) - changedPort = socket; - if ((socket.getLocalPort() == receiverSocket.getLocalPort()) && - (!socket.getLocalAddress().equals(receiverSocket.getLocalAddress()))) - changedIP = socket; - if ((socket.getLocalPort() != receiverSocket.getLocalPort()) && - (!socket.getLocalAddress().equals(receiverSocket.getLocalAddress()))) - changedPortIP = socket; - } - } - - public void run() { - while (true) { - try { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - receiverSocket.receive(receive); - logger.finest(receiverSocket.getLocalAddress().getHostAddress() + ":" + receiverSocket.getLocalPort() + " datagram received from " + receive.getAddress().getHostAddress() + ":" + receive.getPort()); - MessageHeader receiveMH = MessageHeader.parseHeader(receive.getData()); - try { - receiveMH.parseAttributes(receive.getData()); - if (receiveMH.getType() == MessageHeaderType.BindingRequest) { - logger.config(receiverSocket.getLocalAddress().getHostAddress() + ":" + receiverSocket.getLocalPort() + " Binding Request received from " + receive.getAddress().getHostAddress() + ":" + receive.getPort()); - ChangeRequest cr = (ChangeRequest) receiveMH.getMessageAttribute(MessageAttributeType.ChangeRequest); - if (cr == null) throw new MessageAttributeException("Message attribute change request is not set."); - ResponseAddress ra = (ResponseAddress) receiveMH.getMessageAttribute(MessageAttributeType.ResponseAddress); - - MessageHeader sendMH = new MessageHeader(MessageHeaderType.BindingResponse); - sendMH.setTransactionID(receiveMH.getTransactionID()); - - // Mapped address attribute - MappedAddress ma = new MappedAddress(); - ma.setAddress(new Address(receive.getAddress().getAddress())); - ma.setPort(receive.getPort()); - sendMH.addMessageAttribute(ma); - // Changed address attribute - ChangedAddress ca = new ChangedAddress(); - ca.setAddress(new Address(changedPortIP.getLocalAddress().getAddress())); - ca.setPort(changedPortIP.getLocalPort()); - sendMH.addMessageAttribute(ca); - if (cr.isChangePort() && (!cr.isChangeIP())) { - logger.finer("Change port received in Change Request attribute"); - // Source address attribute - SourceAddress sa = new SourceAddress(); - sa.setAddress(new Address(changedPort.getLocalAddress().getAddress())); - sa.setPort(changedPort.getLocalPort()); - sendMH.addMessageAttribute(sa); - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - if (ra != null) { - send.setPort(ra.getPort()); - send.setAddress(ra.getAddress().getInetAddress()); - } else { - send.setPort(receive.getPort()); - send.setAddress(receive.getAddress()); - } - changedPort.send(send); - logger.config(changedPort.getLocalAddress().getHostAddress() + ":" + changedPort.getLocalPort() + " send Binding Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); - } else if ((!cr.isChangePort()) && cr.isChangeIP()) { - logger.finer("Change ip received in Change Request attribute"); - // Source address attribute - SourceAddress sa = new SourceAddress(); - sa.setAddress(new Address(changedIP.getLocalAddress().getAddress())); - sa.setPort(changedIP.getLocalPort()); - sendMH.addMessageAttribute(sa); - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - if (ra != null) { - send.setPort(ra.getPort()); - send.setAddress(ra.getAddress().getInetAddress()); - } else { - send.setPort(receive.getPort()); - send.setAddress(receive.getAddress()); - } - changedIP.send(send); - logger.config(changedIP.getLocalAddress().getHostAddress() + ":" + changedIP.getLocalPort() + " send Binding Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); - } else if ((!cr.isChangePort()) && (!cr.isChangeIP())) { - logger.finer("Nothing received in Change Request attribute"); - // Source address attribute - SourceAddress sa = new SourceAddress(); - sa.setAddress(new Address(receiverSocket.getLocalAddress().getAddress())); - sa.setPort(receiverSocket.getLocalPort()); - sendMH.addMessageAttribute(sa); - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - if (ra != null) { - send.setPort(ra.getPort()); - send.setAddress(ra.getAddress().getInetAddress()); - } else { - send.setPort(receive.getPort()); - send.setAddress(receive.getAddress()); - } - receiverSocket.send(send); - logger.config(receiverSocket.getLocalAddress().getHostAddress() + ":" + receiverSocket.getLocalPort() + " send Binding Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); - } else if (cr.isChangePort() && cr.isChangeIP()) { - logger.finer("Change port and ip received in Change Request attribute"); - // Source address attribute - SourceAddress sa = new SourceAddress(); - sa.setAddress(new Address(changedPortIP.getLocalAddress().getAddress())); - sa.setPort(changedPortIP.getLocalPort()); - sendMH.addMessageAttribute(sa); - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - if (ra != null) { - send.setPort(ra.getPort()); - send.setAddress(ra.getAddress().getInetAddress()); - } else { - send.setPort(receive.getPort()); - send.setAddress(receive.getAddress()); - } - changedPortIP.send(send); - logger.config(changedPortIP.getLocalAddress().getHostAddress() + ":" + changedPortIP.getLocalPort() + " send Binding Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); - } - } - } catch (UnknownMessageAttributeException umae) { - umae.printStackTrace(); - // Generate Binding error response - MessageHeader sendMH = new MessageHeader(MessageHeaderType.BindingErrorResponse); - sendMH.setTransactionID(receiveMH.getTransactionID()); - - // Unknown attributes - UnknownAttribute ua = new UnknownAttribute(); - ua.addAttribute(umae.getType()); - sendMH.addMessageAttribute(ua); - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - send.setPort(receive.getPort()); - send.setAddress(receive.getAddress()); - receiverSocket.send(send); - logger.config(changedPortIP.getLocalAddress().getHostAddress() + ":" + changedPortIP.getLocalPort() + " send Binding Error Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); - } - } catch (IOException ioe) { - ioe.printStackTrace(); - } catch (MessageAttributeParsingException mape) { - mape.printStackTrace(); - } catch (MessageAttributeException mae) { - mae.printStackTrace(); - } catch (MessageHeaderParsingException mhpe) { - mhpe.printStackTrace(); - } catch (UtilityException ue) { - ue.printStackTrace(); - } catch (ArrayIndexOutOfBoundsException aioobe) { - aioobe.printStackTrace(); - } - } - } - } - - /* - * To invoke the STUN server two IP addresses and two ports are required. - */ - public static void main(String args[]) { - try { - if (args.length != 4) { - System.out.println("usage: java de.javawi.jstun.test.demo.StunServer PORT1 IP1 PORT2 IP2"); - System.out.println(); - System.out.println(" PORT1 - the first port that should be used by the server"); - System.out.println(" IP1 - the first ip address that should be used by the server"); - System.out.println(" PORT2 - the second port that should be used by the server"); - System.out.println(" IP2 - the second ip address that should be used by the server"); - System.exit(0); - } - Handler fh = new FileHandler("logging_server.txt"); - fh.setFormatter(new SimpleFormatter()); - Logger.getLogger("de.javawi.stun").addHandler(fh); - Logger.getLogger("de.javawi.stun").setLevel(Level.ALL); - StunServer ss = new StunServer(Integer.parseInt(args[0]), - InetAddress.getByName(args[1]), - Integer.parseInt(args[2]), - InetAddress.getByName(args[3])); - ss.start(); - } catch (SocketException se) { - se.printStackTrace(); - } catch (UnknownHostException uhe) { - uhe.printStackTrace(); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/ice/Candidate.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/ice/Candidate.java deleted file mode 100644 index 22dd58fb..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/ice/Candidate.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.test.demo.ice; - -import java.net.DatagramSocket; -import java.net.SocketException; -import java.net.UnknownHostException; - -import de.javawi.jstun.util.Address; -import de.javawi.jstun.util.UtilityException; - -public class Candidate implements Comparable { - // The ieft-mmusic-ice-12 draft is not non-ambigious about the number of types. - // Chapter 5.1 defines 3 and 4 types on page 16 and page 17, respectively. - public enum CandidateType { Local, ServerReflexive, PeerReflexive, Relayed }; - - private DatagramSocket socket; - private CandidateType type; - private short componentId; - private int priority; - private int foundationId; - private Candidate base; - private boolean isInUse; - - public Candidate(Address address, short componentId) throws SocketException, UnknownHostException, UtilityException { - this.socket = new DatagramSocket(0, address.getInetAddress()); - this.type = CandidateType.Local; - this.componentId = componentId; - this.priority = 0; - this.base = this; - this.isInUse = false; - } - - public Candidate(Address address, CandidateType type, short componentId, Candidate base) throws SocketException, UnknownHostException, UtilityException { - this.socket = new DatagramSocket(0, address.getInetAddress()); - this.type = type; - setComponentId(componentId); - this.priority = 0; - this.base = base; - this.isInUse = false; - } - - public void setBase(Candidate base) { - this.base = base; - } - - public Candidate getBase() { - return base; - } - - public CandidateType getCandidateType() { - return type; - } - - public void setComponentId(short componentId) { - if ((componentId < 1) || (componentId > 256)) throw new IllegalArgumentException(componentId + " is not between 1 and 256 inclusive."); - this.componentId = componentId; - } - - public short getComponentId() { - return componentId; - } - - public void setFoundationId(int foundationId) { - this.foundationId = foundationId; - } - - public int getFoundationId() { - return foundationId; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - public int getPriority() { - return priority; - } - - public Address getAddress() throws UtilityException { - return new Address(socket.getLocalAddress().getAddress()); - } - - public int getPort() { - return socket.getLocalPort(); - } - - public void setInUse(boolean isInUse) { - this.isInUse = isInUse; - } - - public boolean getInUse() { - return isInUse; - } - - public int compareTo(Object arg0) { - Candidate cand = (Candidate) arg0; - return cand.getPriority() - getPriority(); - } - - public boolean equals(Object o) { - if (o == null) return false; - if ((((Candidate) o).socket.equals(socket)) && (((Candidate) o).base.equals(base))) return true; - return false; - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/ice/ICENegociator.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/ice/ICENegociator.java deleted file mode 100644 index 502528c5..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/test/demo/ice/ICENegociator.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.test.demo.ice; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import de.javawi.jstun.test.DiscoveryInfo; -import de.javawi.jstun.test.DiscoveryTest; -import de.javawi.jstun.test.demo.ice.Candidate.CandidateType; -import de.javawi.jstun.util.Address; - -public class ICENegociator { - // type preference must be an integere from 0 (=lowest) to 126 (=highest) (inclusive) - private final static int LOCAL_PREFERENCE = 0; - private final static int SERVER_REFLEXIVE_PREFERENCE = 42; - private final static int PEER_REFLEXIVE_PREFERENCE = 84; - private final static int RELAYED_PREFERENCE = 126; - - // component id - private short componentId; - - // candidates - HashSet candidates; - - public ICENegociator(short componentId) { - this.componentId = componentId; - candidates = new HashSet(); - } - - /* - * This method gathers candidate addresses as described in draft-ietf-mmusic-ice-12.txt Chapter 2.1 - * Unfortunately, only the candidates of the direct attached network interfaces and server reflexive - * addreses are gathered. So far, no support for relayed candidates is available (because I am not - * aware of any STUN relay server). - */ - public void gatherCandidateAddresses() { - candidates = new HashSet(); - try { - Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); - while (ifaces.hasMoreElements()) { - NetworkInterface iface = ifaces.nextElement(); - Enumeration iaddresses = iface.getInetAddresses(); - while (iaddresses.hasMoreElements()) { - InetAddress iaddress = iaddresses.nextElement(); - if (!iaddress.isLoopbackAddress() && !iaddress.isLinkLocalAddress()) { - // add host candidate - Candidate local = new Candidate(new Address(iaddress.getAddress()), componentId); - candidates.add(local); - // add server reflexive address - DiscoveryTest test = new DiscoveryTest(iaddress, "iphone-stun.freenet.de", 3478); - DiscoveryInfo di = test.test(); - if (di.getPublicIP() != null) { - Candidate cand = new Candidate(new Address(di.getPublicIP().getAddress()), CandidateType.ServerReflexive, componentId, local); - cand.setComponentId(componentId); - candidates.add(cand); - } - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void prioritizeCandidates() { - // count number of candidate types - int numberLocal = 0; - int numberServerReflexive = 0; - int numberPeerReflexive = 0; - int numberRelayed = 0; - // count number of candidates of a particular type - Iterator iterCandidates = candidates.iterator(); - while (iterCandidates.hasNext()) { - Candidate cand = iterCandidates.next(); - CandidateType type = cand.getCandidateType(); - if (type == CandidateType.Local) numberLocal++; - else if (type == CandidateType.ServerReflexive) numberServerReflexive++; - else if (type == CandidateType.PeerReflexive) numberPeerReflexive++; - else if (type == CandidateType.Relayed) numberRelayed++; - } - // assign priorities - iterCandidates = candidates.iterator(); - while (iterCandidates.hasNext()) { - int typeValue = 0; - int localValue = 0; - int componentValue = 0; - Candidate cand = iterCandidates.next(); - CandidateType type = cand.getCandidateType(); - if (type == CandidateType.Local) { - typeValue = LOCAL_PREFERENCE; - localValue = numberLocal--; - } - else if (type == CandidateType.ServerReflexive) { - typeValue = SERVER_REFLEXIVE_PREFERENCE; - localValue = numberServerReflexive--; - } - else if (type == CandidateType.PeerReflexive) { - typeValue = PEER_REFLEXIVE_PREFERENCE; - localValue = numberPeerReflexive--; - } - else if (type == CandidateType.Relayed) { - typeValue = RELAYED_PREFERENCE; - localValue = numberRelayed--; - } - componentValue = cand.getComponentId(); - int priority = ((2 ^ 24) * typeValue) + ((2 ^ 8) * localValue) + componentValue; - cand.setPriority(priority); - } - } - - public List getSortedCandidates() { - Vector sortedCandidates = new Vector(candidates); - Collections.sort(sortedCandidates); - return sortedCandidates; - } - - public static void main(String args[]) { - ICENegociator cc = new ICENegociator((short) 1); - // gather candidates - cc.gatherCandidateAddresses(); - // priorize candidates - cc.prioritizeCandidates(); - // get SortedCandidates - List sortedCandidates = cc.getSortedCandidates(); - - // sent sorted candidate addresses to peer over SDP - // received sorted candidate addresses of peer over SDP - - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/util/Address.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/util/Address.java deleted file mode 100644 index 46ad1a0e..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/util/Address.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.util; - -import java.util.*; -import java.net.*; - -public class Address { - int firstOctet; - int secondOctet; - int thirdOctet; - int fourthOctet; - - public Address(int firstOctet, int secondOctet, int thirdOctet, int fourthOctet) throws UtilityException { - if ((firstOctet < 0) || (firstOctet > 255) || (secondOctet < 0) || (secondOctet > 255) || (thirdOctet < 0) || (thirdOctet > 255) || (fourthOctet < 0) || (fourthOctet > 255)) { - throw new UtilityException("Address is malformed."); - } - this.firstOctet = firstOctet; - this.secondOctet = secondOctet; - this.thirdOctet = thirdOctet; - this.fourthOctet = fourthOctet; - } - - public Address(String address) throws UtilityException { - StringTokenizer st = new StringTokenizer(address, "."); - if (st.countTokens() != 4) { - throw new UtilityException("4 octets in address string are required."); - } - int i = 0; - while (st.hasMoreTokens()) { - int temp = Integer.parseInt(st.nextToken()); - if ((temp < 0) || (temp > 255)) { - throw new UtilityException("Address is in incorrect format."); - } - switch (i) { - case 0: firstOctet = temp; ++i; break; - case 1: secondOctet = temp; ++i; break; - case 2: thirdOctet = temp; ++i; break; - case 3: fourthOctet = temp; ++i; break; - } - } - } - - public Address(byte[] address) throws UtilityException { - if (address.length < 4) { - throw new UtilityException("4 bytes are required."); - } - firstOctet = Utility.oneByteToInteger(address[0]); - secondOctet = Utility.oneByteToInteger(address[1]); - thirdOctet = Utility.oneByteToInteger(address[2]); - fourthOctet = Utility.oneByteToInteger(address[3]); - } - - public String toString() { - return firstOctet + "." + secondOctet + "." + thirdOctet + "." + fourthOctet; - } - - public byte[] getBytes() throws UtilityException { - byte[] result = new byte[4]; - result[0] = Utility.integerToOneByte(firstOctet); - result[1] = Utility.integerToOneByte(secondOctet); - result[2] = Utility.integerToOneByte(thirdOctet); - result[3] = Utility.integerToOneByte(fourthOctet); - return result; - } - - public InetAddress getInetAddress() throws UtilityException, UnknownHostException { - byte[] address = new byte[4]; - address[0] = Utility.integerToOneByte(firstOctet); - address[1] = Utility.integerToOneByte(secondOctet); - address[2] = Utility.integerToOneByte(thirdOctet); - address[3] = Utility.integerToOneByte(fourthOctet); - return InetAddress.getByAddress(address); - } - - public boolean equals(Object obj) { - if (obj == null) return false; - try { - byte[] data1 = this.getBytes(); - byte[] data2 = ((Address) obj).getBytes(); - if ((data1[0] == data2[0]) && (data1[1] == data2[1]) && - (data1[2] == data2[2]) && (data1[3] == data2[3])) return true; - return false; - } catch (UtilityException ue) { - return false; - } - } - - public int hashCode() { - return (firstOctet << 24) + (secondOctet << 16) + (thirdOctet << 8) + fourthOctet; - } - -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/util/Utility.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/util/Utility.java deleted file mode 100644 index 91c2d88e..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/util/Utility.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.util; - -public class Utility { - - public static final byte integerToOneByte(int value) throws UtilityException { - if ((value > Math.pow(2,15)) || (value < 0)) { - throw new UtilityException("Integer value " + value + " is larger than 2^15"); - } - return (byte)(value & 0xFF); - } - - public static final byte[] integerToTwoBytes(int value) throws UtilityException { - byte[] result = new byte[2]; - if ((value > Math.pow(2,31)) || (value < 0)) { - throw new UtilityException("Integer value " + value + " is larger than 2^31"); - } - result[0] = (byte)((value >>> 8) & 0xFF); - result[1] = (byte)(value & 0xFF); - return result; - } - - public static final byte[] integerToFourBytes(int value) throws UtilityException { - byte[] result = new byte[4]; - if ((value > Math.pow(2,63)) || (value < 0)) { - throw new UtilityException("Integer value " + value + " is larger than 2^63"); - } - result[0] = (byte)((value >>> 24) & 0xFF); - result[1] = (byte)((value >>> 16) & 0xFF); - result[2] = (byte)((value >>> 8) & 0xFF); - result[3] = (byte)(value & 0xFF); - return result; - } - - public static final int oneByteToInteger(byte value) throws UtilityException { - return (int)value & 0xFF; - } - - public static final int twoBytesToInteger(byte[] value) throws UtilityException { - if (value.length < 2) { - throw new UtilityException("Byte array too short!"); - } - int temp0 = value[0] & 0xFF; - int temp1 = value[1] & 0xFF; - return ((temp0 << 8) + temp1); - } - - public static final long fourBytesToLong(byte[] value) throws UtilityException { - if (value.length < 4) { - throw new UtilityException("Byte array too short!"); - } - int temp0 = value[0] & 0xFF; - int temp1 = value[1] & 0xFF; - int temp2 = value[2] & 0xFF; - int temp3 = value[3] & 0xFF; - return (((long)temp0 << 24) + (temp1 << 16) + (temp2 << 8) + temp3); - } -} diff --git a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/util/UtilityException.java b/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/util/UtilityException.java deleted file mode 100644 index d6f65fa7..00000000 --- a/p2pproxy/dependencies-src/jstun-src-0.7.1/de/javawi/jstun/util/UtilityException.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package de.javawi.jstun.util; - -public class UtilityException extends Exception { - private static final long serialVersionUID = 3545800974716581680L; - - UtilityException(String mesg) { - super(mesg); - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/pom.xml b/p2pproxy/dependencies-src/jxse-src-2.5/api/pom.xml deleted file mode 100644 index 4f467d1c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/pom.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - net.jxta.platform - jxta - 1.0 - ../pom.xml - - 4.0.0 - jxta-api - net.jxta.platform - jxta-api - jar - 1.0 - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/Version.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/Version.java deleted file mode 100644 index f6604de0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/Version.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * - * ==================================================================== - * - * Copyright (c) 2001 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta; - -import java.lang.Package; - -/** - * Provides easy access to Java Package information for the JXSE API. - */ -public final class Version { - - /** - * Returns the package. - * - * @return The specification title. - */ - public static Package getPackage() { - return Version.class.getPackage(); - } - - /** - * Returns the specification title. - * - * @return The specification title. - */ - public static String getSpecTitle() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getSpecificationTitle(); - } - - /** - * Returns the specification vendor. - * - * @return The specification vendor. - */ - public static String getSpecVendor() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getSpecificationVendor(); - } - - /** - * Returns the specification version. - * - * @return The specification version. - */ - public static String getSpecVersion() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getSpecificationVersion(); - } - - /** - * Returns the specification title. - * - * @return The specification title. - */ - public static String getImplTitle() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getImplementationTitle(); - } - - /** - * Returns the specification vendor. - * - * @return The specification vendor. - */ - public static String getImplVendor() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getImplementationVendor(); - } - - /** - * Returns the specification version. - * - * @return The specification version. - */ - public static String getImplVersion() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getImplementationVersion(); - } - - /** - * This class is a singleton. - */ - private Version() { - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/access/AccessService.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/access/AccessService.java deleted file mode 100644 index e5183e82..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/access/AccessService.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * - * ==================================================================== - * - * Copyright (c) 2001 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.access; - - -import net.jxta.credential.Credential; -import net.jxta.credential.PrivilegedOperation; -import net.jxta.document.Element; -import net.jxta.service.Service; - - -/** - * The Access Service is used by JXTA Applications and Services to determine if - specific operations are permitted for a particular identity. - * - *

Each Access Service implementation provides a mechanism for determining - * if, for a given operation and identity, the operation is permitted. - **/ -public interface AccessService extends Service { - - /** - * The result of an access check. - **/ - public enum AccessResult { - - /** - * State is unknown or could not be established. - * - *

The operation should not be performed. - * - *

This result may not be used by all Access Service - * implementations. - **/ - UNDETERMINED, /** - * Operation is disallowed. - * - *

The operation should not be performed. - * - **/ DISALLOWED, /** - * Operation is permitted. - * - *

The operation should be performed. - * - **/ PERMITTED, /** - * Operation would be permitted, but one (or more) of the provided - * credentials was expired. - * - *

The operation should not be performed. - * - *

This result may not be used by all Access Service - * implementations. - **/ PERMITTED_EXPIRED - } - - /** - * Determine if a privileged operation is permitted for a given identity. - * - * @param operation The operation which is being requested or {@code null}. - * {@code null} signifies that the operation is unimportant though the - * credential must be valid. - * @param credential The identity which is requesting or {@code null}. A - * {@code null} value indicates that no credential is available. - * @return the result of the access check. - **/ - public AccessResult doAccessCheck(PrivilegedOperation operation, Credential credential); - - /** - * Create a new privileged operation with the specified subject. Each - * operation is also associated with an identity, the offerer. Generally - * the privileged operation is cryptographically signed by the offerer. - * - * @see net.jxta.credential.Credential - * - * @param subject The subject of the operation. This usually identifies - * what operation is being requested. - * @param offerer The identity which is offering the operation. - * @return The privileged operation object - **/ - public PrivilegedOperation newPrivilegedOperation(Object subject, Credential offerer); - - /** - * Read a privileged operation from a portion of a structured document. - * - * @param source The root of the document portion containing the serialized - * representation of the privileged operation. - * @return The privileged operation object. - **/ - public PrivilegedOperation newPrivilegedOperation(Element source); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/access/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/access/package.html deleted file mode 100644 index e9f7516f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/access/package.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - The Access Service provides a framework for using the identities created - with the Membership Service to control whether specific operations are - permitted. - -

The Access Service, like the Membership Service, is not associated with - a particular JXTA protocol. Each Access Service implementation is - responsible for its own protocol definition (if any). This approach is used - primarily so that JXTA bridges well to existing common Membership and Access - technologies. For example; PKI, LDAP Kerberos, NTLM and API based interfaces - such as PAM and JAAS. - - @see net.jxta.credential.Credential - @see net.jxta.credential.PrivilegedOperation - @see net.jxta.membership.MembershipService - @see JXTA Protocols Specification : Protocols - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/Codat.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/Codat.java deleted file mode 100644 index 75a45844..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/Codat.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.codat; - - -import net.jxta.document.Document; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peergroup.PeerGroupID; - -import java.io.IOException; - - -/** - * The common container for managing content within JXTA. A Codat consists of: - *

    - *
  • Content data for the Codat in the form of a JXTA - * {@link net.jxta.document.Document}.
  • - *
  • A persistent canonical identifier for the Codat in the form of a - * {@link net.jxta.codat.CodatID}.
  • - *
  • An optional CodatID for an associated Codat for which this Codat is - * metadata.
  • - *
- * - * @see net.jxta.codat.CodatID - * @see net.jxta.document.Document - */ -public class Codat { - - /** - * CodatID of this Codat. A persistent canonical identifier for this Codat. - */ - private final CodatID id; - - /** - * CodatID for an associated Codat for which this Codat is metadata. This - * may be the CodatId of another Codat in the same Peer Group or - * null. - */ - private final CodatID metaId; - - /** - * Contains the data of this Codat. - */ - private final Document doc; - - /** - * Constructs a Codat instance with a new CodatId given a PeerGroupID and - * a Document. - * - * @param groupID The peer group to which this Codat will belong. - * @param about The CodatID of an associated Codat for which this Codat is - * metadata or null if there is no associated Codat. - * @param document Document which contains the content data for this Codat. - * @throws IOException if there is an error accessing the document. - */ - public Codat(PeerGroupID groupID, CodatID about, Document document) throws IOException { - this(IDFactory.newCodatID(groupID, document.getStream()), about, document); - } - - /** - * Constructs a Codat instance for an existing Codat given it's - * CodatID and a document. - *

- *

This implementation does not verify that the CodatID matches the - * provided Document. - * - * @param id CodatId of the new Codat. - * @param about CodatID of an associated Codat for which this Codat is metadata. - * @param document Document which contains the content data for this Codat. - */ - public Codat(CodatID id, CodatID about, Document document) { - if (null == id) { - throw new IllegalArgumentException("CodatID may not be null."); - } - - if (null == document) { - throw new IllegalArgumentException("Document may not be null."); - } - - this.id = id; - this.metaId = about; - this.doc = document; - } - - /** - * Returns the CodatID of this Codat. - * - * @return The CodatID of this Codat. - */ - public ID getCodatID() { - return id; - } - - /** - * Returns the CodatID of an associated Codat for which this Codat is - * metadata or null if there is no associated Codat. - * - * @return CodatID The CodatID of an associated Codat for which this Codat - * is metadata or null if there is no associated Codat. - */ - public ID getMetaID() { - return metaId; - } - - /** - * Returns a Document containing the data of this Codat. - * - * @return A Document containing the data of this Codat. - */ - public Document getDocument() { - return doc; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/CodatID.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/CodatID.java deleted file mode 100644 index 5e7c94d7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/CodatID.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.codat; - - -import java.net.URI; -import net.jxta.id.ID; - - -/** - * An identifier that enables canonical references to be made to a Codat within - * the context of a specific peer group. - *

- *

A CodatID is formed by the conjuction of:

    - *
  • a PeerGroupID
  • - *
  • a randomly chosen value that has a high probability of being unique
  • - *
  • an optional SHA1 cryptographic hash of the Codat contents
- *

- *

Codats which contain static content will normally include the hash value - * as part of their CodatID. - * - * @see net.jxta.codat.Codat - * @see net.jxta.peergroup.PeerGroupID - */ -public abstract class CodatID extends ID { - - /** - * Creates an ID by parsing the given URI. - * - *

This convenience factory method works as if by invoking the - * {@link net.jxta.id.IDFactory#fromURI(URI)} method; any - * {@link java.net.URISyntaxException} thrown is caught and wrapped in a - * new {@link IllegalArgumentException} object, which is then thrown. - * - *

This method is provided for use in situations where it is known that - * the given string is a legal ID, for example for ID constants declared - * within in a program, and so it would be considered a programming error - * for the URI not to parse as such. The {@link net.jxta.id.IDFactory}, - * which throws {@link java.net.URISyntaxException} directly, should be used - * situations where a ID is being constructed from user input or from some - * other source that may be prone to errors. - * - * @param fromURI The URI to be parsed into an ID - * @return The new ID - * - * @throws NullPointerException If {@code fromURI} is {@code null}. - * @throws IllegalArgumentException If the given URI is not a valid ID. - */ - public static CodatID create(URI fromURI) { - return (CodatID) ID.create(fromURI); - } - - /** - * {@inheritDoc} - */ - public CodatID intern() { - return (CodatID) super.intern(); - } - - /** - * Returns PeerGroupID of the Peer Group to which this Codat ID belongs. - * - * @return PeerGroupID of the Peer Group which this ID is part of. - */ - public abstract ID getPeerGroupID(); - - /** - * Returns true if this CodatID is associated with a static Codat. - * - * @return true if the codatId is for a Codat with static content - * otherwise false. - */ - public abstract boolean isStatic(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/Metadata.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/Metadata.java deleted file mode 100644 index 1d1f7bbd..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/Metadata.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.codat; - - -import net.jxta.document.Document; -import net.jxta.peergroup.PeerGroupID; - -import java.io.IOException; - - -/** - * Medata Codats are special codats that contain information about another - * Codat. Multiple medata Codats can refer to the same Codat. Medata codats can - * hold any kind of information about a codat, such as a symbolic name, - * description, index and searching information, etc. - * - * @see net.jxta.codat.Codat - * @see net.jxta.codat.CodatID - * @see net.jxta.document.Document - */ -public class Metadata extends Codat { - - /** - * Constructs a Metadata instance with a new CodatId given a PeerGroupID, - * the CodatID of the associated Codat and a Document. - * - * @param groupID The peer group to which this Codat will belong. - * @param about The CodatID of an associated Codat for which this Codat is - * metadata or null if there is no associated Codat. - * @param document Document which contains the content data for this Codat. - * @throws IOException if there is an error accessing the document. - */ - public Metadata(PeerGroupID groupID, CodatID about, Document document) throws IOException { - super(groupID, about, document); - } - - /** - * Constructs a Metadata instance for an existing Codat given it's - * CodatID, the CodatID of the associated Codat and a Document. - *

- *

This implementation does not verify that the CodatID matches the - * provided Document. - * - * @param id CodatId of the new Codat. - * @param about CodatID of an associated Codat for which this Codat is metadata. - * @param document Document which contains the content data for this Codat. - */ - public Metadata(CodatID id, CodatID about, Document document) { - super(id, about, document); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/package.html deleted file mode 100644 index 7b4aa9a5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/codat/package.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - -Codats are container objects that can hold both data or code and are -associated with a JXTA ID. - -@see net.jxta.id -@see JXTA Protocols - Specification : Protocols - - -file:///home/mike/code/jxta/spec/www/v1.0/docbook/JXTAProtocols.html#overview-codats diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/AuthenticationCredential.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/AuthenticationCredential.java deleted file mode 100644 index 081e8364..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/AuthenticationCredential.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.credential; - -import net.jxta.document.*; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peergroup.PeerGroup; -import net.jxta.service.Service; - -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import java.util.logging.Logger; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - -/** - * Authenication credentials are used by JXTA Membership Services as the - * basis for applications for peergroup membership. The AuthenticationCredential - * provides two important pieces of inforamtion: - *

    - *
  • the authetication method being requested
  • - *
  • identity information which will be provided to that authentication - * method.
  • - *
      - *

      - * Not all authentication methods use the identity nformation. - * - * @see net.jxta.credential.Credential - * @see net.jxta.membership.MembershipService - * @see net.jxta.membership.Authenticator - */ -public final class AuthenticationCredential implements Credential { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(AuthenticationCredential.class.getName()); - - /** - * the authentication method which will be requested when this credential is - * provided during "apply" to a peergroup membership service. - */ - private String authenticationMethod = null; - - /** - * Any optional information which is required by the requested authentication method. - */ - private Element identityInfo = null; - - /** - * The peergroup of this AuthenticationCredential - */ - private final PeerGroup peergroup; - - /** - * Creates new AuthenticationCredential - * - * @param peergroup The peergroup context in which this - * AuthenticationCredential is created. - * @param method The authentication method which will be requested when the - * AuthentiationCredential is provided to the peergroup Membership Service. - * Authentication methods are specific to Membership services. Consult the - * Documentation for the Membership service you will be authenticating - * against in order to determine the valid method values. Every - * Membership service should support a default authentication method which - * can be specified as null. - * @param indentityInfo Optional additional information which is used by the - * authentication method or null. This information is passed to the - * authentication method during the apply operation of the Membership - * Service. Consult the documentation for the specific Membership Service - * you are using for details on how this information is used (if at all). - */ - public AuthenticationCredential(PeerGroup peergroup, String method, Element indentityInfo) { - this.peergroup = peergroup; - - authenticationMethod = method; - - if (null != indentityInfo) { - this.identityInfo = StructuredDocumentUtils.copyAsDocument(indentityInfo); - } - } - - /** - * Creates new AuthenticationCredential - * - * @param peergroup The peergroup context in which this - * AuthenticationCredential is created. - * @param root the document containing the serialized representation of the - * AuthenticationCredential. - */ - public AuthenticationCredential(PeerGroup peergroup, Element root) { - - this.peergroup = peergroup; - - initialize(root); - } - - /** - * {@inheritDoc} - *

      - * AuthenticationCredentials are created in the context of a PeerGroup - * though they are generally independant of peergroups. The intent is that - * the AuthenticationCredential will be passed to the MembershipService - * service of the same peergroup as the AuthenticationCredenitals. - * - * @return PeerGroupID associated with this AuthenticationCredential. - */ - public ID getPeerGroupID() { - return peergroup.getPeerGroupID(); - } - - /** - * {@inheritDoc} - */ - public ID getPeerID() { - return peergroup.getPeerID(); - } - - /** - * {@inheritDoc} - */ - public Service getSourceService() { - return null; - } - - /** - * {@inheritDoc} - *

      - * AuthenticationCredential are never expired. The Authenticator will - * determine the true validity from the included identity info. - */ - public boolean isExpired() { - return false; - } - - /** - * {@inheritDoc} - *

      - * AuthenticationCredential are always valid, the Authenticator will - * determine the true validity from the included identity info. - */ - public boolean isValid() { - return true; - } - - /** - * {@inheritDoc} - *

      - * There is no straightforward mechansim for identifying the subject - * unfortunately. - */ - public Object getSubject() { - return null; - } - - /** - * Write credential into a document. as is a mime media-type - * specification and provides the form of the document which is being - * requested. Two standard document forms are defined. "text/text" encodes - * the document in a form nice for printing out and "text/xml" which - * provides an XML format. - * - * @param as The mime media type of the encoding format being requested. - * @return the StructuredDocument which represents this credential. - * @throws Exception When errors occur. - */ - public StructuredDocument getDocument(MimeMediaType as) throws Exception { - - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(as, "jxta:Cred"); - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - ((Attributable) doc).addAttribute("xml:space", "preserve"); - ((Attributable) doc).addAttribute("type", "AuthenticationCredential"); - } - - Element e = doc.createElement("Method", getMethod()); - - doc.appendChild(e); - - e = doc.createElement("PeerGroupID", getPeerGroupID().toString()); - doc.appendChild(e); - - e = doc.createElement("PeerID", getPeerID().toString()); - doc.appendChild(e); - - if (null != identityInfo) { - e = doc.createElement("IdentityInfo"); - doc.appendChild(e); - - StructuredDocumentUtils.copyElements(doc, e, identityInfo); - } - - return doc; - } - - /** - * Returns the authentication method which this AuthenticationCredential - * will be requesting when it is provided to a Membership Service during the - * "Apply" operation. - * - * @return String containing the authentication method being requested. - */ - public String getMethod() { - return authenticationMethod; - } - - protected void setMethod(String authenticationMethod) { - this.authenticationMethod = authenticationMethod; - } - - /** - * Returns the StructuredDocument Element containing the identity information which was - * originally provided when this AuthenticationCredential was created. - * - * @return StructuredDocument Element containing the identity information which was - * originally provided when this AuthenticationCredential was created. - */ - public Element getIdentityInfo() { - return (null == identityInfo) ? null : StructuredDocumentUtils.copyAsDocument(identityInfo); - } - - /** - * Process an individual element from the document. - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - */ - protected boolean handleElement(TextElement elem) { - if (elem.getName().equals("PeerGroupID")) { - try { - URI gID = new URI(elem.getTextValue()); - ID pgid = IDFactory.fromURI(gID); - - if (!pgid.equals(getPeerGroupID())) { - throw new IllegalArgumentException("Operation is from a different group. " + pgid + " != " + getPeerGroupID()); - } - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Unusable ID in advertisement: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("PeerID")) { - try { - URI pID = new URI(elem.getTextValue()); - ID pid = IDFactory.fromURI(pID); - - if (!pid.equals(getPeerID())) { - throw new IllegalArgumentException("Operation is from a different group. " + pid + " != " + getPeerID()); - } - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad Peer ID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a peer id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("Method")) { - setMethod(elem.getTextValue()); - return true; - } - - if (elem.getName().equals("IdentityInfo")) { - Enumeration firstChild = elem.getChildren(); - - if (!firstChild.hasMoreElements()) { - throw new IllegalArgumentException("Missing identity info"); - } - - identityInfo = StructuredDocumentUtils.copyAsDocument((Element) firstChild.nextElement()); - - return true; - } - - // element was not handled - return false; - } - - /** - * Intialize from a portion of a structured document. - * - * @param root the element - */ - protected void initialize(Element root) { - - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports TextElement"); - } - - TextElement doc = (TextElement) root; - - String typedoctype = ""; - - if (root instanceof Attributable) { - Attribute itsType = ((Attributable) root).getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - } - - String doctype = doc.getName(); - - if (!"jxta:AuthenticationCredential".equals(doctype) && !"jxta:AuthenticationCredential".equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doctype); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - TextElement elem = (TextElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandleded element \'" + elem.getName() + "\' in " + doc.getName()); - } - } - } - - // sanity check time! - - // FIXME bondolo@jxta.org 20030409 check things - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/Credential.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/Credential.java deleted file mode 100644 index 9a42252b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/Credential.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.credential; - - -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.id.ID; -import net.jxta.service.Service; - - -/** - * Credentials provide the basic mechanisms for securely establishing and - * communicating identity within JXTA. Credentials have three different roles - * within JXTA: - *

      - *

        - *
      • Authentication credentials are associated with authentication methods - * and are used to provide information required for authentication. Each - * {@link net.jxta.credential.AuthenticationCredential AuthenticationCredential} - * implementation is specific to its associated - * {@link net.jxta.membership.Authenticator Authenticator}. Authentication - * Credentials are normally created by constructing a document which follows - * a schema provided by the authentication method.
      • - *

        - *

      • Identity credentials associate an identity with a peer. The peer may - * request operations to be performed using that identity. Identity Credentials - * are created by successfully completing authentication with a Membership - * Service.
      • - *

        - *

      • Privileged operations associate an operation with an identity. To - * request a remote peer to perform some operation an application or service - * provides a {@link net.jxta.credential.PrivilegedOperation} and an - * identity credential along with the request. The remote peer determines if - * the operation is permitted for the specified identity and if it is permitted, - * completes the operation.
      • - *
      - *

      - *

      The XML representation of a Credential uses the following very simple - * schema. Credential implementations extend this schema as needed. - *

      - *

      - * <xs:complexType name="Cred">
      - *   <xs:all>
      - *   </xs:all>
      - * </xs:complexType>
      - * 
      - */ -public interface Credential { - - /** - * Returns the peerGroupID associated with this credential. - * - * @return The peerGroupID associated with this credential. - */ - public ID getPeerGroupID(); - - /** - * Returns the peerID associated with this credential. - * - * @return The peerID associated with this credential. - */ - public ID getPeerID(); - - /** - * Returns the service which generated this credential. - * - * @return The service which generated this credential. - */ - public Service getSourceService(); - - /** - * Returns {@code true} if this credential is expired. Some credential - * implementations may never expire. - * - * @return {@code true} if this credential is expired, otherwise - * {@code false}. - */ - public boolean isExpired(); - - /** - * Returns {@code true} if this credential is currently valid. - * - * @return {@code true} if the credential is currently valid, otherwise - * {@code false}. - */ - public boolean isValid(); - - /** - * Returns the subject of this credential. The Objects returned must - * support {@link Object#equals(Object)} and {@link Object#hashCode()}. - * - * @return The subject of the credential as an abstract object. - */ - public Object getSubject(); - - /** - * Write credential into a document. asMimeType is a mime - * media-type specification and provides the form of the document which is - * being requested. Two standard document forms are defined. - * "{@code text/plain}" encodes the document in a "pretty-print" format - * for human viewing and "{@code text/xml}" which provides an XML format. - *

      - *

      Depending on the credential format this document may be - * cryptographically signed to prevent alteration. - * - * @param asMimeType MimeMediaType format representation requested - * @return The credential serialized to a Document. - * @throws Exception if an error occurs - */ - public StructuredDocument getDocument(MimeMediaType asMimeType) throws Exception; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/CredentialPCLSupport.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/CredentialPCLSupport.java deleted file mode 100644 index 16bc378d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/CredentialPCLSupport.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.credential; - - -import java.beans.PropertyChangeListener; - - -/** - * Provides Property Change Listener support for Credentials. - */ -public interface CredentialPCLSupport { - - /** - * Property name for the expired bound property. - */ - public final static String EXPIRED_CREDENTIAL_PROPERTY = "expired"; - - /** - * Property name for valid bound property. - */ - public final static String VALID_CREDENTIAL_PROPERTY = "valid"; - - /** - * Add a listener - * - * @param listener the listener - */ - public void addPropertyChangeListener(PropertyChangeListener listener); - - /** - * Add a listener. Available properties from all Credentials are : - *

      - *

        - *
      • expired
      • - *
      • valid
      • - *
      - * - * @param propertyName the property to watch - * @param listener the listener - */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener); - - /** - * Remove a listener - * - * @param listener the listener - */ - public void removePropertyChangeListener(PropertyChangeListener listener); - - /** - * Remove a listener - * - * @param propertyName the property which was watched - * @param listener the listener - */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/CredentialValidator.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/CredentialValidator.java deleted file mode 100644 index 8e57de9a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/CredentialValidator.java +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.credential; - - -/** - * CredentialValidator defines the interface for allowing external validation of a credential - * - */ -public interface CredentialValidator { - - /** - * Called when a credential verfication is needed. - * @param cred the credential to verify, Credential can be null. - * @return true if verified - */ - public boolean checkCred(Credential cred); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/PrivilegedOperation.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/PrivilegedOperation.java deleted file mode 100644 index e8c83c96..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/PrivilegedOperation.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - - * - * ==================================================================== - * - * Copyright (c) 2001 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.credential; - - -/** - * A Privileged Operation is an identifier for an operation whose usage is - * restricted. It is represented as a credential so that users and providers - * can prevent the unauthorized creation of privledges. - *

      - *

      Each operation is associated with an offerer. The offerer is the - * identity which created the operation. - */ -public interface PrivilegedOperation extends Credential { - - /** - * Returns the offerer of this operation. The offerer is the identity which - * created the operation. - * - * @return the offerer of the operation. - */ - public Credential getOfferer(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/package.html deleted file mode 100644 index 4c201736..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/credential/package.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - -Credentials provide the basic mechanisms for securly establishing and -communicating identity within JXTA. - -@see JXTA Protocols - Specification : Protocols - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/DiscoveryEvent.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/DiscoveryEvent.java deleted file mode 100644 index 0c6cdabf..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/DiscoveryEvent.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.discovery; - - -import java.util.Enumeration; -import java.util.EventObject; -import net.jxta.document.Advertisement; -import net.jxta.protocol.DiscoveryResponseMsg; - - -/** - * Container for DiscoveryService events. The source of the event is the Endpoint - * address of the responding peer - */ -public class DiscoveryEvent extends EventObject { - - private final DiscoveryResponseMsg response; - private final int queryID; - - /** - * Creates a new event - * - * @see net.jxta.protocol.DiscoveryResponseMsg - * @see net.jxta.protocol.ResolverResponseMsg - * - * @param source The source of the event is the Endpoint address of the responding peer - * @param response The response message for which this event is being generated. - * @param queryid The query id associated with the response returned in this event - */ - public DiscoveryEvent(Object source, DiscoveryResponseMsg response, int queryid) { - super(source); - this.response = response; - this.queryID = queryid; - } - - /** - * Returns the response associated with the event - * - * @return DiscoveryResponseMsg - * - * @see net.jxta.protocol.DiscoveryResponseMsg - */ - public DiscoveryResponseMsg getResponse() { - - return response; - } - - /** - * Returns the query id associated with the response returned in this event - * - * @return query id associated with the response - */ - public int getQueryID() { - - return queryID; - } - - /** - * Returns an array of advertisements contained in the DiscoveryResponse - * for this event. - * - * @return Enumeration of Advertisements - */ - public Enumeration getSearchResults() { - - return response.getAdvertisements(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/DiscoveryListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/DiscoveryListener.java deleted file mode 100644 index f3d47e7d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/DiscoveryListener.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.discovery; - - -import java.util.EventListener; - - -/** - * The listener interface for receiving {@link DiscoveryEvent}s from the - * Discovery Service. - * - * The following 2 examples illustrate how to implement a - * DiscoverListener: - * - *

      Example 1: - *

      - * DiscoveryListener myListener = new DiscoveryListener() {
      - *   public void discoveryEvent(DiscoveryEvent e) {
      - *     DiscoveryResponseMsg msg = e.getResponse();
      - *     if (myQueryID == e.getQueryID()) {
      - *       int advCount = msg.getResponseCount();
      - *     }
      - *   }
      - *   discovery.addDiscoveryListener(myListener);
      - *   int myQueryID = discovery.getRemoteAdvertisements(address,
      - *     discovery.GROUP, attr, val,threshold);
      - * 
      - * - *

      Example 2: - *

      - * public class JxtaAppDemo implements Runnable, DiscoveryListener {
      - *          ..
      - *          ..
      - *  public void discoveryEvent(DiscoveryEvent ev) {
      - *
      - *     DiscoveryResponseMsg res = ev.getResponse();
      - *     ..
      - *     ..
      - *     // see tutorial example 2 for full source
      - *     // JXTA Tutorials
      - *     }
      - * }
      - * 
      - * - * @see net.jxta.discovery.DiscoveryService - * @see net.jxta.discovery.DiscoveryEvent - **/ -public interface DiscoveryListener extends EventListener { - - /** - * Called to handle an event from the Discovery Service. - * - * @param event the discovery event - */ - void discoveryEvent(DiscoveryEvent event); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/DiscoveryService.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/DiscoveryService.java deleted file mode 100644 index 62ce541f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/DiscoveryService.java +++ /dev/null @@ -1,506 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.discovery; - - -import java.io.IOException; -import java.util.Enumeration; - -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.service.Service; - - -/** - * Provides an asynchronous mechanism for discovering Advertisement (Peers, - * Groups, Pipes, Modules, etc.). The scope of discovery queries can be - * controlled by specifying a name and attribute pair, and/or a threshold. - * The threshold is an upper limit the requesting peer specifies for - * responding peers not to exceed. Each JXTA Peer Group has an instance of - * a DiscoveryService. The scope of discovery is limited to the group. For - * example : - * - *

      A peer in the soccer group invokes the soccer group's DiscoveryService - * to discover pipe advertisements for the Score tracker service in the group, - * and is interested in a maximum of 10 Advertisements from each peer: - *

      - *  discovery.getRemoteAdvertisements(null, discovery.ADV,
      - *                                    "Name", "Score tracker*", 10, null);
      - *
      - * 
      - * - *

      In the above example, peers that are part of the soccer group would - * respond. After a getRemoteAdvertisements call is made and the peers respond, - * a call to getLocalAdvertisements can be made to retrieve results that have - * been found and added to the local group cache. Alternately, a call to - * addDiscoveryListener() will provide asynchronous notification of discovered - * advertisements. - * - *

      When an Advertisement is published, it is stored, and indexed in the - * peer's local cache. The Advertisement indexes are also shared with - * Rendezvous peers. Advertisement indexes may not be shared with other - * peers immediately, but may be updated as part of a periodic process. The - * Discovery Service currently updates remote indexes every 30 seconds. - * - *

      It is important to note that what is shared with the rendezvous peer is - * the index and expiration of the advertisement, not the advertisement. The - * indexes are republished whenever the peer establishes a new connection with - * a different rendezvous peer. - * - *

      Distributed index garbage collection. A rendezvous peer will GC indexes for - * a specific peer when it receive a disconnect message, or it has determined - * that a peer is no longer reachable, the latter action is a lazy GC and is - * triggered by messenger creation failures which results in a mark and sweep at - * a future point in time. - * - *

      DiscoveryService also provides a mechanism for publishing advertisements, - * so that they may be discovered. The rules to follow when publishing are: - * - *

        - *
      • - * Use the current discovery service to publish advertisements private to the - * group. - *
        discovery.publish(adv);
        - * 
      • - * - *
      • Use the parent's discovery to publish advertisements that public outside - * of the group. Example : a peer would like publish the "soccer" group in the - * NetPeerGroup - *
        - *        parent=soccerGroup.getParent();
        - *        discovery= parent.getDiscoveryService()
        - *        discovery.publish(adv);
        - * 
      • - *
      - * - *

      The threshold can be utilized in peer discovery in situations where a peer - * is only interested in other peers, and not about additional peers they may - * know about. To achieve this effect for peer discovery set the Threshold to - * 0 (zero). - * - *

      Advertisements are often stored in a persistent local cache. This cache - * can improve performance and responsiveness by retaining advertisements - * between restarts. - * - *@see net.jxta.service.Service - *@see net.jxta.resolver.ResolverService - *@see net.jxta.protocol.DiscoveryQueryMsg - *@see net.jxta.protocol.DiscoveryResponseMsg - *@see net.jxta.protocol.ResolverQueryMsg - *@see net.jxta.protocol.ResolverResponseMsg - */ -public interface DiscoveryService extends Service { - - /** - * Discovery type Peer - */ - public final static int PEER = 0; - - /** - * Discovery type Group - */ - public final static int GROUP = 1; - - /** - * Discovery type Advertisement - */ - public final static int ADV = 2; - - /** - * Default lifetime time for advertisements. This is the maximum - * amount of time which the advertisement will remain valid. If the - * advertisement remains valid after this time, then the creator will - * need to republish the advertisement. - */ - public final static long DEFAULT_LIFETIME = 1000L * 60L * 60L * 24L * 365L; - - /** - * Default expiration time for advertisements. This is the amount of - * time which advertisements will live in caches. After this time, the - * advertisement should be refreshed from the source. - */ - public final static long DEFAULT_EXPIRATION = 1000L * 60L * 60L * 2L; - - /** - * Infinite lifetime for advertisements. The advertisement is valid - * forever. (well maybe it will expire when the sun burns out, but not - * before then). - */ - public final static long INFINITE_LIFETIME = Long.MAX_VALUE; - - /** - * Specifies that the advertisement will have no expiration and will be - * kept indefinitely. - */ - public final static long NO_EXPIRATION = Long.MAX_VALUE; - - /** - * Discover advertisements from remote peers. This does not normally - * provide an exhaustive search. Instead it provides a "best efforts" - * search which will provide a selection of advertisements of matching the - * search criteria. The selection of advertisements returned may be random - * or predictable depending upon the network configuration and no - * particular behaviour should be assumed. In general the narrower the - * query specified the more exhaustive the responses will be. - * - *

      Discovery can be performed in two ways :

        - *
      • With a null peerid - The discovery query is - * propagated on via the Rendezvous Service and via local sub-net - * utilizing IP multicast.
      • - *
      • With a provided peerid - The discovery query is forwarded to the - * specified peer.
      • - *
      - * - *

      The scope of advertisements returned can be narrowed by specifying - * an {@code attribute} and {@code value} pair. The {@code attribute} is - * a case-sensitive string matching the name of an Advertisement XML tag - * who's values will be matched by the {@code value}. Only a limited number - * of Advertisement XML fields are indexed. {@link - * net.jxta.document.Advertisement#getIndexFields()} will return the - * fields on which you may query for a particular Advertisement type. - * - *

      The {@code value} is a case-insensitive string who's value is - * matched against the values of {@code attribute} fields of Advertisements. - * The {@code} value may be of several forms : - *

        - *
      • {@code null} - Don't care. All advertisements with the matching - * {@code attribute} will be returned.
      • - *
      • exact value - Only advertisements with an {@code attribute} - * field who's value exactly matches the string {@code value} will be - * returned.
      • - *
      • wild card - Only advertisements with an {@code attribute} - * field who's value matches the wild card expression {@code value} - * will be returned. eg. The following expressions all match against - * "FooBar": - *
          - *
        • {@code foO*}
        • - *
        • {@code *Bar}
        • - *
        • {@code *oBA*}
        • - *
      • - *
      - * - * @param peerid If provided the query will be forwarded to the specified - * peer. If {@code null} then the query will be propagated through the - * network to peers with matching Advertisements. - * @param type Discovery type; PEER, GROUP or ADV. - * @param attribute indexed element name (see advertisement(s) for a - * list of indexed fields. A null attribute indicates any advertisement - * of specified type - * @param value value of attribute to narrow discovery to. Valid values for - * this parameter are null (don't care), Exact value, or use of wild - * card(s) (e.g. if a Advertisement defines FooBar , a value - * of "*bar", "foo*", or "*ooB*", will return the Advertisement - * @param threshold The maximum number of matching advertisements which - * be returned by each responding peer. A {@code threshold} of 0, and - * {@code type} of {@code PEER} has a special behaviour. - * @return query ID for this discovery query. - */ - public int getRemoteAdvertisements(String peerid, int type, String attribute, String value, int threshold); - - /** - * Discover advertisements from remote peers. This does not normally - * provide an exhaustive search. Instead it provides a "best efforts" - * search which will provide a selection of advertisements of matching the - * search criteria. The selection of advertisements returned may be random - * or predictable depending upon the network configuration and no - * particular behaviour should be assumed. In general the narrower the - * query specified the more exhaustive the responses will be. - * - *

      Discovery can be performed in two ways :

        - *
      • With a {@code null} peerid - The discovery query is - * propagated on via the Rendezvous Service and via local sub-net - * utilizing IP multicast.
      • - *
      • With a provided peerid - The discovery query is forwarded to the - * specified peer.
      • - *
      - * - *

      The scope of advertisements returned can be narrowed by specifying - * an {@code attribute} and {@code value} pair. The {@code attribute} is - * a case-sensitive string matching the name of an Advertisement XML tag - * who's values will be matched by the {@code value}. Only a limited number - * of Advertisement XML fields are indexed. {@link - * net.jxta.document.Advertisement#getIndexFields()} will return the - * fields on which you may query for a particular Advertisement type. - * - *

      The {@code value} is a case-insensitive string who's value is - * matched against the values of {@code attribute} fields of Advertisements. - * The {@code} value may be of several forms : - *

        - *
      • {@code null} - Don't care. All advertisements with the matching - * {@code attribute} will be returned.
      • - *
      • exact value - Only advertisements with an {@code attribute} - * field who's value exactly matches the string {@code value} will be - * returned.
      • - *
      • wild card - Only advertisements with an {@code attribute} - * field who's value matches the wild card expression {@code value} - * will be returned. eg. The following expressions all match against - * "FooBar": - *
          - *
        • {@code fOo*}
        • - *
        • {@code *bAr}
        • - *
        • {@code *OBa*}
        • - *
      • - *
      - * - * @param peerid If provided the query will be forwarded to the specified - * peer. If {@code null} then the query will be propagated through the - * network to peers with matching Advertisements. - * @param type Discovery type; PEER, GROUP or ADV. - * @param attribute indexed element name (see Advertisement(s) for a - * list of indexed fields. A null attribute indicates any advertisement - * of specified type - * @param value value of attribute to narrow discovery to. Valid values - * for this parameter or {@code null} (don't care), Exact value, or use - * of wild card(s) (e.g. if a Advertisement defines FooBar, - * a value of "*bar", "foo*", or "*ooB*", will return the Advertisement - * @param threshold The maximum number of matching advertisements which - * be returned by each responding peer. A {@code threshold} of 0, and - * {@code type} of {@code PEER} has a special behaviour. - * @param listener The listener which will be called when advertisement - * which match this query are discovered or {@code null} if no - * callback is desired. - * @return query ID for this discovery query. - */ - public int getRemoteAdvertisements(String peerid, int type, String attribute, String value, int threshold, DiscoveryListener listener); - - /** - * Retrieve locally stored Advertisements. This is an exhaustive search of - * the locally cached results. All valid known matching results will be - * returned. - * - * @param type Discovery type; PEER, GROUP or ADV. - * @param attribute indexed element name (see Advertisement(s) for a - * list of indexed fields. {@code null} indicates any advertisement - * of specified type - * @param value value of attribute to narrow discovery to valid - * values for this parameter are {@code null} (don't care), Exact - * value, or use of wild card(s) (e.g. if a Advertisement defines - * FooBar , a value of "*bar", "foo*", or "*ooB*", will - * return the Advertisement - * @return Enumeration of stored advertisements. - * @throws IOException Thrown if an error occurs during retrieval. - */ - public Enumeration getLocalAdvertisements(int type, String attribute, String value) throws IOException; - - /** - * Publish an Advertisement. The Advertisement will expire automatically - * on the local peer after DEFAULT_LIFETIME and will expire on - * other peers after DEFAULT_EXPIRATION. - * - *

      When an Advertisement is published, it is stored, and indexed in the - * peer's local cache. The Advertisement indexes are also shared with - * Rendezvous peers. Advertisement indexes may not be shared with other - * peers immediately, but may be updated as part of a periodic process. The - * Discovery Service currently publishes index updates every 30 seconds. - * - * @param adv The Advertisement to publish. - * @throws IOException When an error occurs during Advertisement publication. - */ - public void publish(Advertisement adv) throws IOException; - - /** - * Publish an Advertisement. The Advertisement will expire automatically - * after the specified time. A peer that discovers this advertisement will - * hold it for about expiration or lifetime milliseconds, - * whichever is smaller. - * - *

      When an Advertisement is published, it is stored, and indexed in the - * peer's local cache. The Advertisement indexes are also shared with - * Rendezvous peers. Advertisement indexes may not be shared with other - * peers immediately, but may be updated as part of a periodic process. The - * Discovery Service currently publishes index updates every 30 seconds. - * - * @param adv The Advertisement to publish. - * @param lifetime Duration in relative milliseconds that this advertisement will exist. - * @param expiration Duration in relative milliseconds that this advertisement will be cached by other peers. - * @throws IOException When an error occurs during Advertisement publication. - */ - public void publish(Advertisement adv, long lifetime, long expiration) throws IOException; - - /** - * Publish an Advertisement via propagation to other peers on the network. - * This does not result in the advertisement being stored locally. The - * Advertisement will be published with an expiration time of - * DEFAULT_EXPIRATION. - * - * @param adv Advertisement to publish. - */ - public void remotePublish(Advertisement adv); - - /** - * Publish an Advertisement via propagation to other peers on the network. - * This does not result in the advertisement being stored locally. - * - * @param adv The Advertisement to publish. - * @param expiration Duration in relative milliseconds that this - * Advertisement will be cached by other peers. - */ - public void remotePublish(Advertisement adv, long expiration); - - /** - * Publish an Advertisement to another peer on the network. - * This does not result in the advertisement being stored locally. The - * Advertisement will be published with an expiration time of - * DEFAULT_EXPIRATION. - * - *@param peerid The ID of a peer, specifying null results in - * propagation within the group. - *@param adv The Advertisement to publish. - */ - public void remotePublish(String peerid, Advertisement adv); - - /** - * Publish an Advertisement to another peer on the network. This does not - * result in the advertisement being stored locally. - * - * @param peerid id of a peer, specifying null results in a propagate - * within the group - * @param adv The Advertisement to publish. - * @param expiration Duration in relative milliseconds that this - * Advertisement will be cached by other peers. - */ - public void remotePublish(String peerid, Advertisement adv, long expiration); - - /** - * Removes the specified Advertisement from the cache of locally stored - * Advertisements. - * - * @param adv Advertisement to remove. - * @throws IOException If there is a problem removing the advertisement. - */ - public void flushAdvertisement(Advertisement adv) throws IOException; - - /** - * Removes the specified Advertisement from the cache of locally stored - * Advertisements. - * - * @param id The {@link Advertisement#getID()} value of the - * Advertisement to be removed. - * @param type Discovery type PEER, GROUP, ADV. - * @throws IOException If there is a problem removing the advertisement. - */ - public void flushAdvertisements(String id, int type) throws IOException; - - /** - * Returns the maximum duration in milliseconds for which this document - * will be cached by peers other than the publisher. This value is either - * the stored lifetime or the remaining lifetime of the document, whichever - * is less. - * - * @param id Document ID, Peer ID, or PeerGroup ID - * @param type Discovery type PEER, GROUP, ADV - * @return The number of milliseconds that other peers will be told to - * retain this Advertisement in their local caches. -1 is returned if - * the Advertisement is not known or already expired. - */ - public long getAdvExpirationTime(ID id, int type); - - /** - * Returns the maximum duration in milliseconds for which this document - * should be kept in local cache. - * - * @param id Document ID, Peer ID, or PeerGroup ID - * @param type Discovery type PEER, GROUP, ADV - * @return The number of milliseconds this Advertisement will remain in the - * local cache unless refreshed before that time. -1 is returned if the - * Advertisement is not known or already expired. - */ - public long getAdvLifeTime(ID id, int type); - - /** - * Returns the maximum duration in milliseconds for which this document - * will be cached by peers other than the publisher. This value is either - * the stored lifetime or the remaining lifetime of the document, whichever - * is less. - * - * @param adv Advertisement - * @return The number of milliseconds that other peers will be told to - * retain this Advertisement in their local caches. -1 is returned if - * the Advertisement is not known or already expired. - */ - public long getAdvExpirationTime(Advertisement adv); - - /** - * Returns the maximum duration in milliseconds for which this document - * should be kept in local cache. - * - * @param adv Advertisement - * @return The number of milliseconds this Advertisement will remain in the - * local cache unless refreshed before that time. -1 is returned if the - * Advertisement is not known or already expired. - */ - public long getAdvLifeTime(Advertisement adv); - - /** - * Register a Discovery listener. The Discovery listener will be called - * whenever Advertisement responses are received from remote peers by the - * Discovery Service. - * - * @param listener the DiscoveryListener - */ - public void addDiscoveryListener(DiscoveryListener listener); - - /** - * Remove a Discovery listener which was previously registered with - * {@link #getRemoteAdvertisements(String,int,String,String,int,DiscoveryListener) getRemoteAdvertisements()} - * or {@link #addDiscoveryListener(DiscoveryListener) addDiscoveryListener()}. - * - * @param listener The listener to be removed. - * @return true if the listener was successfully removed, false otherwise - */ - public boolean removeDiscoveryListener(DiscoveryListener listener); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/package.html deleted file mode 100644 index c304dd16..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/discovery/package.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - The JXTA Discovery Service provides an asynchronous mechanism for - discovering Peer Advertisements, Group Advertisements, and other general - JXTA Advertisements (pipes, services, etc.). - - @see net.jxta.resolver - @see net.jxta.document.Advertisement - @see JXTA Protocols Specification : Peer Discovery Protocol - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Advertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Advertisement.java deleted file mode 100644 index 88b88c8e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Advertisement.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.UndeclaredThrowableException; -import java.lang.reflect.Method; - -import net.jxta.id.ID; - - -/** - * Advertisements are core JXTA objects that are used to advertise Peers, - * PeerGroups, Services, Pipes or other JXTA resources. Advertisements provide - * a platform independent representation of core platform objects that can be - * exchanged between different platform implementations (Java, C, etc.). - * - *

      Each Advertisement holds a document that represents the advertisement. - * Advertisements are typically represented as a text document (XML). The - * {@link Advertisement#getDocument(MimeMediaType) getDocument(mimetype)} - * method is used to generate representations of the advertisement. Different - * representations are available via mime type selection. Typical mime types - * are "text/xml" or "text/plain" that generate textual representations for the - * Advertisements. - * - *

      Advertisements are created via {@link AdvertisementFactory} rather than - * through use of constructors. This is done because public the Advertisement - * sub-classes are typically abstract. The actual implementations are provided - * by private sub-classes. - * - * @see net.jxta.document.AdvertisementFactory - * @see net.jxta.document.ExtendableAdvertisement - * @see net.jxta.id.ID - * @see net.jxta.document.Document - * @see net.jxta.document.MimeMediaType - */ -public abstract class Advertisement { - - /** - * {@inheritDoc} - */ - @Override - public Advertisement clone() throws CloneNotSupportedException { - return (Advertisement) super.clone(); - } - - /** - * Return a string representation of this advertisement. The string will - * contain the advertisement pretty-print formatted as a UTF-8 encoded XML - * Document. - * - * @return A String containing the advertisement. - */ - @Override - public String toString() { - XMLDocument doc = (XMLDocument) getDocument(MimeMediaType.XMLUTF8); - - // Force pretty printing - doc.addAttribute("xml:space", "default"); - - return doc.toString(); - } - - /** - * Returns the identifying type of this Advertisement. - * - *

      Note: This is a static method. It cannot be used to determine - * the runtime type of an advertisement. ie. - *

      -     *      Advertisement adv = module.getSomeAdv();
      -     *      String advType = adv.getAdvertisementType();
      -     *  
      - * - *

      This is wrong and does not work the way you might expect. - * This call is not polymorphic and calls - * {@code Advertisement.getAdvertisementType()} no matter what the real - * type of the advertisement. - * - * @return The type of advertisement. - */ - public static String getAdvertisementType() { - throw new UnsupportedOperationException( - "Advertisement : sub-class failed to override getAdvertisementType. getAdvertisementType() is static and is *not* polymorphic."); - } - - /** - * Returns the identifying type of this Advertisement. Unlike - * {@link #getAdvertisementType()} this method will return the correct - * runtime type of an Advertisement object. - *

      - * This implementation is provided for existing advertisements which do not - * provide their own implementation. In most cases you should provide your - * own implementation for efficiency reasons. - * - * @since JXSE 2.1.1 - * @return The identifying type of this Advertisement. - */ - public String getAdvType() { - try { - Method getAdvertisementTypeMethod = this.getClass().getMethod("getAdvertisementType", (Class[]) null); - String result = (String) getAdvertisementTypeMethod.invoke(null, (Object[]) null); - - return result; - } catch (NoSuchMethodException failed) { - UnsupportedOperationException failure = new UnsupportedOperationException("Could not get Advertisement type."); - - failure.initCause(failed); - throw failure; - } catch (IllegalAccessException failed) { - SecurityException failure = new SecurityException("Could not get Advertisement type."); - - failure.initCause(failed); - throw failure; - } catch (InvocationTargetException failed) { - UndeclaredThrowableException failure = new UndeclaredThrowableException(failed, "Failed getting Advertisement type."); - - failure.initCause(failed.getCause()); - throw failure; - } - } - - /** - * Write this advertisement into a document of the requested type. Two - * standard document forms are defined. "text/plain" encodes - * the document in a "pretty-print" format for human viewing and - * "text/xml" which provides an XML format. - * - * @param asMimeType MimeMediaType format representation requested. - * @return The {@code Advertisement} represented as a {@code Document} of - * the requested MIME Media Type. - */ - public abstract Document getDocument(MimeMediaType asMimeType); - - /** - * Returns an ID which identifies this {@code Advertisement} as uniquely as - * possible. This ID is typically used as the primary key for indexing of - * the Advertisement within databases. - *

      - * Each advertisement sub-class must choose an appropriate implementation - * which returns canonical and relatively unique ID values for it's - * instances. Since this ID is commonly used for indexing, the IDs returned - * must be as unique as possible to avoid collisions. The value for the ID - * returned can either be: - *

      - *

        - *
      • An ID which is already part of the advertisement definition - * and is relatively unique between advertisements instances. For - * example, the Peer Advertisement returns the Peer ID.
      • - * - *
      • A static CodatID which is generated via some canonical process - * which will produce the same value each time and different values for - * different advertisements of the same type.
      • - * - *
      • ID.nullID for advertisement types which are not readily indexed. - *
      • - *
      - *

      - * For Advertisement types which normally return non-ID.nullID values - * no ID should be returned when asked to generate an ID while the - * Advertisement is an inconsistent state (example: uninitialized index - * fields). Instead {@link java.lang.IllegalStateException} should be - * thrown. - * - * @return An ID that relatively uniquely identifies this advertisement - * or {@code ID.nullID} if this advertisement is of a type that is not - * normally indexed. - */ - public abstract ID getID(); - - /** - * Returns the element names on which this advertisement should be indexed. - * - * @return The element names on which this advertisement should be indexed. - */ - public abstract String[] getIndexFields(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/AdvertisementFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/AdvertisementFactory.java deleted file mode 100644 index aa870cdf..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/AdvertisementFactory.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.InputStream; -import java.io.Reader; -import java.util.HashMap; -import java.util.Map; - -import java.io.IOException; -import java.util.NoSuchElementException; -import java.util.MissingResourceException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.util.ClassFactory; - - -/** - * A Factory class for constructing Advertisements. This class abstracts the - * the implementations used to represent and create advertisements. - * - *

      Advertisements are core objects that are used to advertise a Peer, a - * PeerGroup, a Service, a Pipe, etc. The Advertisement class provides a - * platform independent representation of core objects that can be exchanged - * between different implementations (Java, C). - * - *

      The AdvertisementFactory extends the ClassFactory to register the various - * types of advertisements into an internal table. The factory is called with - * the Advertisement type requested to create the corresponding advertisement - * type. - * - *

      The set of Advertisements types supported is loaded from the JXTA - * classpath via the service provider interface. - * - * @see net.jxta.document.Advertisement - * @see net.jxta.document.Document - * @see net.jxta.document.MimeMediaType - * @see net.jxta.peergroup.PeerGroup - * @see net.jxta.protocol.PeerAdvertisement - * @see net.jxta.protocol.PeerGroupAdvertisement - * @see net.jxta.protocol.PipeAdvertisement - */ -public class AdvertisementFactory extends ClassFactory { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(AdvertisementFactory.class.getName()); - - /** - * Interface for instantiators of Advertisements - */ - public interface Instantiator { - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - String getAdvertisementType(); - - /** - * Constructs an instance of {@link Advertisement} matching the type - * specified by the advertisementType parameter. - * - * - * @return The instance of {@link Advertisement}. - */ - Advertisement newInstance(); - - /** - * Constructs an instance of {@link Advertisement} matching the type - * specified by the advertisementType parameter. - * - * @param root Specifies a portion of a @link StructuredDocument} which - * will be converted into an Advertisement. - * @return The instance of {@link Advertisement}. - */ - Advertisement newInstance(net.jxta.document.Element root); - } - - /** - * This class is a singleton. This is the instance that backs the - * static methods. - */ - private final static AdvertisementFactory factory = new AdvertisementFactory(); - - /** - * This is the map of mime-types and constructors used by - * {@code newAdvertisement}. - */ - private final Map encodings = new HashMap(); - - /** - * If true then the pre-defined set of StructuredDocument sub-classes has - * been registered from the property containing them. - */ - private boolean loadedProperty = false; - - /** - * Private constructor. This class is not meant to be instantiated except - * by itself. - * - */ - private AdvertisementFactory() {} - - /** - * Registers the pre-defined set of Advertisement sub-classes so that - * this factory can construct them. - * - * @return true if at least one of the Advertisement sub-classes could - * be registered otherwise false. - */ - private synchronized boolean loadProviders() { - if (!factory.loadedProperty) { - factory.loadedProperty = registerProviders(Advertisement.class.getName()); - } - - return factory.loadedProperty; - } - - /** - * {@inheritDoc} - */ - @Override - protected Map getAssocTable() { - return encodings; - } - - /** - * {@inheritDoc} - */ - @Override - public Class getClassOfInstantiators() { - // our key is the doctype names. - return Instantiator.class; - } - - /** - * {@inheritDoc} - */ - @Override - public Class getClassForKey() { - // our key is the doctype names. - return java.lang.String.class; - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean registerAssoc(String className) { - boolean registeredSomething = false; - - try { - Class advClass = Class.forName(className + "$Instantiator"); - - Instantiator instantiator = (Instantiator) advClass.newInstance(); - - String advType = instantiator.getAdvertisementType(); - - registeredSomething = registerAdvertisementInstance(advType, instantiator); - } catch (Exception all) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Failed to register \'" + className + "\'", all); - } - } - - return registeredSomething; - } - - /** - * Register an instantiator for and advertisement type to allow instances - * of that type to be created. - * - * @param rootType the identifying value for this advertisement instance - * type. - * @param instantiator the instantiator to use in constructing objects - * of this rootType. - * @return boolean true if the rootType type is registered. If there is - * already a constructor for this type then false will be returned. - */ - public static boolean registerAdvertisementInstance(String rootType, Instantiator instantiator) { - boolean result = factory.registerAssoc(rootType, instantiator); - - return result; - } - - /** - * Constructs a new instance of {@link Advertisement} matching the type - * specified by the {@code advertisementType} parameter. - * - * @param advertisementType Specifies the type of advertisement to create. - * @return The instance of {@link Advertisement}. - * @throws NoSuchElementException if there is no matching advertisement type. - */ - public static Advertisement newAdvertisement(String advertisementType) { - factory.loadProviders(); - - Instantiator instantiator = factory.getInstantiator(advertisementType); - - Advertisement a = instantiator.newInstance(); - - return a; - } - - /** - * Constructs an instance of {@link Advertisement} from the provided - * InputStream. The content type of the stream is declared via - * the mimetype parameter. - * - * @deprecated Please convert your code to construct an {@code XMLDocument} - * using {@code StructuredDocumentFactory} and then call - * {@link AdvertisementFactory#newAdvertisement(XMLElement)}. For example : - *

      -     *   XMLDocument xml = (XMLDocument) StructuredDocumentFactory.newStructuredDocument( MimeMediaType.XMLUTF8, is );
      -     * 
      - * or frequently: - *

      -     *   XMLDocument xml = (XMLDocument) StructuredDocumentFactory.newStructuredDocument( msgElement );
      -     * 
      - * followed by: - *

      -     *   Advertisement adv = AdvertisementFactory.newAdvertisement(xml);
      -     * 
      - * - * @param mimetype Specifies the mime media type of the stream being read. - * @param stream input stream used to read data to construct the advertisement - * @return The instance of {@link Advertisement} - * @throws IOException error reading message from input stream - * @throws NoSuchElementException if there is no matching advertisement type - * for the type of document read in. - */ - @Deprecated - public static Advertisement newAdvertisement(MimeMediaType mimetype, InputStream stream) throws IOException { - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(mimetype, stream); - - if (!(doc instanceof XMLDocument)) { - throw new IllegalArgumentException("Advertisements must be XML"); - } - - return newAdvertisement((XMLDocument) doc); - } - - /** - * Reconstructs an instance of {@link Advertisement} from the provided - * Reader. The content type of the reader is declared via the - * mimetype parameter. - * - * @deprecated Please convert your code to construct an {@code XMLDocument} - * using {@code StructuredDocumentFactory} and then call - * {@link AdvertisementFactory#newAdvertisement(XMLElement)}. For example : - *

      -     *   XMLDocument xml = (XMLDocument) StructuredDocumentFactory.newStructuredDocument( MimeMediaType.XMLUTF8, reader );
      -     * 
      - * or frequently: - *

      -     *   XMLDocument xml = (XMLDocument) StructuredDocumentFactory.newStructuredDocument( msgElement );
      -     * 
      - * followed by: - *

      -     *   Advertisement adv = AdvertisementFactory.newAdvertisement(xml);
      -     * 
      - * - * @param mimetype Specifies the mime media type of the stream being read. - * @param source used to read data to construct the advertisement. - * @return The instance of {@link Advertisement} - * @throws IOException error reading message from input stream - * @throws NoSuchElementException if there is no matching advertisement type - * for the type of document read in. - * @throws UnsupportedOperationException if the specified mime type is not - * associated with a text oriented document type. - */ - @Deprecated - public static Advertisement newAdvertisement(MimeMediaType mimetype, Reader source) throws IOException { - StructuredTextDocument doc = (StructuredTextDocument) StructuredDocumentFactory.newStructuredDocument(mimetype, source); - - return newAdvertisement(doc); - } - - /** - * Reconstructs an instance of {@link Advertisement} matching the type - * specified by the {@code root} parameter. - * - * @deprecated Advertisements must be encoded in XML. This is a legacy - * static constructor. You should convert your code to use the - * {@link AdvertisementFactory#newAdvertisement(XMLElement) XMLElement} - * version. - * - * @param root Specifies a portion of a StructuredDocument which will be - * converted into an Advertisement. - * @return The instance of {@link Advertisement}. - * @throws NoSuchElementException if there is no advertisement type - * matching the type of the root node. - */ - @Deprecated - public static Advertisement newAdvertisement(TextElement root) { - if (!(root instanceof XMLElement)) { - throw new IllegalArgumentException("Advertisements must be XML"); - } - - return newAdvertisement((XMLElement) root); - } - - /** - * Reconstructs an instance of {@link Advertisement} matching the type - * specified by the {@code root} parameter. - * - * @param root Specifies a portion of an XMLElement which will be - * converted into an Advertisement. - * @return The instance of {@link Advertisement}. - * @throws NoSuchElementException if there is no advertisement type - * matching the type of the root node. - */ - public static Advertisement newAdvertisement(XMLElement root) { - factory.loadProviders(); - - Instantiator instantiator = null; - - // The base type of the advertisement may be overridden by a type - // declaration. If this is the case, then we try to use that as the - // key rather than the root name. - Attribute type = root.getAttribute("type"); - - if (null != type) { - try { - instantiator = factory.getInstantiator(type.getValue()); - } catch (NoSuchElementException notThere) { - // do nothing, its not fatal - ; - } - } - - // Don't have an instantiator for the type attribute, try the root name - if (null == instantiator) { - instantiator = factory.getInstantiator(root.getName()); - } - - Advertisement a = instantiator.newInstance(root); - - return a; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Attributable.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Attributable.java deleted file mode 100644 index eee48900..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Attributable.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.util.Enumeration; - - -/** - * Interface for name value pairs to be associated with some base object. - * - * @see net.jxta.document.Attribute - * @see net.jxta.document.StructuredDocument - * @see net.jxta.document.Element - */ -public interface Attributable { - - /** - * Adds an attribute with the given name and value. Some implementations - * may support only a single value for each distinct name. Others may - * support multiple values for each name. If the value being provided - * replaces some other value then that value is returned otherwise null - * is returned. - * - * @param name name of the attribute. - * @param value value for the attribute. - * @return String containing previous value for this name if the value - * is being replaced otherwise null. - */ - String addAttribute(String name, String value); - - /** - * Adds an attribute with the given name and value. Some implementations - * may support only a single value for each distinct name. Others may - * support multiple values for each name. If the value being provided - * replaces some other value then that value is returned otherwise null - * is returned. - * - * @param newAttrib new attribute. - * @return String containing previous value for this name if the value - * is being replaced otherwise null. - */ - String addAttribute(Attribute newAttrib); - - /** - * Returns an enumerations of the attributes associated with this object. - * Each element is of type Attribute. - * - * @return Enumeration the attributes associated with this object. - */ - Enumeration getAttributes(); - - /** - * Returns a single attribute which matches the name provided. If no such - * named attribute exists then null is returned. For implementations of - * this interface which support multiple values for each name only the - * first value will be returned. To access all values for a name you must - * use getAttributes. - * - * @param name the attribute name - * @return Attribute the attributes matching the given name. - */ - Attribute getAttribute(String name); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Attribute.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Attribute.java deleted file mode 100644 index 1d746627..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Attribute.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -/** - * A name value pair which is associated with some base object. - * - * @see net.jxta.document.Attributable - * @see net.jxta.document.StructuredDocument - * @see net.jxta.document.Element - * - **/ -public class Attribute { - - /** - * The object which this attribute extends. - **/ - private Attributable owner; - - /** - * Our name - **/ - private String name; - - /** - * Our value - **/ - private String value; - - /** - * Constructor for a new attribute which can be added to an - * {@link Attributable}. - * - * @param name Name for this attribute. - * @param value Value for this attribute. - **/ - public Attribute(String name, String value) { - this(null, name, value); - } - - /** - * Constructor for a new attribute which is associated with an - * @link Attributable} object. - * - * @param owner The Atrributable owner of this attribute or null. - * @param name Name for this attribute. - * @param value Value for this attribute. - **/ - public Attribute(Attributable owner, String name, String value) { - this.owner = owner; - this.name = name; - this.value = value; - } - - /** - * {@inheritDoc} - **/ - @Override - protected Object clone() { - return this; // immutable so we can return self. - } - - /** - * {@inheritDoc} - - * The two attributes are the same if they have - * the same owner, name and value. - * - * @param target Attribute to be checked with - * @return boolean if the attributes are equal otherwise false. - **/ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof Attribute) { - Attribute targAttrib = (Attribute) target; - - boolean result = ((owner.equals(targAttrib.owner)) && name.equals(targAttrib.name) && value.equals(targAttrib.name)); - - return result; - } else { - return false; - } - } - - /** - * {@inheritDoc} - **/ - @Override - public int hashCode() { - int result = name.hashCode() ^ value.hashCode(); - - result ^= (null != owner) ? owner.hashCode() : 0; - return result; - } - - /** - * {@inheritDoc} - **/ - @Override - public String toString() { - return "<" + name + " = \"" + value + "\">"; - } - - /** - * Return name of this attribute - * - * @return String containing the attribute's name. - **/ - public String getName() { - return name; - } - - /** - * Return the {@link Attributable} which is the owner of this attribute. - * - * @return Attributable object which owns this attribute. - **/ - public Attributable getOwner() { - return owner; - } - - /** - * Return value of this attribute - * - * @return String containing the attribute's value. - **/ - public String getValue() { - return value; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/BinaryDocument.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/BinaryDocument.java deleted file mode 100644 index 04b6c919..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/BinaryDocument.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.IOException; - - -/** - * This class is an implementation of the Document interface. It is perhaps the - * simplest implementation of the Document interface possible. - */ -public class BinaryDocument implements Document { - - /** - * Our Mime Media Types - */ - private static final MimeMediaType[] myTypes = { - MimeMediaType.AOS - }; - - /** - * Storage for our bytes. - */ - private final byte[] ourBytes; - - /** - * The MIME type of this document. - */ - private final MimeMediaType ourType; - - /** - * Returns the MIME Media types supported by this this Document per - * {@link IETF RFC 2046 MIME : Media Types}. - *

      - * Jxta does not currently support the 'Multipart' or 'Message' media types. - * - * @return An array of MimeMediaType objects containing the MIME Media Type - * for this Document. - */ - public static MimeMediaType[] getSupportedMimeTypes() { - return (myTypes.clone()); - } - - /** - * Creates new BinaryDocument from a byte array. The data in the array is - * not copied. If you intend to modify the array after creating a document - * then you should pass a copy of the data instead. - * - * @param someBytes Contains a byte array which will serve as our data. - */ - public BinaryDocument(byte[] someBytes) { - this(someBytes, myTypes[0]); - } - - /** - * Creates new BinaryDocument from a byte array. The data in the array is - * not copied. If you intend to modify the array after creating a document - * then you should pass a copy of the data instead. - * - * @param someBytes Contains a byte array which will serve as our data. - * @param type The MIME media type for this document. - */ - public BinaryDocument(byte[] someBytes, MimeMediaType type) { - ourBytes = someBytes; - ourType = type; - } - - /** - * {@inheritDoc} - */ - public MimeMediaType getMimeType() { - return ourType; - } - - /** - * {@inheritDoc} - */ - public String getFileExtension() { - return StructuredDocumentFactory.getFileExtensionForMimeType(ourType); - } - - /** - * {@inheritDoc} - */ - public InputStream getStream() throws IOException { - return (new ByteArrayInputStream(ourBytes)); - } - - /** - * {@inheritDoc} - */ - public void sendToStream(OutputStream stream) throws IOException { - stream.write(ourBytes); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Document.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Document.java deleted file mode 100644 index 016d8f1b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Document.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.InputStream; -import java.io.OutputStream; - -import java.io.IOException; - - -/** - * A simple typed container for data. A {@code Document} is presented as a - * byte stream with an associated type. The data type is specified using a - * MIME Media Type (as defined by - * {@link IETF RFC 2046 MIME : Media Types}). - * - * @see net.jxta.document.MimeMediaType - * @see net.jxta.document.StructuredDocument - * @see net.jxta.document.StructuredDocumentFactory - */ -public interface Document extends DocumentStreamIO { - - /** - * Returns the MIME Media type of this {@code Document} per - * {@link IETF RFC 2046 MIME : Media Types}. - * - *

      JXTA does not currently support the 'Multipart' or - * 'Message' media types. - * - * @return The MIME Media Type for this {@code Document}. - */ - MimeMediaType getMimeType(); - - /** - * Returns the file extension type used by this {@code Document}. This - * value is usually chosen based upon the MIME Media Type. - * - * @return An appropriate file extension for this {@code Document}. - */ - String getFileExtension(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/DocumentByteArrayIO.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/DocumentByteArrayIO.java deleted file mode 100644 index dba00eee..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/DocumentByteArrayIO.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.nio.ByteBuffer; - - -/** - * Provides {@code byte} array based interfaces for manipulating - * {@code Document} contents. - * - * @see net.jxta.document.Document - */ -public interface DocumentByteArrayIO { - - /** - * Returns the {@code Document} as a sequence of bytes. - */ - byte[] getBytes(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/DocumentByteBufferIO.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/DocumentByteBufferIO.java deleted file mode 100644 index 2131e16d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/DocumentByteBufferIO.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.nio.ByteBuffer; - - -/** - * Provides {@code ByteBuffer} based interfaces for manipulating - * {@code Document} contents. - * - * @see java.nio.ByteBuffer - * @see net.jxta.document.Document - */ -public interface DocumentByteBufferIO { - - /** - * Returns the {@code Document} as a sequence of ByteBuffers - */ - ByteBuffer[] getByteBuffers(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/DocumentStreamIO.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/DocumentStreamIO.java deleted file mode 100644 index c3e9734f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/DocumentStreamIO.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.InputStream; -import java.io.OutputStream; - -import java.io.IOException; - - -/** - * Provides stream based interfaces for manipulating {@code Document} contents. - * - * @see net.jxta.document.Document - */ -public interface DocumentStreamIO { - - /** - * Returns the stream of bytes which represents the content of this - * {@code Document}. - * - * @return An {@link java.io.InputStream} containing the bytes - * of this {@code Document}. - * @throws IOException For errors while writing the {@code Document}. - */ - InputStream getStream() throws IOException; - - /** - * Send the contents of this {@code Document} to the specified stream. - * - * @param stream The OutputStream to which the {@code Document} will - * be written. - * @throws IOException For errors while writing the {@code Document}. - */ - void sendToStream(OutputStream stream) throws IOException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Element.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Element.java deleted file mode 100644 index b73bd8d7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/Element.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.document; - - -import java.util.Enumeration; - - -/** - * An element represents a portion of a {@link StructuredDocument}. An element - * is identifiable by a key and may also optionally have a - * value. Each Element also maintains a collection of references - * to other elements, its children. Elements can be - * composed into arbitrary hierarchical structures forming complex data - * structures. - * - *

      Element instances are always associated with a - * {@link StructuredDocument}. A {@link StructuredDocument} is a specialized - * form of Element with additional features that make it appropriate for - * acting as the root of a hierarchy of elements. - * - * @see net.jxta.document.Document - * @see net.jxta.document.StructuredDocument - * @see net.jxta.document.StructuredDocumentFactory - * @see net.jxta.document.StructuredTextDocument - * @see net.jxta.document.TextElement - */ -public interface Element> { - - /** - * Get the key associated with this Element. - * - * @return The key of this Element. - */ - Object getKey(); - - /** - * Get the value (if any) associated with this Element. - * - * @return The value of this element, if any, otherwise null. - */ - Object getValue(); - - /** - * Get the root document element of the hierarchy this element belongs to. - * - * @return The root document element of this element's hierarchy. - */ - StructuredDocument getRoot(); - - /** - * Get the parent element of this element. If this Element has not been - * inserted into the Document then null is returned. If this - * element is the root element of the Document then it returns itself. ie., - * this == this.getParent(). - * - * @return The parent of this element. If the element has no parent - * then null will be returned. If the element is the root Element of the - * hierarchy then it will return itself. - */ - E getParent(); - - /** - * Add a child element to this element. The child element must be from the - * document as the element it is to be added to. Elements are created using - * either {@link StructuredDocument#createElement(Object)} or - * {@link StructuredDocument#createElement(Object, Object)}. - * - * @param element The element to be added as a child. - */ - void appendChild(E element); - - /** - * Returns an enumeration of the immediate children of this element. - * - * @return Enumeration containing all of the children of this element. - */ - Enumeration getChildren(); - - /** - * Returns an enumeration of the immediate children of this element who - * match the specified key. - * - * @param key The key which will be matched against. - * @return Enumeration containing all of the matching children of this - * element. - */ - Enumeration getChildren(Object key); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/ExtendableAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/ExtendableAdvertisement.java deleted file mode 100644 index 70e71ab7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/ExtendableAdvertisement.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -/** - * Extendable advertisements provide features for allowing inheritance of - * advertisement types. The core and standard JXTA advertisements all allow - * extension by extending this class. - * - * @see net.jxta.document.Advertisement - * @see net.jxta.document.AdvertisementFactory - * @see net.jxta.document.Document - * @see net.jxta.document.MimeMediaType - */ -public abstract class ExtendableAdvertisement extends Advertisement { - - /** - * If {@code true} then the advertisement will be pretty print formatted - * when it is output as XML. Currently this must be specified at - * construction time as it is normally a preference per advertisement type. - */ - private transient boolean formatted; - - /** - * Default constructor. The advertisement will *not* be pretty-printed when - * it is output as XML. - */ - protected ExtendableAdvertisement() { - this(false); - } - - /** - * @param formatted If {@code true} then the advertisement will be pretty - * print formatted when it is output as XML. - */ - protected ExtendableAdvertisement(boolean formatted) { - this.formatted = formatted; - } - - /** - * Returns the base type of this advertisement hierarchy. Typically, only - * the most basic advertisement of a type will implement this method and - * declare it as final. - * - * @return String the base type of advertisements in this hierarchy. - */ - public abstract String getBaseAdvType(); - - /** - * Process an individual element from the document during parse. Normally, - * implementations will allow the base advertisements a chance to handle - * the element before attempting to handle the element themselves. ie. - *

      - *

      
      -     *  protected boolean handleElement(Element elem) {
      -     *
      -     *      if (super.handleElement()) {
      -     *           // it's been handled.
      -     *           return true;
      -     *           }
      -     *      ... handle elements here ...
      -     *
      -     *      // we don't know how to handle the element
      -     *      return false;
      -     *      }
      -     *  
      - * - * @param elem The element to be processed. - * @return {@code true} if the element was recognized, otherwise false. - */ - protected boolean handleElement(Element elem) { - // we don't handle any elements. - return false; - } - - /** - * Process an individual attribute from the document root node. Normally, - * implementations will allow the base advertisements a chance to handle - * the attribute before attempting to handle the element themselves. ie. - *

      - *

      
      -     *  protected boolean handleAttribute( Attribute elem ) {
      -     * 

      - * if (super.handleAttribute()) { - * // it's been handled. - * return true; - * } - * - * ... handle attributes here ... - * - * // we don't know how to handle the attribute - * return false; - * } - *

      - * - * @param attrib The attribute to be processed. - * @return {@code true} if the attribute was recognized, otherwise false. - */ - protected boolean handleAttribute(Attribute attrib) { - - // "handle" the attributes that we choose to ignore. - if ("xmlns:jxta".equals(attrib.getName())) { - return true; - } else if ("xml:space".equals(attrib.getName())) { - return true; - } else if ("type".equals(attrib.getName())) { - return true; - } - - return false; - } - - /** - * {@inheritDoc} - *

      - * We don't have any content to add, just build the document instance and - * return it to implementations that actually do something with it. - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - Document adv = StructuredDocumentFactory.newStructuredDocument(encodeAs, getBaseAdvType()); - - if (!(adv instanceof Attributable)) { - throw new IllegalArgumentException("Advertisements require document type with attribute support."); - } - - if (adv instanceof XMLDocument) { - XMLDocument xmlAdv = (XMLDocument) adv; - - xmlAdv.addAttribute("xmlns:jxta", "http://jxta.org"); - if (!formatted) { - xmlAdv.addAttribute("xml:space", "preserve"); - } - } - - if (!getBaseAdvType().equals(getAdvType())) { - ((Attributable) adv).addAttribute("type", getAdvType()); - } - - return adv; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/FileDocument.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/FileDocument.java deleted file mode 100644 index bcee2c9f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/FileDocument.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.OutputStream; - -import java.io.IOException; - - -/** - * This class presents a Document interface for a specific file on disk. - */ -public class FileDocument implements Document { - - private final static int BUFFER_SIZE = 4096; - - /** - * File which backs this document. - */ - private final File file; - - /** - * MIME media type of this document. - **/ - private final MimeMediaType type; - - /** - * Create a new File Document. - **/ - public FileDocument(File file) { - this(file, StructuredDocumentFactory.getMimeTypeForFileExtension(getFileExtension(file))); - } - - /** - * Create a new File Document. - */ - public FileDocument(File file, MimeMediaType type) { - if (file.isDirectory()) { - throw(new IllegalArgumentException("File cannot be a directory")); - } - - if (!file.exists()) { - throw(new IllegalArgumentException("File must exist")); - } - - this.file = file; - this.type = type.intern(); - } - - /** - * {@inheritDoc} - * - *

      Returns everything after the last '.' in the filename, or the - * empty string if the file name does not contain a '.'. - **/ - public String getFileExtension() { - return getFileExtension(file); - } - - /** - *

      Returns everything after the last '.' in the filename, or the - * empty string if the file name does not contain a '.'. - **/ - private static String getFileExtension(File file) { - - String fileName = file.getName(); - int idx = fileName.lastIndexOf('.'); - - if (idx < 0 || idx == fileName.length()) { - return ""; - } else { - return fileName.substring(idx + 1); - } - } - - /** - * {@inheritDoc} - **/ - public MimeMediaType getMimeType() { - return type; - } - - /** - * {@inheritDoc} - **/ - public InputStream getStream() throws IOException { - return new FileInputStream(file); - } - - /** - * {@inheritDoc} - **/ - public void sendToStream(OutputStream sink) throws IOException { - InputStream source = getStream(); - int c; - byte[] buf = new byte[BUFFER_SIZE]; - - do { - c = source.read(buf); - - if (-1 == c) { - break; - } - - sink.write(buf, 0, c); - } while (true); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/MimeMediaType.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/MimeMediaType.java deleted file mode 100644 index c044aacb..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/MimeMediaType.java +++ /dev/null @@ -1,835 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.*; -import java.lang.ref.Reference; -import java.lang.ref.WeakReference; -import java.util.*; - - -/** - * MIME Media Types are used to describe the format of data streams. MIME - * Media Types are defined by - * {@link IETF RFC 2046 MIME : Media Types}. - * This class manages parsing of Mime Media Types from strings and piecemeal - * construction of Mime Media Type descriptors. - *

      - *

      Note : This implementation does not include support for the character - * encoding techniques described by : - * {@link IETF RFC 2046 MIME : Media Types}. - * - * @see net.jxta.document.Document - * @see net.jxta.document.StructuredDocument - * @see net.jxta.document.StructuredDocumentFactory - * @see net.jxta.document.StructuredTextDocument - */ -public class MimeMediaType implements Serializable { - - /** - * Magic value for this format of serialization version. - */ - private final static long serialVersionUID = 7546247036878523161L; - - private final static String CTL = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007" - + "\u0008\u0009\n\u000b\u000c\r\u000e\u000f" + "\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017" - + "\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f" + "\u007f"; - - private final static String space = "\u0020"; - private final static String LWSP_char = space + "\u0009"; - private final static String param_sep = LWSP_char + ";"; - private final static String tspecials = "()<>@,;:\\\"/[]?="; - private final static String terminator = CTL + space + tspecials; - - /** - * A canonical map of Mime Media Types. - */ - private static final Map> interned = new WeakHashMap>(); - - /** - * Common Mime Media Type for arbitrary unparsed binary data. - */ - public static final MimeMediaType AOS = new MimeMediaType("application", "octet-stream").intern(); - - /** - * Common Mime Media Type for text encoded using the default character - * encoding for this JVM. The default character encoding is specified by - * the JDK System property "file.encoding". - *

      - *

      The default encoding varies with host platform and locale. This - * media type must not be used for any documents which - * will be exchanged with other peers (as they may be using different - * default character encodings). - */ - public static final MimeMediaType TEXT_DEFAULTENCODING = new MimeMediaType("text", "plain").intern(); - - /** - * Common Mime Media Type for plain text encoded as UTF-8 characters. This - * type is used by JXTA for all strings. - */ - public static final MimeMediaType TEXTUTF8 = new MimeMediaType("text", "plain", "charset=\"UTF-8\"").intern(); - - /** - * Common Mime Media Type for XML encoded using the default character - * encoding for this JVM. The default character encoding is specified by - * the JDK System property "file.encoding". - *

      - *

      The default encoding varies with host platform and locale. This - * media type must not be used for any documents which - * will be exchanged with other peers (as they may be using different - * default character encodings). - */ - public static final MimeMediaType XML_DEFAULTENCODING = new MimeMediaType("text", "xml").intern(); - - /** - * Common Mime Media Type for XML encoded using the default character - * encoding for this JVM. The default character encoding is specified by - * the JDK System property "file.encoding". - *

      - *

      The default encoding varies with host platform and locale. This - * media type must not be used for any documents which - * will be exchanged with other peers (as they may be using different - * default character encodings). - */ - public static final MimeMediaType APPLICATION_XML_DEFAULTENCODING = new MimeMediaType("application", "xml").intern(); - - /** - * Common Mime Media Type for XML encoded as UTF-8 characters. This type is - * used by JXTA for all protocol messages and metadata. - */ - public static final MimeMediaType XMLUTF8 = new MimeMediaType("text", "xml", "charset=\"UTF-8\"").intern(); - - /** - * The primary media type - */ - private transient String type = null; - - /** - * The specific media sub-type - */ - private transient String subtype = null; - - /** - * The parameters for this media type - */ - private transient List parameters = new ArrayList(); - - /** - * The hashcode value for this mime media type. - */ - private transient int cachedHashCode = 0; - - /** - * manages a media type parameter. - */ - private static class parameter implements Comparable { - - /** - * Attribute name. - */ - final String attribute; - - /** - * Value for the attribute. Includes quoting characters if they are - * needed for outputting this value. - */ - final String value; - - parameter(String attr, String val) { - attribute = attr; - value = val; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (!(obj instanceof parameter)) { - return false; - } - - parameter asParameter = (parameter) obj; - - return attribute.equalsIgnoreCase(asParameter.attribute) && asParameter.value.equals(value); - - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return attribute.toLowerCase().hashCode() * 6037 + value.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return attribute + "=" + outputForm(value); - } - - /** - * {@inheritDoc} - */ - public int compareTo(parameter asParameter) { - if (this == asParameter) { - return 0; - } - - int result = attribute.compareToIgnoreCase(asParameter.attribute); - - if (0 != result) { - return result; - } - - return value.compareTo(asParameter.value); - } - - private static String outputForm(String val) { - StringBuilder result = new StringBuilder(); - - if (-1 == findNextSeperator(val)) { - result.append(val); - } else { - // needs quoting - result.append('\"'); - for (int eachChar = 0; eachChar < val.length(); eachChar++) { - char aChar = val.charAt(eachChar); - - if (('\\' == aChar) || ('\"' == aChar) || ('\r' == aChar)) { - // needs escaping. - result.append('\\'); - } - result.append(aChar); - } - result.append('\"'); - } - return result.toString(); - } - } - - /** - * Creates a new MimeMediaType - * - * @param mimetype string representing a mime-type - */ - public MimeMediaType(String mimetype) { - - String cleaned = mimetype.trim(); - - if (0 == cleaned.length()) { - throw new IllegalArgumentException("input cannot be empty"); - } - - // determine the type - int typeSepAt = findNextSeperator(cleaned); - - if ((-1 == typeSepAt) || (0 == typeSepAt) || ('/' != cleaned.charAt(typeSepAt))) { - throw new IllegalArgumentException("expected seperator or seperator in unexpected location"); - } - - setType(cleaned.substring(0, typeSepAt)); - - // determine the sub-type - int subtypeSepAt = findNextSeperator(cleaned, typeSepAt + 1); - - String itsParams = ""; - - if (-1 == subtypeSepAt) { - setSubtype(cleaned.substring(typeSepAt + 1)); - } else { - setSubtype(cleaned.substring(typeSepAt + 1, subtypeSepAt)); - itsParams = cleaned.substring(subtypeSepAt); - // include the seperator, its significant - } - - parseParams(itsParams, false); - } - - /** - * Creates a new type/subtype MimeMediaType - * - * @param type string representing a mime type - * @param subtype string representing a mime subtype - */ - public MimeMediaType(String type, String subtype) { - this(type, subtype, null); - } - - /** - * Creates a new type/subtype MimeMediaType - * - * @param type string representing a mime type - * @param subtype string representing a mime subtype - * @param parameters parameters to the mime-type constructor - */ - public MimeMediaType(String type, String subtype, String parameters) { - setType(type); - setSubtype(subtype); - if (null != parameters) { - parseParams(parameters, false); - } - } - - /** - * Creates a new type/subtype MimeMediaType with the specified parameters. - * The parameters are copied from the source mime type and additional params - * are added. If replace is true, then the provided params will overwrite - * the params from the source mime type. - * - * @param type the source mime type - * @param params parameters to the mime-type constructor - * @param replace parameters if true then provided params should replace - * existing params else they are accumulated. - */ - public MimeMediaType(MimeMediaType type, String params, boolean replace) { - setType(type.getType()); - setSubtype(type.getSubtype()); - parameters.addAll(type.parameters); - - parseParams(params, replace); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (!(obj instanceof MimeMediaType)) { - return false; - } - - MimeMediaType asMMT = (MimeMediaType) obj; - - if (!type.equalsIgnoreCase(asMMT.type)) { - return false; - } - - if (!subtype.equalsIgnoreCase(asMMT.subtype)) { - return false; - } - - List myParams = new ArrayList(parameters); - List itsParams = new ArrayList(asMMT.parameters); - - Collections.sort(myParams); - Collections.sort(itsParams); - - return myParams.equals(itsParams); - } - - /** - * Similar to {@link #equals(Object)}, but ignores any parameters. Compares - * only the type and sub-type. - * - * @param obj the object to compare - * @return true if equal - */ - public boolean equalsIngoringParams(Object obj) { - if (this == obj) { - return true; - } - - if (!(obj instanceof MimeMediaType)) { - return false; - } - - MimeMediaType likeMe = (MimeMediaType) obj; - - boolean retValue = getType().equalsIgnoreCase(likeMe.getType()) && getSubtype().equalsIgnoreCase(likeMe.getSubtype()); - - return retValue; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - if (0 == cachedHashCode) { - List myParams = new ArrayList(parameters); - - Collections.sort(myParams); - - int calcedHash = type.hashCode() * 2467 + subtype.hashCode() * 3943 + myParams.hashCode(); - - cachedHashCode = (0 != calcedHash) ? calcedHash : 1; - } - - return cachedHashCode; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringBuilder retValue = new StringBuilder(getMimeMediaType()); - - for (parameter parameter : parameters) { - retValue.append(';'); - parameter aParam = parameter; - - retValue.append(aParam.toString()); - } - return retValue.toString(); - } - - /** - * Returns the "base" MIME media type of this type. ie. with no parameters. - * - * @return The "base" MIME media type of this MimeMediaType. - */ - public MimeMediaType getBaseMimeMediaType() { - return new MimeMediaType(type, subtype).intern(); - } - - /** - * Returns the "base" MIME media type of this type. ie. with no parameters. - * - * @return The "base" MIME media type of this type. ie. with no parameters. - */ - public String getMimeMediaType() { - StringBuilder retValue = new StringBuilder(type.length() + 1 + subtype.length()); - - retValue.append(type); - retValue.append('/'); - retValue.append(subtype); - - return retValue.toString(); - } - - /** - * Get type of the mime-type - * - * @return type of the mime-type - */ - public String getType() { - return type; - } - - /** - * Check if the mime-type is for provisional. See Section 2.1 of - * {@link IETF RFC 2048 MIME : Registration Procedures} - * - * @return boolean true if it is a provisional type - */ - public boolean isExperimentalType() { - if ((null == type) || (type.length() < 2)) { - return false; - } - - if (type.startsWith("x-") || type.startsWith("x.")) { - return true; - } - - return null != subtype && subtype.length() >= 2 && (subtype.startsWith("x-") || subtype.startsWith("x.")); - - } - - /** - * Set the type of MimeMediaType - * - * @param type type value - */ - private void setType(String type) { - if (null == type) { - throw new IllegalArgumentException("type cannot be null"); - } - - String cleaned = type.trim().toLowerCase(Locale.US); - - if (0 == cleaned.length()) { - throw new IllegalArgumentException("type cannot be null"); - } - - if (-1 != findNextSeperator(cleaned)) { - throw new IllegalArgumentException("type cannot contain a seperator"); - } - - this.type = cleaned; - } - - /** - * Get the Subtype of the mime-type - * - * @return subtype of the mime-type - */ - public String getSubtype() { - return subtype; - } - - /** - * Check if the mime-type is for debugging. This method will be - * removed - * - * @return boolean true if it is a debugging type - */ - public boolean isExperimentalSubtype() { - if ((null == subtype) || (subtype.length() < 2)) { - return false; - } - - return (('x' == subtype.charAt(0)) && ('-' == subtype.charAt(1))); - } - - /** - * Set the subtype of MimeMediaType - * - * @param subtype subtype value - */ - private void setSubtype(String subtype) { - if (null == subtype) { - throw new IllegalArgumentException("subtype cannot be null"); - } - - String cleaned = subtype.trim().toLowerCase(Locale.US); - - if (0 == cleaned.length()) { - throw new IllegalArgumentException("subtype cannot be null"); - } - - if (-1 != findNextSeperator(cleaned)) { - throw new IllegalArgumentException("subtype cannot contain a seperator"); - } - - this.subtype = cleaned; - } - - /** - * Get the value of the first occurance of the specified parameter from the - * parameter list. - * - * @param param the parameter to retrieve. - * @return the value of the specifid parameter or null if the parameter was - * not found. - */ - public String getParameter(String param) { - for (parameter parameter : parameters) { - parameter aParam = parameter; - - if (aParam.attribute.equalsIgnoreCase(param)) { - return aParam.value; - } - } - return null; - } - - /** - * Parses the parametes portion of a MIME Media Type specification. - * - * @param itsParams parse a string for mime parameters. - * @param replace parameters if true then provided params should replace - * existing params else they are accumulated. - */ - private void parseParams(String itsParams, boolean replace) { - int currentCharIdx = 0; - String currentAttribute = null; - boolean inSeperator = true; - boolean inComment = false; - boolean inAttribute = false; - StringBuffer currentValue = null; - boolean inValue = false; - boolean inQuoted = false; - boolean nextEscaped = false; - - while (currentCharIdx < itsParams.length()) { - char currentChar = itsParams.charAt(currentCharIdx); - - if (inSeperator) { - if ('(' == currentChar) { - inSeperator = false; - inComment = true; - } else if (-1 == param_sep.indexOf(currentChar)) { - inSeperator = false; - inAttribute = true; - currentCharIdx--; // unget - } - } else if (inComment) { - if (nextEscaped) { - nextEscaped = false; - } else { - if ('\\' == currentChar) { - nextEscaped = true; - } else if (')' == currentChar) { - inComment = false; - inSeperator = true; - } else if ('\r' == currentChar) { - throw new IllegalArgumentException("malformed mime parameter at idx = " + currentCharIdx); - } - } - } else if (inAttribute) { - int endAttr = findNextSeperator(itsParams, currentCharIdx); - - if ((-1 == endAttr) || ('=' != itsParams.charAt(endAttr)) || (0 == (endAttr - currentCharIdx))) { - throw new IllegalArgumentException("malformed mime parameter at idx = " + currentCharIdx); - } - - currentAttribute = itsParams.substring(currentCharIdx, endAttr).toLowerCase(Locale.US); - - currentCharIdx = endAttr; // skip the equals. - inAttribute = false; - inValue = true; - inQuoted = false; - nextEscaped = false; - currentValue = new StringBuffer(); - } else if (inValue) { - if (inQuoted) { - if (nextEscaped) { - currentValue.append(currentChar); - nextEscaped = false; - } else { - if ('\\' == currentChar) { - nextEscaped = true; - } else if ('"' == currentChar) { - inQuoted = false; - } else if ('\r' == currentChar) { - throw new IllegalArgumentException("malformed mime parameter at idx = " + currentCharIdx); - } else { - currentValue.append(currentChar); - } - } - } else if (-1 == terminator.indexOf(currentChar)) { - currentValue.append(currentChar); - } else { - if ('"' == currentChar) { - inQuoted = true; - } else { - parameter newparam = new parameter(currentAttribute, currentValue.toString()); - - if (replace) { - while (parameters.remove(newparam)) {} - } - - parameters.add(newparam); - - inValue = false; - inSeperator = true; - currentCharIdx--; // unget - } - } - } else { - throw new IllegalArgumentException("malformed mime parameter at idx = " + currentCharIdx); - } - - currentCharIdx++; - } - - // finish off the last value. - if (inValue) { - if (nextEscaped || inQuoted) { - throw new IllegalArgumentException("malformed mime parameter at idx = " + currentCharIdx); - } - - parameter newparam = new parameter(currentAttribute, currentValue.toString()); - - if (replace) { - while (parameters.remove(newparam)) {} - } - - parameters.add(newparam); - - inValue = false; - inSeperator = true; - } - - if (!inSeperator) { - throw new IllegalArgumentException("malformed mime parameter at idx = " + currentCharIdx); - } - } - - /** - * Find next separator position in mime-type - * - * @param source source location - * @return int separator location - */ - private static int findNextSeperator(String source) { - return findNextSeperator(source, 0); - } - - /** - * Find next separator position in mime-type - * - * @param source source location - * @param from from location - * @return int separator location - */ - private static int findNextSeperator(String source, int from) { - - int seperator = -1; - - // find a seperator - for (int eachChar = from; eachChar < source.length(); eachChar++) { - if (-1 != terminator.indexOf(source.charAt(eachChar))) { - seperator = eachChar; - break; - } - } - - return seperator; - } - - /** - * Returns a MimeMediaType with a value represented by the specified String. - *

      - * This method may produce better results than using the constructor - * the same parameter set in that: - *

      - * - * new MimeMediaType( string ) != new MimeMediaType( string ) - * - *

      - * while for common types: - *

      - * - * MimeMediaType.valueOf( string ) == MimeMediaType.valueOf( string ) - * - */ - public static MimeMediaType valueOf(String mimetype) { - return new MimeMediaType(mimetype).intern(); - } - - /** - * Read this Object in for Java Serialization - * - * @param s The stream from which the Object will be read. - * @throws IOException for errors reading from the input stream. - * @throws ClassNotFoundException if the serialized representation contains - * references to classes which cannot be found. - */ - private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { - s.defaultReadObject(); - - MimeMediaType readType = MimeMediaType.valueOf(s.readUTF()); - - type = readType.type; - subtype = readType.subtype; - parameters = readType.parameters; - } - - /** - * Return the interned form of the ID. - */ - private Object readResolve() throws ObjectStreamException { - return intern(); - } - - /** - * Write this Object out for Java Serialization - * - * @param s The stream to which the Object will be written. - * @throws IOException for errors writing to the output stream. - */ - private void writeObject(ObjectOutputStream s) throws IOException { - s.defaultWriteObject(); - - s.writeUTF(toString()); - } - - /** - * Returns a canonical representation for the MimeMediaType object. - *

      - *

      A pool of MimeMediaType, is maintained privately by the class. - *

      - *

      When the intern method is invoked, if the pool already contains a - * MimeMediaType equal to this MimeMediaType object as determined by the - * equals(Object) method, then the MimeMediaType from the pool is returned. - * Otherwise, this MimeMediaType object is added to the pool and a reference - * to this MimeMediaType object is returned. - *

      - *

      It follows that for any two MimeMediaType s and t, - * s.intern() == t.intern() is true if and only if s.equals(t) - * is true. - * - * @return a MimeMediaType that has the same value as this type, but is - * guaranteed to be from a pool of unique types. - */ - public MimeMediaType intern() { - synchronized (MimeMediaType.class) { - Reference common = interned.get(this); - - MimeMediaType result; - - if (null == common) { - common = new WeakReference(this); - interned.put(this, common); - result = this; - } else { - result = common.get(); - if (null == result) { - interned.put(this, new WeakReference(this)); - result = this; - } - } - - return result; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/StructuredDocument.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/StructuredDocument.java deleted file mode 100644 index 73e19ddd..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/StructuredDocument.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -/** - * An extension of {@link Document} which allows the content of a document to be - * specified by a hierarchy of elements. This allows the content of many - * document types to be manipulated in an abstract way without regard to the - * physical representation of the documents. - * - *

      StructuredDocuments are one of the elementary components that is - * manipulated by the JXTA core. StructuredDocuments are used to represent most - * core objects such as peer, peergroup or pipe advertisements. - * - * @see net.jxta.document.Document - * @see net.jxta.document.StructuredTextDocument - * @see net.jxta.document.StructuredDocumentFactory - **/ -public interface StructuredDocument> extends Document, Element { - - /** - * Create a new element without value. - * - * @param key The key of the element to be created. - * @return The new element. - **/ - E createElement(Object key); - - /** - * Create a new element with value. - * - * @param key The name of the element to be created. - * @param value The value of the element to be created or - * null if no value is desired. - * @return The new element. - **/ - E createElement(Object key, Object value); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/StructuredDocumentFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/StructuredDocumentFactory.java deleted file mode 100644 index 74154edd..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/StructuredDocumentFactory.java +++ /dev/null @@ -1,582 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.InputStream; -import java.io.Reader; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Map; - -import java.io.IOException; -import java.util.MissingResourceException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.util.ClassFactory; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.TextMessageElement; - - -/** - * A factory for constructing instances of {@link StructuredDocument}. - * Behind the scenes, it also provides for the registration of the mime-types - * and constructors needed to accomplish the construction. All supported - * mime-types will need to register their implementation in this factory. - * - * @see net.jxta.document.Document - * @see net.jxta.document.StructuredTextDocument - * @see net.jxta.document.StructuredDocument - * @see net.jxta.document.MimeMediaType - */ -public final class StructuredDocumentFactory extends ClassFactory { - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(StructuredDocumentFactory.class.getName()); - - /** - * Interface for instantiators of StructuredDocuments - */ - public interface Instantiator { - - /** - * For mapping between extensions and MIME types. - */ - class ExtensionMapping extends Object { - - /** - * The extension - */ - private final String extension; - - /** - * MIME type it maps to - */ - private final MimeMediaType mimetype; - - /** - * default constructor - */ - public ExtensionMapping(String extension, MimeMediaType mimetype) { - this.extension = extension; - this.mimetype = (null != mimetype) ? mimetype.intern() : null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof ExtensionMapping) { - ExtensionMapping likeMe = (ExtensionMapping) target; - - if (!extension.equals(likeMe.extension)) { - return false; - } - - if ((null == mimetype) && (null == likeMe.mimetype)) { - return true; - } - - if ((null == mimetype) || (null == likeMe.mimetype)) { - return false; - } - - return mimetype.equals(likeMe.mimetype); - } else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int hash = extension.hashCode(); - - if (null != mimetype) { - hash ^= mimetype.hashCode(); - } - - return hash; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return extension + " -> " + ((null != mimetype) ? mimetype.toString() : ""); - } - - /** - * Returns the extension which is part of this mapping. - * - * @return the extension which is part of this mapping. - */ - public String getExtension() { - return extension; - } - - /** - * Returns the MIME Media Type which is part of this mapping. - * - * @return the MIME Media Type which is part of this mapping. - */ - public MimeMediaType getMimeMediaType() { - return mimetype; - } - } - - /** - * Returns the MIME Media types supported by this this Document per - * {@link IETF RFC 2046 MIME : Media Types}. - * - *

      JXTA does not currently support the 'Multipart' or 'Message' - * media types. - * - * @return An array of MimeMediaType objects containing the MIME Media Type - * for this Document. - */ - MimeMediaType[] getSupportedMimeTypes(); - - /** - * Returns the mapping of file extension and mime-types for this type - * of document. The default extension is mapped to the 'null' mime-type - * and should only be used if no other mapping matches. - * - * @return An array of objects containing file extensions - */ - ExtensionMapping[] getSupportedFileExtensions(); - - /** - * Create a new structured document of the type specified by doctype. - * - * @param mimeType The MIME type to be associated with this instance. - * the base type must be one of the types returned by - * getSupportedMimeTypes. Some implementations may accept - * parameters in the params section of the MIME type. - * @param doctype Type for the base node of the document. - * @return StructuredDocument instance. - */ - StructuredDocument newInstance(MimeMediaType mimeType, String doctype); - - /** - * Create a new structured document of the type specified by doctype. - * - * @param mimeType The MIME type to be associated with this instance. - * The base type must be one of the types returned by - * getSupportedMimeTypes. Some implementations may accept - * parameters in the params section of the MIME type. - * @param doctype Type for the base node of the document. - * @param value Value for the base node of the document. - * @return {@link StructuredDocument} instance. - */ - StructuredDocument newInstance(MimeMediaType mimeType, String doctype, String value); - - /** - * Create a structured document from a stream containing an appropriately serialized - * instance of the same document. - * - * @param mimeType The MIME type to be associated with this instance. - * The base type must be one of the types returned by - * getSupportedMimeTypes. Some implementations may accept - * parameters in the params section of the MIME type. - * @param source The {@code Inputstream} from which to read the - * document. - * @return {@link StructuredDocument} instance. - * @throws IOException Thrown for problems reading from the source. - */ - StructuredDocument newInstance(MimeMediaType mimeType, InputStream source) throws IOException; - } - - - /** - * Interface for instantiators of StructuredTextDocuments - */ - public interface TextInstantiator extends Instantiator { - - /** - * Create a structured document from a Reader containing an appropriately serialized - * instance of the same document. - * - * @param mimeType The MIME type to be associated with this instance. - * The base type must be one of the types returned by - * getSupportedMimeTypes. Some implementations may accept - * parameters in the params section of the MIME type. - * @param source {@code Reader} from which to read the instance. - * @return {@link StructuredDocument} instance. - * @throws IOException Thrown for problems reading from the source. - */ - StructuredDocument newInstance(MimeMediaType mimeType, Reader source) throws IOException; - } - - /** - * This class is a singleton. This is the instance that backs the - * static methods. - */ - private static final StructuredDocumentFactory factory = new StructuredDocumentFactory(); - - /** - * This is the map of mime-types and instantiators used by - * newStructuredDocument. - */ - private final Map encodings = new HashMap(); - - /** - * This is the map of extensions to mime-types used by - * {@link #getMimeTypeForFileExtension(String) } - */ - private final Map extToMime = new HashMap(); - - /** - * This is the map of mime-types to extensions used by - * {@link #getFileExtensionForMimeType(MimeMediaType mimetype) } - */ - private final Map mimeToExt = new HashMap(); - - /** - * If true then the pre-defined set of StructuredDocument sub-classes has - * been registered from the property containing them. - */ - private boolean loadedProperty = false; - - /** - * Private constructor. This class is not meant to be instantiated except - * by itself. - * - */ - private StructuredDocumentFactory() {} - - /** - * Registers the pre-defined set of StructuredDocument sub-classes so that - * this factory can construct them. - * - * @return true if at least one of the StructuredDocument sub-classes could - * be registered otherwise false. - */ - private synchronized boolean loadProviders() { - if (factory.loadedProperty) { - return true; - } - - factory.loadedProperty = registerProviders(StructuredDocument.class.getName()); - - return factory.loadedProperty; - } - - /** - * {@inheritDoc} - */ - @Override - protected Map getAssocTable() { - return encodings; - } - - /** - * {@inheritDoc} - */ - @Override - protected Class getClassForKey() { - return MimeMediaType.class; - } - - /** - * {@inheritDoc} - */ - @Override - protected Class getClassOfInstantiators() { - // our key is the doctype names. - return Instantiator.class; - } - - /** - * {@inheritDoc} - * - *

      We override the standard implementation to get the MIME type from - * the class and use that as the key to register the class with the factory. - * - * @param className The class name which will be registered. - * @return boolean true if the class was registered otherwise false. - */ - @Override - protected boolean registerAssoc(String className) { - boolean registeredSomething = false; - - LOG.finer("Registering : " + className); - - try { - Class docClass = Class.forName(className); - - Instantiator instantiator = (Instantiator) docClass.getField("INSTANTIATOR").get(null); - - MimeMediaType[] mimeTypes = instantiator.getSupportedMimeTypes(); - - for (int eachType = 0; eachType < mimeTypes.length; eachType++) { - LOG.finer(" Registering Type : " + mimeTypes[eachType].getMimeMediaType()); - registeredSomething |= registerInstantiator(mimeTypes[eachType], instantiator); - } - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to register \'" + className + "\'", all); - } - } - - return registeredSomething; - } - - /** - * Returns the preferred extension for a given mime-type. If there is no - * mapping or no preferred extension for this MIME type then null is - * returned. - * - * @param mimetype the MimeMediaType we wish to know the file extension for. - * @return String containing the extension or null for mime-types with no - * known association. - */ - public static String getFileExtensionForMimeType(MimeMediaType mimetype) { - factory.loadProviders(); - - return factory.mimeToExt.get(mimetype.getBaseMimeMediaType()); - } - - /** - * Returns the preferred mime-type for a given file extension. If there is - * no mapping then null is returned. - * - * @param extension The extension we wish to know the mime-type for. - * @return MimeMediaType associated with this file extension. - */ - public static MimeMediaType getMimeTypeForFileExtension(String extension) { - factory.loadProviders(); - - MimeMediaType result = factory.extToMime.get(extension); - - return result; - } - - /** - * Register an instantiator object a mime-type of documents to be - * constructed. - * - * @param mimetype the mime-type associated. - * @param instantiator the instantiator that wants to be registered.. - * @return boolean true if the instantiator for this mime-type is now - * registered. If there was already an instantiator this mime-type then - * false will be returned. - * @throws SecurityException there were permission problems registering - * the instantiator. - */ - public static boolean registerInstantiator(MimeMediaType mimetype, Instantiator instantiator) { - boolean registered = factory.registerAssoc(mimetype.getBaseMimeMediaType(), instantiator); - - if (registered) { - Instantiator.ExtensionMapping[] extensions = instantiator.getSupportedFileExtensions(); - - for (int eachExt = 0; eachExt < extensions.length; eachExt++) { - if (null != extensions[eachExt].getMimeMediaType()) { - factory.extToMime.put(extensions[eachExt].getExtension(), extensions[eachExt].getMimeMediaType().intern()); - - factory.mimeToExt.put(extensions[eachExt].getMimeMediaType(), extensions[eachExt].getExtension()); - - // And the base version. - factory.mimeToExt.put(extensions[eachExt].getMimeMediaType().getBaseMimeMediaType(), extensions[eachExt].getExtension()); - } - } - } - - return registered; - } - - /** - * Constructs an instance of {@link StructuredDocument} matching - * the mime-type specified by the mimetype parameter. The - * doctype parameter identifies the base type of the - * {@link StructuredDocument}. - * - * @param mimetype Specifies the mime media type to be associated with - * the {@link StructuredDocument} to be created. - * @param doctype Specifies the root type of the {@link StructuredDocument} - * to be created. - * @return StructuredDocument The instance of {@link StructuredDocument} - * or null if it could not be created. - * @throws NoSuchElementException invalid mime-media-type - */ - public static StructuredDocument newStructuredDocument(MimeMediaType mimetype, String doctype) { - factory.loadProviders(); - - Instantiator instantiator = factory.getInstantiator(mimetype.getBaseMimeMediaType()); - - return instantiator.newInstance(mimetype, doctype); - } - - /** - * Constructs an instance of {@link StructuredDocument} matching - * the mime-type specified by the mimetype parameter. The - * doctype parameter identifies the base type of the - * {@link StructuredDocument}. Value supplies a value for the root - * element. - * - * @param mimetype Specifies the mime media type to be associated with - * the {@link StructuredDocument} to be created. - * @param doctype Specifies the root type of the {@link StructuredDocument} - * to be created. - * @param value Specifies a value for the root element. - * @return StructuredDocument The instance of {@link StructuredDocument} - * or null if it could not be created. - * @throws NoSuchElementException if the mime-type has not been registered. - */ - public static StructuredDocument newStructuredDocument(MimeMediaType mimetype, String doctype, String value) { - factory.loadProviders(); - - Instantiator instantiator = factory.getInstantiator(mimetype.getBaseMimeMediaType()); - - return instantiator.newInstance(mimetype, doctype, value); - } - - /** - * Constructs an instance of {@link StructuredDocument} matching - * the mime-type specified by the mimetype parameter. The - * doctype parameter identifies the base type of the - * {@link StructuredDocument}. - * - * @param mimetype Specifies the mime media type to be associated with the - * {@link StructuredDocument} to be created. - * @param stream Contains an InputStream from which the document will be - * constructed. - * @return StructuredDocument The instance of {@link StructuredDocument} - * or null if it could not be created. - * @throws IOException If there is a problem reading from the stream. - * @throws NoSuchElementException if the mime-type has not been registered. - */ - public static StructuredDocument newStructuredDocument(MimeMediaType mimetype, InputStream stream) throws IOException { - factory.loadProviders(); - - Instantiator instantiator = factory.getInstantiator(mimetype.getBaseMimeMediaType()); - - return instantiator.newInstance(mimetype, stream); - } - - /** - * Constructs an instance of {@link StructuredDocument} matching - * the mime-type specified by the mimetype parameter. The - * doctype parameter identifies the base type of the - * {@link StructuredDocument}. - * - * @param mimetype Specifies the mime media type to be associated with the - * {@link StructuredDocument} to be created. - * @param reader A Reader from which the document will be constructed. - * @return StructuredDocument The instance of {@link StructuredDocument} - * or {@code null} if it could not be created. - * @throws IOException If there is a problem reading from the stream. - * @throws NoSuchElementException if the mime-type has not been registered. - * @throws UnsupportedOperationException if the mime-type provided is not - * a text oriented MIME type. - */ - public static StructuredDocument newStructuredDocument(MimeMediaType mimetype, Reader reader) throws IOException { - factory.loadProviders(); - - Instantiator instantiator = factory.getInstantiator(mimetype.getBaseMimeMediaType()); - - if (!(instantiator instanceof TextInstantiator)) { - // XXX 20020502 bondolo@jxta.org we could probably do something - // really inefficient that would allow it to work, but better not to. - // if ReaderInputStream existed, it would be easy to do. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning( "Document Class \'" + instantiator.getClass().getName() + "\' associated with \'" + mimetype - + "\' is not a text oriented document"); - } - - throw new UnsupportedOperationException( "Document Class '" + instantiator.getClass().getName() - + "' associated with '" + mimetype + "' is not a text oriented document"); - } - - return ((TextInstantiator) instantiator).newInstance(mimetype, reader); - } - - /** - * Constructs an instance of {@link StructuredDocument} based upon the - * content of the provided message element. - * - * @param element The message element from which to create the document. - * @return StructuredDocument The instance of {@link StructuredDocument} - * or null if it could not be created. - * @throws IOException If there is a problem reading from the stream. - * @throws NoSuchElementException if the mime-type has not been registered. - */ - public static StructuredDocument newStructuredDocument(MessageElement element) throws IOException { - factory.loadProviders(); - - Instantiator instantiator = factory.getInstantiator(element.getMimeType().getBaseMimeMediaType()); - - if ((instantiator instanceof TextInstantiator) && (element instanceof TextMessageElement)) { - return ((TextInstantiator) instantiator).newInstance(element.getMimeType(), ((TextMessageElement) element).getReader()); - } else { - return instantiator.newInstance(element.getMimeType(), element.getStream()); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/StructuredDocumentUtils.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/StructuredDocumentUtils.java deleted file mode 100644 index 0a3b07da..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/StructuredDocumentUtils.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.util.Enumeration; - - -/** - * Provides a number of static utility members which are helpful in - * manipluating StructuredDocuments. - * - **/ -public final class StructuredDocumentUtils { - - /** - * A singleton class, not meant to be constructed - **/ - private StructuredDocumentUtils() { - ; - } - - /** - * Recursively copy children elements of from into the - * the element intoElement of document intoDoc. - * - *

      BEWARE that this does NOT copy the TEXTVALUE (if any) of the - * fromParent element, ONLY CHILDREN. All other elements - * are fully copied, including their textValue. - * - *

      It is not possible to copy a textValue in an existing element. - * - * @param intoDoc the document into which the elements will be - * copied. - * @param intoElement the element which will serve as the parent for - * the elements being copied. - * @param from the parent element of the elements which will be copied. - **/ - public static void copyChildren(StructuredDocument intoDoc, Element intoElement, Element from) { - - for (Enumeration eachChild = from.getChildren(); eachChild.hasMoreElements();) { - - Element aChild = (Element) eachChild.nextElement(); - Element newElement = intoDoc.createElement(aChild.getKey(), aChild.getValue()); - - intoElement.appendChild(newElement); - - // copy attributes if any - if ((aChild instanceof Attributable) && (newElement instanceof Attributable)) { - Enumeration eachAttrib = ((Attributable) aChild).getAttributes(); - - while (eachAttrib.hasMoreElements()) { - Attribute anAttrib = (Attribute) eachAttrib.nextElement(); - - ((Attributable) newElement).addAttribute(anAttrib.getName(), anAttrib.getValue()); - } - } - - // recurse to add the children. - copyChildren(intoDoc, newElement, aChild); - } - } - - /** - * Recursively copy elements beginnging with from into the - * document identified by intoDoc. - * - * @param intoDoc the document into which the elements which will be - * copied. - * @param intoElement the element which will serve as the parent for - * the elements being copied. - * @param from the root element of the hierarchy which will be copied. - * @param newName the root element being copied is renamed - * newName. - * @return The added element. - * - **/ - public static Element copyElements(StructuredDocument intoDoc, Element intoElement, Element from, Object newName) { - - Element newElement = intoDoc.createElement(newName, from.getValue()); - - intoElement.appendChild(newElement); - - boolean hasType = false; - - // copy attributes if any - if (newElement instanceof Attributable) { - - if (from instanceof Attributable) { - Enumeration eachAttrib = ((Attributable) from).getAttributes(); - - while (eachAttrib.hasMoreElements()) { - Attribute anAttrib = (Attribute) eachAttrib.nextElement(); - String attribName = anAttrib.getName(); - - if (attribName.equals("type")) { - hasType = true; - } - ((Attributable) newElement).addAttribute(attribName, anAttrib.getValue()); - } - } - - // If "from" happens to be a document, and if it happens to be renamed, and if it does not have an explicit type - // attribute, then preserve the document type, which we assume is the original name, converted to string, as a type - // attribute. It is an XMLism. It may be wrong or at least ineffective for other kinds of structured documents. If - // it one day becomes an issue, it will have to be resolved by having a method specific to each kind of structured - // document and dedicated to correcting type loss. - - Object origName = from.getKey().toString(); - - if ((!hasType) && (!newName.equals(origName)) && (from instanceof Document)) { - ((Attributable) newElement).addAttribute("type", origName.toString()); - } - } - - StructuredDocumentUtils.copyChildren(intoDoc, newElement, from); - - return newElement; - } - - /** - * Recursively copy elements beginnging with from into the - * document identified by intoDoc. - * - * @param intoDoc the document into which the elements which will be - * copied. - * @param intoElement the element which will serve as the parent for - * the elements being copied. - * @param from the root element of the hierarchy which will be copied. - * @return The added element. - **/ - public static Element copyElements(StructuredDocument intoDoc, Element intoElement, Element from) { - - return copyElements(intoDoc, intoElement, from, from.getKey()); - } - - /** - * Copies the specified element or document into a standalone document of - * same type. The from for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -/** - * Extends {@link StructuredDocument} to provide accessors appropriate for text - * based documents. - * - * @see net.jxta.document.Document - * @see net.jxta.document.StructuredDocument - * @see net.jxta.document.TextDocument - * @see net.jxta.document.Element - * @see net.jxta.document.TextElement - * @see net.jxta.document.StructuredDocumentFactory - */ -public interface StructuredTextDocument> extends TextDocument, StructuredDocument, TextElement { - - /** - * Create a new element without value. - * - * @param name The name of the element to be created. - * @return The new element. - */ - T createElement(String name); - - /** - * Create a new element with value. - * - * @param name The name of the element to be created. - * @param value The value of the element to be created. - * @return The new element. - */ - T createElement(String name, String value); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocument.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocument.java deleted file mode 100644 index 701a5b18..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocument.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.Writer; -import java.io.Reader; - -import java.io.IOException; - - -/** - * Extends {@link net.jxta.document.Document} for text documents. - * - * @see net.jxta.document.Document - */ -public interface TextDocument extends Document, TextDocumentReaderIO {} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentCharArrayIO.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentCharArrayIO.java deleted file mode 100644 index 9ad6c2c6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentCharArrayIO.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.Writer; -import java.io.Reader; - -import java.io.IOException; - - -/** - * Provides {@code char} array based interfaces for manipulating - * {@code TextDocument}s. - */ -public interface TextDocumentCharArrayIO { - - /** - * Returns the sequence of characters which represents the content of the - * {@code TextDocument}. - * - * @return A character array containing the characters of the - * {@code TextDocument}. - */ - char[] getChars(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentCharBufferIO.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentCharBufferIO.java deleted file mode 100644 index 304602cc..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentCharBufferIO.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.Writer; -import java.io.Reader; - -import java.io.IOException; - - -/** - * Provides {@code Reader}/{@code Writer} based interfaces for manipulating - * {@code TextDocument}s. - */ -public interface TextDocumentCharBufferIO { - - /** - * Returns the sequence of characters which represents the content of the - * {@code TextDocument}. - * - * @return A character array containing the characters of the - * {@code TextDocument}. - */ - CharSequence getCharSequence(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentCharSequenceIO.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentCharSequenceIO.java deleted file mode 100644 index fda5b275..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentCharSequenceIO.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.nio.CharBuffer; - - -/** - * Provides {@code Reader}/{@code Writer} based interfaces for manipulating - * {@code TextDocument}s. - */ -public interface TextDocumentCharSequenceIO { - - /** - * Returns the sequence of characters which represents the content of the - * {@code TextDocument}. - * - * @return A sequence of {@code CharBuffer}s containing the characters of - * the {@code TextDocument}. - */ - CharBuffer getCharBuffers(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentReaderIO.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentReaderIO.java deleted file mode 100644 index a1742ab6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextDocumentReaderIO.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.io.Writer; -import java.io.Reader; - -import java.io.IOException; - - -/** - * Provides {@code Reader}/{@code Writer} based interfaces for manipulating - * {@code TextDocument}s. - */ -public interface TextDocumentReaderIO { - - /** - * Returns the sequence of characters which represents the content of the - * {@code TextDocument}. - * - * @return An {@link java.io.Reader} containing the characters of the - * {@code TextDocument}. - * @throws IOException If an I/O error occurs. - */ - Reader getReader() throws IOException; - - /** - * Send the contents of this {@code TextDocument} to the specified - * Writer. - * - * @param writer The {@link java.io.Writer} to which the characters of the - * {@code TextDocument} will be written. - * @throws IOException If an I/O error occurs. - */ - void sendToWriter(Writer writer) throws IOException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextElement.java deleted file mode 100644 index c816cee9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/TextElement.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.util.Enumeration; - - -/** - * Extends {@link Element} to provide {@link java.lang.String} oriented - * accessors for instances of {@link StructuredTextDocument} - * - * @see net.jxta.document.Document - * @see net.jxta.document.Element - * @see net.jxta.document.StructuredDocument - * @see net.jxta.document.StructuredTextDocument - */ -public interface TextElement> extends Element { - - /** - * {@inheritDoc} - */ - String getKey(); - - /** - * {@inheritDoc} - */ - String getValue(); - - /** - * {@inheritDoc} - */ - StructuredTextDocument getRoot(); - - /** - * Get the name associated with an element. - * - * @return A string containing the name of this element. - */ - String getName(); - - /** - * Get the value (if any) associated with an element. - * - * @return A string containing the value of this element, if any, otherwise null. - */ - String getTextValue(); - - /** - * Returns an enumeration of the immediate children of this element whose - * name match the specified string. - * - * @param name The name which will be matched against. - * @return An enumeration containing all of the children of this element. - */ - Enumeration getChildren(String name); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/XMLDocument.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/XMLDocument.java deleted file mode 100644 index 1424da1e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/XMLDocument.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -/** - * Common interfaces for all {@link net.jxta.document.StructuredTextDocument} - * which are implemented by XML Documents. Appropriate for advertisements and - * messages. - */ -public interface XMLDocument> extends XMLElement, StructuredTextDocument { - - /** - * {@inheritDoc} - */ - X createElement(String name); - - /** - * {@inheritDoc} - */ - X createElement(String name, String value); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/XMLElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/XMLElement.java deleted file mode 100644 index 091ffc8e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/XMLElement.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.document; - - -import java.util.Enumeration; - - -/** - * Common definition of XML Elements. Appropriate for advertisements and - * messages. - */ -public interface XMLElement> extends TextElement, Attributable { - - /** - * {@inheritDoc} - */ - XMLDocument getRoot(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/package.html deleted file mode 100644 index e579d09e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/document/package.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - JXTA Documents are containers for both structured and unstructured data. - Advertisements are used to describe JXTA resources such as peers, groups, - services, and codats. - - @see JXTA Protocols Specification : Advertisementss - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/AbstractMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/AbstractMessenger.java deleted file mode 100644 index d81cba5e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/AbstractMessenger.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -import net.jxta.util.AbstractSimpleSelectable; -import net.jxta.util.SimpleSelectable; - -import java.io.IOException; -import java.io.InterruptedIOException; - - -/** - * An AbstractMessenger is used to implement messengers (for example, by transport modules). - * It supplies the convenience, bw compatible, obvious, or otherwise rarely changed methods. - * Many method cannot be overloaded in order to ensure standard behaviour. - * The rest is left to implementations. - * - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.endpoint.EndpointAddress - * @see net.jxta.endpoint.Message - */ -public abstract class AbstractMessenger extends AbstractSimpleSelectable implements Messenger { - - /** - * The default Maximum Transmission Unit. - */ - protected static final long DEFAULT_MTU = Long.parseLong(System.getProperty("net.jxta.MTU", "65536")); - - /** - * The destination address of messages sent on this messenger. - */ - protected final EndpointAddress dstAddress; - - /** - * The stateLock that we share with the implementation. - * This permits to implement waitState in a totally generic way: waitState depends only on the lock - * (provided at construction), and on getState(), supplied by the implementation. - */ - private Object stateLock; - - /** - * Create a new abstract messenger. - *

      - * Warning: This class needs to know the object on which to waitState must synchronize. It is generally impossible - * to pass it at construction because it is not yet constructed. Instead implementations MUST call {@link #setStateLock} - * from their constructor. - * - * @param dest who messages should be addressed to - */ - public AbstractMessenger(EndpointAddress dest) { - dstAddress = dest; - } - - /** - * {@inheritDoc} - *

      - * A simple implementation for debugging. Do not depend upon the format. - */ - @Override - public String toString() { - return super.toString() + " {" + dstAddress + "}"; - } - - /** - * Specifies the object on which waitState must synchronize. - * - * @param stateLock The object on which waitState must synchronize. This has to be the object that gets notified when the - * implementation changes its state. Changing state is defined as "any operation that causes the result of the - * getState method to change". Implementations that use the MessengerState state machine should typically use the - * MessengerState object as their state lock, but it is not assumed. - */ - protected void setStateLock(Object stateLock) { - this.stateLock = stateLock; - } - - /* - * Messenger methods implementations. - */ - - /** - * {@inheritDoc} - *

      - * This is here for backward compatibility reasons. The notion of long term unemployment still exists, but is no-longer part - * of the API. Self closing for unemployment is now a built-in feature of messengers. - */ - @Deprecated - public final boolean isIdle() { - return false; - } - - /** - * {@inheritDoc} - */ - @Deprecated - public final boolean isSynchronous() { - return false; - } - - /** - * {@inheritDoc} - */ - public final EndpointAddress getDestinationAddress() { - return dstAddress; - } - - /** - * {@inheritDoc} - */ - @Deprecated - public final EndpointAddress getDestinationAddressObject() { - return dstAddress; - } - - /** - * {@inheritDoc} - *

      It is not always enforced. At least this much can always be sent. - */ - public long getMTU() { - return DEFAULT_MTU; - } - - /** - * {@inheritDoc} - *

      - * This is a minimal implementation. It may not detect closure - * initiated by the other side unless the messenger was actually used - * since. A more accurate (but not mandatory implementation) would - * actually go and check the underlying connection, if relevant...unless - * breakage initiated by the other side is actually reported asynchronously - * when it happens. Breakage detection from the other side need not - * be reported atomically with its occurrence. This not very important - * since we canonicalize transport messengers and so do not need to - * aggressively collect closed ones. When not used, messengers die by themselves. - */ - public boolean isClosed() { - return (getState() & USABLE) == 0; - } - - /** - * {@inheritDoc} - */ - public final void flush() throws IOException { - int currentState = 0; - - try { - currentState = waitState(IDLE, 0); - } catch (InterruptedException ie) { - InterruptedIOException iio = new InterruptedIOException("flush() interrupted"); - - iio.initCause(ie); - throw iio; - } - - if ((currentState & (CLOSED | USABLE)) != 0) { - return; - } - - throw new IOException("Messenger was unexpectedly closed."); - } - - /** - * {@inheritDoc} - */ - public final boolean sendMessage(Message msg) throws IOException { - return sendMessage(msg, null, null); - } - - /** - * {@inheritDoc} - * - */ - public void sendMessage(Message msg, String service, String serviceParam, OutgoingMessageEventListener listener) { - throw new UnsupportedOperationException("This legacy method is not supported by this messenger."); - } - - /** - * {@inheritDoc} - */ - public final boolean sendMessage(Message msg, String rService, String rServiceParam) throws IOException { - - // We have to retrieve the failure from the message and throw it if its an IOException, this is what the API - // says that this method does. - - if (sendMessageN(msg, rService, rServiceParam)) { - return true; - } - - Object failed = msg.getMessageProperty(Messenger.class); - - if ((failed == null) || !(failed instanceof OutgoingMessageEvent)) { - // huh ? - return false; - } - - Throwable t = ((OutgoingMessageEvent) failed).getFailure(); - - if (t == null) { - // Must be saturation, then. (No throw for that). - return false; - } - - // Now see how we can manage to throw it. - if (t instanceof IOException) { - throw (IOException) t; - } else if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } else if (t instanceof Error) { - throw (Error) t; - } - - IOException failure = new IOException("Failure sending message"); - - failure.initCause(t); - - throw failure; - } - - /** - * {@inheritDoc} - *

      - * This method synchronizes on the lock object supplied at construction. - */ - public final int waitState(int wantedStates, long timeout) throws InterruptedException { - synchronized (stateLock) { - if (timeout == 0) { - while ((wantedStates & getState()) == 0) { - stateLock.wait(); - } - return getState(); - } - - if (timeout < 0) { - stateLock.wait(timeout); // let it throw the appropriate error. - } - - long start = System.currentTimeMillis(); - long end = start + timeout; - - if (end < start) { - end = Long.MAX_VALUE; - } - long left = end - start; - - while ((left > 0) && (wantedStates & getState()) == 0) { - - stateLock.wait(left); - - left = end - System.currentTimeMillis(); - } - - return getState(); - } - } - - /* - * SimpleSelectable implementation. - */ - - /** - * Implements a default for all AbstractMessengers: mirror the event to our selectors. This is what is needed by all the - * known AbstractMessengers that register themselves somewhere. (That is ChannelMessengers). - * FIXME - jice@jxta.org 20040413: Not sure that this is the best default. - * - * @param changedObject Ignored. - */ - public void itemChanged(SimpleSelectable changedObject) { - notifyChange(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/AsyncChannelMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/AsyncChannelMessenger.java deleted file mode 100644 index ff8607eb..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/AsyncChannelMessenger.java +++ /dev/null @@ -1,665 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - -import net.jxta.peergroup.PeerGroupID; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; - -/** - * Extends Channel Messenger behaviour to provide asynchronous message sending - * via queuing. - */ -public abstract class AsyncChannelMessenger extends ChannelMessenger { - - /* - * Logger - * private final static transient Logger LOG = Logger.getLogger(AsyncChannelMessenger.class.getName()); - */ - - /** - * {@code true} if we have deliberately closed our one message input queue. - */ - private boolean inputClosed = false; - - /** - * {@code true} if we have deliberately stopped sending. - */ - private boolean outputClosed = false; - - /** - * Actions that we defer to after returning from event methods. In other - * words, they cannot be done with the lock held, or they require calling - * more event methods. - */ - private enum DeferredAction { - - /** - * No action deferred. - */ - ACTION_NONE, - /** - * Must send the current message. - */ - ACTION_SEND, - /** - * Must report failure to connect. - */ - ACTION_CONNECT - } - - /** - * The current deferred action. - */ - private DeferredAction deferredAction = DeferredAction.ACTION_NONE; - - /** - * The messages queue. - */ - private final BlockingQueue queue; - - /** - * State lock and engine. - */ - private final AsyncChannelMessengerState stateMachine; - - /** - * Our statemachine implementation; just connects the standard MessengerState action methods to - * this object. - */ - private class AsyncChannelMessengerState extends MessengerState { - - protected AsyncChannelMessengerState(boolean connected) { - super(connected); - } - - /* - * The required action methods. - */ - - /** - * {@inheritDoc} - */ - @Override - protected void connectAction() { - deferredAction = DeferredAction.ACTION_CONNECT; - } - - /** - * {@inheritDoc} - */ - @Override - protected void startAction() { - deferredAction = DeferredAction.ACTION_SEND; - } - - /** - * {@inheritDoc} - */ - @Override - protected void closeInputAction() { - // We're synchronized here. (invoked from stateMachine) - inputClosed = true; - } - - /** - * {@inheritDoc} - */ - @Override - protected void closeOutputAction() { - // We're synchronized here. (invoked from stateMachine) - outputClosed = true; - } - - /** - * {@inheritDoc} - */ - @Override - protected void failAllAction() { - - // The queue is now closed, so we can rest assured that the last - // message is really the last one. This is a synchronous action. The - // state machine assumes that it is done when we return. There is no - // need to signal completion with an idleEvent. - PendingMessage theMsg; - - while (true) { - theMsg = null; - - synchronized (stateMachine) { - theMsg = queue.poll(); - } - - if (theMsg == null) { - return; - } - - Message currentMsg = theMsg.msg; - Throwable currentFailure = theMsg.failure; - - if (currentFailure == null) { - currentFailure = new IOException("Messenger unexpectedly closed"); - } - - OutgoingMessageEvent event = new OutgoingMessageEvent(currentMsg, currentFailure); - - currentMsg.setMessageProperty(Messenger.class, event); - } - } - } - - - /** - * The representation of a queued message. It is shared between this - * abstract class and any implementation. - */ - protected static class PendingMessage { - final Message msg; - final String service; - final String param; - Throwable failure; - - PendingMessage(Message msg, String service, String param) { - this.msg = msg; - this.service = service; - this.param = param; - this.failure = null; - } - } - - /** - * Create a new AsyncChannelMessenger. - * - * @param baseAddress The network address messages go to; regardless of - * service, param, or group. - * @param redirection Group to which the messages must be redirected. This - * is used to implement the automatic group segregation which has become a - * de-facto standard. If not null, the unique portion of the specified - * groupID is prepended with {@link #InsertedServicePrefix} and inserted in - * every message's destination address in place of the the original service - * name, which gets shifted into the beginning of the service parameter. The - * opposite is done on arrival to restore the original destination address - * before the message is delivered to the listener in the the specified - * group. Messages that already bear a group redirection are not affected. - * @param origService The default destination service for messages sent - * without specifying a different service. - * @param origServiceParam The default destination service parameter for - * messages sent without specifying a different service parameter. - * @param queueSize the queue size that channels should have. - * @param connected true if the channel is created in the connected state. - */ - public AsyncChannelMessenger(EndpointAddress baseAddress, PeerGroupID redirection, String origService, String origServiceParam, int queueSize, boolean connected) { - - super(baseAddress, redirection, origService, origServiceParam); - - stateMachine = new AsyncChannelMessengerState(connected); - - queue = new ArrayBlockingQueue(queueSize); - - // We synchronize our state with the sharedMessenger's stateMachine. - // Logic would dictate that we pass it to super(), but it is not itself - // constructed until super() returns. No way around it. - - setStateLock(stateMachine); - } - - /** - * {@inheritDoc} - */ - public final void close() { - DeferredAction action; - - synchronized (stateMachine) { - stateMachine.closeEvent(); - action = eventCalled(true); - } - - // We called an event. State may have changed. - notifyChange(); - - performDeferredAction(action); - } - - /** - * This internal method does the common part of sending the message on - * behalf of both sendMessageN and sendMessageB. - *

      It is not quite possible to implement sendMessageB as a wrapper - * around sendMessageN without some internal cooperation. At least not in - * an efficient manner. sendMessageB must not set the message property: - * either it fails and throws, or it returns successfully and the property - * is set later. This is required so that messages can be retried when - * failing synchronously (through a blocking messenger typically, but the - * semantic has to be uniform). - *

      Each of sendMessageB and sendMessageN takes care of status reporting - * on its own terms. - * - * @param msg the message to send - * @param rService destination service - * @param rServiceParam destination param - * @return The outcome from that one attempt. {@code true} means done. - * {@code false} means saturated. When {@code true} is returned, it means - * that the fate of the message will be decided asynchronously, so we do - * not have any details, yet. - * @throws IOException is thrown if this messenger is closed. - * @throws InterruptedException if interrupted - */ - private boolean sendMessageCommon(Message msg, String rService, String rServiceParam) throws IOException, InterruptedException { - - String service = effectiveService(rService); - String serviceParam = effectiveParam(rService, rServiceParam); - boolean queued = true; - boolean change = false; - DeferredAction action = DeferredAction.ACTION_NONE; - - synchronized (stateMachine) { - if (inputClosed) { - throw new IOException("This messenger is closed. It cannot be used to send messages."); - } - - boolean wasEmpty = queue.isEmpty(); - - if (queue.remainingCapacity() > 1) { - queue.put(new PendingMessage(msg, service, serviceParam)); - - // Still not saturated. If we weren't idle either, then nothing worth mentionning. - if (wasEmpty) { - change = true; - stateMachine.msgsEvent(); - action = eventCalled(false); - } - } else if (1 == queue.remainingCapacity()) { - queue.put(new PendingMessage(msg, service, serviceParam)); - - // Now saturated. - stateMachine.saturatedEvent(); - action = eventCalled(false); - change = true; - } else { - // Was already saturated. - queued = false; - } - } - - if (queued && change) { - // If not queued, there was no change of condition as far as - // outsiders are concerned. (redundant saturatedEvent, only - // defensive; to guarantee statemachine in sync). else, if the - // saturation state did not change, we have no state change to - // notify. - notifyChange(); - } - - performDeferredAction(action); - - // Before we return, make sure that this channel remains referenced if - // it has messages. It could become unreferenced if it is not yet - // resolved and the application lets go of it after sending messages. - // This means that we may need to do something only in the resolpending - // and resolsaturated cases. The way we do this test, there can be false - // positives. They're dealt with as part of the action that is carried - // out. - if ((stateMachine.getState() & (Messenger.RESOLPENDING | Messenger.RESOLSATURATED)) != 0) { - resolPendingImpl(); - } - - return queued; - } - - /** - * {@inheritDoc} - */ - public final boolean sendMessageN(Message msg, String rService, String rServiceParam) { - - try { - if (sendMessageCommon(msg, rService, rServiceParam)) { - // If it worked the message is queued; the outcome will be notified later. - return true; - } - // Non-blocking and queue full: report overflow. - msg.setMessageProperty(Messenger.class, OutgoingMessageEvent.OVERFLOW); - } catch (IOException oie) { - msg.setMessageProperty(Messenger.class, new OutgoingMessageEvent(msg, oie)); - } catch (InterruptedException interrupted) { - msg.setMessageProperty(Messenger.class, new OutgoingMessageEvent(msg, interrupted)); - } - return false; - } - - /** - * {@inheritDoc} - */ - public final void sendMessageB(Message msg, String rService, String rServiceParam) throws IOException { - - try { - while (true) { - // if sendMessageCommon says "true" it worked. - if (sendMessageCommon(msg, rService, rServiceParam)) { - return; - } - // Do a shallow check on the queue. If it seems empty (without getting into a critical section to - // verify it), then yielding is good bet. It is a lot cheaper and smoother than waiting. - // Note the message should be enqueued now. yielding makes sense now if the queue is empty - if (queue.isEmpty()) { - Thread.yield(); - } - - // If we reached this far, it is neither closed, nor ok. So it was saturated. - synchronized (stateMachine) { - // Cheaper than waitState. sendMessageCommon already does the relevant state checks. - stateMachine.wait(); - } - } - } catch (InterruptedException ie) { - InterruptedIOException iie = new InterruptedIOException("Message send interrupted"); - - iie.initCause(ie); - throw iie; - } - } - - /** - * {@inheritDoc} - */ - public final void resolve() { - DeferredAction action; - - synchronized (stateMachine) { - stateMachine.resolveEvent(); - action = eventCalled(true); - } - notifyChange(); - performDeferredAction(action); // we expect connect but let the state machine decide. - } - - /** - * {@inheritDoc} - */ - public final int getState() { - return stateMachine.getState(); - } - - /** - * {@inheritDoc} - */ - @Override - public final Messenger getChannelMessenger(PeerGroupID redirection, String service, String serviceParam) { - // Channels don't make channels. - return null; - } - - /** - * Three exposed methods may need to inject new events in the system: - * sendMessageN, close, and shutdown. - * Since they can all cause actions, and since connectAction and - * startAction are deferred, it seems possible that one of the actions - * caused by send, close, or shutdown be called while connectAction or - * startAction are in progress. - *

      However, the state machine gives us a few guarantees: connectAction - * and startAction can never nest. We will not be asked to perform one while - * still performing the other. Only the synchronous actions closeInput, - * closeOutput, or failAll can possibly be requested in the interval. We - * could make more assumptions and simplify the code, but rather keep at - * least some flexibility. - *

      - * DEAD LOCK WARNING: the implementor's method invoke some of our call backs - * while synchronized. Then our call backs synchronize on the state machine - * in here. This nesting order must always be respected. As a result, we can - * never invoke implementors methods while synchronized. Hence the - * deferredAction processing. - * - * @param action the action - */ - private void performDeferredAction(DeferredAction action) { - switch (action) { - case ACTION_SEND: - startImpl(); - break; - - case ACTION_CONNECT: - connectImpl(); - break; - } - } - - /** - * A shortHand for a frequently used sequence. MUST be called while - * synchronized on stateMachine. - * - * @param notifyAll If {@code true} then this is a life-cycle event and all - * waiters on the stateMachine should be notified. If {@code false} then - * only a single waiter will be notified for simple activity events. - * @return the deferred action. - */ - private DeferredAction eventCalled(boolean notifyAll) { - DeferredAction action = deferredAction; - - deferredAction = DeferredAction.ACTION_NONE; - if (notifyAll) { - stateMachine.notifyAll(); - } else { - stateMachine.notify(); - } - return action; - } - - /* - * Implement the methods that our shared messenger will use to report progress. - */ - - /** - * The implementation will invoke this method when it becomes resolved, - * after connectImpl was invoked. - */ - protected void up() { - DeferredAction action; - - synchronized (stateMachine) { - stateMachine.upEvent(); - action = eventCalled(true); - } - notifyChange(); - performDeferredAction(action); // we expect start but let the state machine decide. - } - - /** - * The implementation invokes this method when it becomes broken. - */ - protected void down() { - DeferredAction action; - - synchronized (stateMachine) { - stateMachine.downEvent(); - action = eventCalled(true); - } - notifyChange(); - performDeferredAction(action); // we expect connect but let the state machine decide. - } - - /** - * Here, we behave like a queue to the shared messenger. When we report - * being empty, though, we're automatically removed from the active queues - * list. We'll go back there the next time we have something to send by - * calling startImpl. - * - * @return pending message - */ - protected PendingMessage peek() { - - PendingMessage theMsg; - DeferredAction action = DeferredAction.ACTION_NONE; - - synchronized (stateMachine) { - // We like the msg to keep occupying space in the queue until it's - // out the door. That way, idleness (that is, not currently working - // on a message), is always consistent with queue emptyness. - - theMsg = queue.peek(); - if (theMsg == null) { - stateMachine.idleEvent(); - action = eventCalled(false); - - // We do not notifyChange, here, because, if the queue is empty, - // it was already notified when the last message was popped. The - // call to idleEvent is only defensive programming to make extra - // sure the state machine is in sync. - - return null; - } - - if (outputClosed) { - // We've been asked to stop sending. Which, if we were sending, - // must be notified by either an idle event or a down - // event. Nothing needs to happen to the shared messenger. We're - // just a channel. - stateMachine.downEvent(); - action = eventCalled(true); - theMsg = null; - } - } - - notifyChange(); - performDeferredAction(action); // we expect none but let the state machine decide. - return theMsg; - } - - /** - * Returns the number of elements in this collection. If this collection - * contains more than Integer.MAX_VALUE elements, returns - * Integer.MAX_VALUE. - * - * @return the number of elements in this collection - */ - protected int size() { - return queue.size(); - } - - /** - * One message done. Update the saturated/etc state accordingly. - * - * @return true if there are more messages after the one we removed. - */ - protected boolean poll() { - - boolean result; - DeferredAction action; - - synchronized (stateMachine) { - queue.poll(); - - if (queue.peek() == null) { - stateMachine.idleEvent(); - action = eventCalled(false); - result = false; - } else { - stateMachine.msgsEvent(); - action = eventCalled(false); - result = true; - } - } - - notifyChange(); - performDeferredAction(action); // we expect none but let the state machine decide. - - return result; - } - - /** - * We invoke this method to be placed on the list of channels that have - * message to send. - *

      - * NOTE that it is the shared messenger responsibility to synchronize so - * that we cannot be added to the active list just before we get removed - * due to reporting an empty queue in parallel. So, if we report an empty - * queue and have a new message to send before the shared messenger removes - * us form the active list, startImpl will block until the removal is done. - * Then we'll be added back. - *

      - * If it cannot be done, it means that the shared messenger is no longer - * usable. It may call down() in sequence. Out of defensiveness, it should - * do so without holding its lock. - */ - protected abstract void startImpl(); - - /** - * We invoke this method to be placed on the list of channels that are - * waiting for resolution. - *

      - * If it cannot be done, it means that the shared messenger is no longer - * usable. It may call down() in sequence. Out of defensiveness, it should - * do so without holding its lock. If the messenger is already resolved it - * may call up() in sequence. Same wisdom applies. It is a good idea to - * create channels in the resolved state if the shared messenger is already - * resolved. That avoids this extra contortion. - */ - protected abstract void connectImpl(); - - /** - * This is invoked to inform the implementation that this channel is now in - * the resolPending or resolSaturated state. This is specific to this type - * of channels. The shared messenger must make sure that this channel - * remains strongly referenced, even though it is not resolved, because - * there are messages in it. It is valid for an application to let go of a - * channel after sending a message, even if the channel is not yet - * resolved. The message will go if/when the channel resolves. This method - * may be invoked redundantly and even once the channel is no longer among - * the one awaiting resolution. The implementation must be careful to - * ignore such calls. - */ - protected abstract void resolPendingImpl(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ByteArrayMessageElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ByteArrayMessageElement.java deleted file mode 100644 index f2892b7e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ByteArrayMessageElement.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -import net.jxta.document.MimeMediaType; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.*; -import java.lang.ref.SoftReference; -import java.util.zip.CRC32; -import java.util.zip.Checksum; - - -/** - * A Message Element using byte arrays for the element data. - * - *

      This implementation does not copy the byte array provided and assumes - * that the contents of the byte array will not change through out the lifetime - * of the MessageElement. - * - *

      some synchronization is due to optimization in {@link #getBytes(boolean)} - * which replaces value of internal member {@link #b}. - */ -public class ByteArrayMessageElement extends MessageElement { - - /** - * Logger - */ - private static transient final Logger LOG = Logger.getLogger(ByteArrayMessageElement.class.getName()); - - /** - * The bytes of this element. - */ - protected byte[] b; - - /** - * This is the offset of our data within the array - */ - protected int offset; - - /** - * length of the element data. sometimes the same as b.length, but may be - * lesser. - */ - protected int len; - - /** - * Create a new Message Element. The contents of the provided byte array - * are not copied during construction. - * - * @param name Name of the MessageElement. May be the empty string ("") if - * the MessageElement is not named. - * @param type Type of the MessageElement. null is the same as specifying - * the type "Application/Octet-stream". - * @param b A byte array containing the contents of this element. - * @param sig optional message digest/digital signature element or null if - * no signature is desired. - */ - public ByteArrayMessageElement(String name, MimeMediaType type, byte[] b, MessageElement sig) { - this(name, type, b, 0, b.length, sig); - } - - /** - * Create a new MessageElement, The contents of the provided byte array are - * not copied during construction. - * - * @param name Name of the MessageElement. May be the empty string ("") if - * the MessageElement is not named. - * @param type Type of the MessageElement. null is the same as specifying - * the type "Application/Octet-stream". - * @param b A byte array containing the contents of this element. - * @param offset all bytes before this location in b - * will be ignored. - * @param sig optional message digest/digital signature elemnent or null if - * no signature is desired. - */ - public ByteArrayMessageElement(String name, MimeMediaType type, byte[] b, int offset, MessageElement sig) { - this(name, type, b, offset, b.length - offset, sig); - } - - /** - * Create a new Element, but dont add it to the message. The contents of - * the byte array are not copied during construction. - * - * @param name Name of the MessageElement. May be the empty string ("") if - * the MessageElement is not named. - * @param type Type of the MessageElement. null is the same as specifying - * the type "Application/Octet-stream". - * @param b A byte array containing the contents of this Element. - * @param offset all bytes before this location will be ignored. - * @param len number of bytes to include - * @param sig optional message digest/digital signature element or null if - * no signature is desired. - */ - public ByteArrayMessageElement(String name, MimeMediaType type, byte[] b, int offset, int len, MessageElement sig) { - super(name, type, sig); - - if (null == b) { - throw new IllegalArgumentException("byte array must not be null"); - } - - if (len < 0) { - throw new IllegalArgumentException("len must be >= 0 : " + len); - } - - if (offset < 0) { - throw new IllegalArgumentException("offset must within byte array : " + offset); - } - - if ((0 != len) && (offset >= b.length)) { - throw new IllegalArgumentException("offset must be positioned within byte array : " + offset + "," + len); - } - - if (((offset + len) > b.length) || ((offset + len) < 0)) { - throw new IllegalArgumentException("offset + len must be positioned within byte array"); - } - - // if we get an empty request and a non-empty buffer, we don't use the provided buffer. - if ((0 == len) && (0 != b.length)) { - b = new byte[len]; - offset = 0; - } - - this.b = b; - this.offset = offset; - this.len = len; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof MessageElement) { - if (!super.equals(target)) { - return false; - } - - if (target instanceof ByteArrayMessageElement) { - ByteArrayMessageElement likeMe = (ByteArrayMessageElement) target; - - synchronized (this) { - synchronized (likeMe) { - if (likeMe.len != len) { - return false; - } - - for (int eachByte = len - 1; eachByte >= 0; eachByte--) { - if (likeMe.b[likeMe.offset + eachByte] != b[offset + eachByte]) { - return false; - } - } - } - } - - return true; - } else { - // have to do a slow stream comparison. - // XXX 20020615 bondolo@jxta.org the performance of this could be much improved. - try { - MessageElement likeMe = (MessageElement) target; - - InputStream myStream = getStream(); - InputStream itsStream = likeMe.getStream(); - - int mine; - int its; - - do { - mine = myStream.read(); - its = itsStream.read(); - - if (mine != its) { - return false; - } // content didn't match - - } while ((-1 != mine) && (-1 != its)); - - return ((-1 == mine) && (-1 == its)); // end at the same time? - } catch (IOException fatal) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "MessageElements could not be compared.", fatal); - } - - throw new IllegalStateException("MessageElements could not be compared." + fatal); - } - } - } - - return false; // not a message element - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int hashCode() { - Checksum crc = new CRC32(); - - crc.update(b, offset, len); - int dataHash = (int) crc.getValue(); - - int result = super.hashCode() * 6037 + // a prime - dataHash; - - return (0 != result) ? result : 1; - } - - /** - * {@inheritDoc} - *

      - * Returns the string representation of this element. The 'charset' - * parameter of the mimetype, if any, is used to determine encoding. If - * the charset specified is unsupported then the default encoding will be - * used. - * - * @return String string representation of this message element. - */ - @Override - public synchronized String toString() { - String result; - - if (null != cachedToString) { - result = cachedToString.get(); - - if (null != result) { - return result; - } - } - - if (LOG.isLoggable(Level.FINER)) { - LOG.finer("creating toString of " + getClass().getName() + '@' + Integer.toHexString(hashCode())); - } - - String charset = type.getParameter("charset"); - - try { - if (null == charset) { - result = new String(b, offset, len); - } else { - result = new String(b, offset, len, charset); - } - } catch (UnsupportedEncodingException caught) { - result = new String(b, offset, len); - } - - cachedToString = new SoftReference(result); - - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public long getByteLength() { - return len; - } - - /** - * {@inheritDoc} - *

      - *

      synchronized so that we can replace our internal buffer with - * the buffer we are returning if we were using a shared buffer. - */ - @Override - public synchronized byte[] getBytes(boolean copy) { - if ((!copy) && (0 == offset) && (b.length == len)) { - return b; - } - - byte[] result = new byte[len]; - - System.arraycopy(b, offset, result, 0, len); - - // if we were using a sub-array we can switch to using this copy. - if (!copy) { - b = result; - offset = 0; - } - - return result; - } - - /** - * {@inheritDoc} - */ - public synchronized InputStream getStream() { - return new ByteArrayInputStream(b, offset, len); - } - - /** - * {@inheritDoc} - */ - @Override - public void sendToStream(OutputStream sendTo) throws IOException { - byte[] sending; - int sendingOffset; - - // locals enable us to reduce the time which the object is synchronized. - synchronized (this) { - sending = b; - sendingOffset = offset; - } - - sendTo.write(sending, sendingOffset, len); - } - - /** - * Returns the contents of this element as a byte array. If this elements - * was originally constructed from a intact byte array, the array returned - * is a "shared" copy of the byte array used by this element. If this - * element was constructed with an offset of other than zero and a length - * different than the length of the source array then this function WILL - * RETURN A COPY OF THE BYTE ARRAY. - * - * @return a byte array containing the contents of this element. - */ - public byte[] getBytes() { - return getBytes(false); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ChannelMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ChannelMessenger.java deleted file mode 100644 index 38beb662..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ChannelMessenger.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -import net.jxta.peergroup.PeerGroupID; - - -/** - * A Channel Messenger provides an exclusive interface to the shared messenger. - *

      - * What is typically exclusive is the message queue, addressing parameters - * that are not usefully shared (serviceName, serviceParam), and if needed - * cross-group address rewriting parameters. - *

      - * This class is provided as a base for implementing such channel messengers, - * which are typically what Messenger.getChannelMessenger() needs to return. - * - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.endpoint.EndpointAddress - * @see net.jxta.endpoint.Message - */ -public abstract class ChannelMessenger extends AbstractMessenger implements Messenger { - - /** - * insertedServicePrefix This is how all valid inserted services start. This - * lets us recognize if a message already has an inserted service. Then we - * must not add another one. Only the top-most one counts. Since insertion - * is only done here, the constant is defined here. Even if historically it - * was done within the endpoint implementation, it has become a protocol now. - */ - public static final String InsertedServicePrefix = "EndpointService:"; - - private String insertedService; - - /** - * The worker that implements sendMessage-with-listener for this channel. If - * there's none, sendMessage-with-listener will throw an exception. Channels - * returned by getMessenger methods all have one already. It is up to the - * invoker of getChannelMessenger to supply one or not. - */ - private ListenerAdaptor messageWatcher; - - protected String origService; - - protected String origServiceParam; - - /** - * Figure out what the service string will be after mangling (if required) - * and applying relevant defaults. - * - * @param service The service name in the unmangled address. - * @return String The service name in the mangled address. - */ - protected String effectiveService(String service) { - - // No redirection required. Just apply the default service. - if (insertedService == null) { - return (service == null) ? origService : service; - } - - // Check if redirection is applicable. - return ((service != null) && service.startsWith(InsertedServicePrefix)) ? service : insertedService; - } - - /** - * Figure out what the param string will be after mangling (if required) and - * applying relevant defaults. - * - * @param service The service name in the unmangled address. - * @param serviceParam The service parameter in the unmangled address. - * @return String The service parameter in the mangled address. - */ - protected String effectiveParam(String service, String serviceParam) { - - // No redirection required. Or not applicable. Just apply the default param. - if ((insertedService == null) || ((service != null) && service.startsWith(InsertedServicePrefix))) { - return (serviceParam == null) ? origServiceParam : serviceParam; - } - - // Apply redirection. We need the effective service, now. - if (service == null) { - service = origService; - } - - if (serviceParam == null) { - serviceParam = origServiceParam; - } - - return ((null != service) && (null != serviceParam)) ? (service + "/" + serviceParam) : service; - } - - /** - * Give this channel the watcher that it must use whenever sendMessage(...,listener) is used. If not set, - * sendMessage(..., listener) will throw. - * - * @param messageWatcher the listener - */ - public void setMessageWatcher(ListenerAdaptor messageWatcher) { - this.messageWatcher = messageWatcher; - } - - /** - * Create a new ChannelMessenger - * - * @param baseAddress The network address messages go to; regardless of service, param, or group. - * @param groupRedirection Group to which the messages must be redirected. This is used to implement the automatic group - * segregation which has become a de-facto standard. If not null, the unique portion of the specified groupID is - * prepended with {@link #InsertedServicePrefix} and inserted in every message's destination address in place of the - * the original service name, which gets shifted into the beginning of the service parameter. The opposite is done - * on arrival to restore the original destination address before the message is delivered to the listener in the - * the specified group. Messages that already bear a group redirection are not affected. - * @param origService The default destination service for messages sent without specifying a different service. - * @param origServiceParam The default destination service parameter for messages sent without specifying a different service - * parameter. - */ - public ChannelMessenger(EndpointAddress baseAddress, PeerGroupID groupRedirection, String origService, String origServiceParam) { - - // FIXME: The inserted service business is really messy. Group seggregation does not have to be the endpoint service's - // business. It should be specified by the app as part of the destination address. What we're doing here - // is simply enforcing what could just be a convention. - - super(baseAddress); - if (groupRedirection == null) { - insertedService = null; - } else { - insertedService = InsertedServicePrefix + groupRedirection.getUniqueValue().toString(); - } - this.origService = origService; - this.origServiceParam = origServiceParam; - } - - /** - * {@inheritDoc} - *

      - * By default a channel refuses to make a channel. - */ - public Messenger getChannelMessenger(PeerGroupID redirection, String service, String serviceParam) { - return null; - } - - /** - * {@inheritDoc} - * - */ - @Override - public void sendMessage(Message msg, String service, String serviceParam, OutgoingMessageEventListener listener) { - if (messageWatcher == null) { - throw new UnsupportedOperationException("This channel was not configured to emulate this legacy method."); - } - - // Cleanup the message from any existing result prop since we're going to use select. - msg.setMessageProperty(Messenger.class, null); - - // Tell the watcher to select that message. - messageWatcher.watchMessage(listener, msg); - - sendMessageN(msg, service, serviceParam); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/EndpointAddress.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/EndpointAddress.java deleted file mode 100644 index e804f579..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/EndpointAddress.java +++ /dev/null @@ -1,637 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - -import net.jxta.id.ID; -import net.jxta.logging.Logging; - -import java.lang.ref.SoftReference; -import java.net.URI; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Describes a destination to which JXTA messages may be sent. This may be: - *

      - * - *

        - *
      • A Pipe
      • - *
      • A Peergroup (propagate)
      • - *
      • A Peer
      • - *
      • A Message Transport for a Peer
      • - *
      - *

      - * An Endpoint Address is a specialized interpretation of a URI. - * Wherever it makes sense you should use a URI in preference to an Endpoint - * Address. An Endpoint Address is composed of four components: a protocol - * (also called a scheme), a protocol address (also called an authority), an - * optional service name and optional service parameter. - *

      - * The Protocol

        - *
      • Describes the method of addressing used by the remainder of the - * endpoint address.
      • - *
      • Indicates how the address will be resolved, ie. who will resolve it.
      • - *
      • Corresponds to the "scheme" portion of a URI in W3C parlance. - *
      • May not contain the ":" character. - *
      - *

      - * The Protocol Address

        - *
      • Describes the destination entity of this address.
      • - *
      • Form is dependant upon the protocol being used.
      • - *
      • Corresponds to the "Authority" portion of a URI in W3C parlance. - *
      • May not contain the "/" character. - *
      - *

      - * The Service Name (optional)

        - *
      • Describes the service that is the destination. A service cannot be - * a protocol address because a service must have a location; a group or a - * specific peer.
      • - *
      • Form is dependant upon service intent. This is matched as a UTF8 - * string.
      • - *
      • May not contain the "/" character. - *
      - * - *

      The Service Parameter (optional)

        - *
      • Describes parameters for the service.
      • - *
      • Form is dependant upon service intent. This is matched as a UTF-8 - * string (if it is used for matching).
      • - *
      - * - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.endpoint.MessageTransport - * @see net.jxta.endpoint.Messenger - * @see net.jxta.pipe.PipeService - */ -public class EndpointAddress { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(EndpointAddress.class.getName()); - - /** - * If {@code true} then endpoint addresses based upon IDs are represented - * using the "jxta://" form. If false then they are presented using the - * "urn:jxta:" form. The two forms are meant to be logically equivalent. - */ - private final static boolean IDS_USE_JXTA_URL_FORM = true; - - /** - * The default protocol value for Endpoint Addresses based upon JXTA IDs. - */ - private final static String JXTA_ID_PROTOCOL = ID.URIEncodingName + ":" + ID.URNNamespace; - - /** - * if true then the address is a url, otherwise its a uri (likely a urn). - */ - private boolean hierarchical = true; - - /** - * Describes the method of addressing used by the remainder of the - * endpoint address. - */ - private String protocol = null; - - /** - * Describes the destination entity of this address. - */ - private String protocolAddress = null; - - /** - * Describes the service that is the destination. - */ - private String service = null; - - /** - * Describes parameters for the service. - */ - private String serviceParam = null; - - /** - * cached calculated hash code. - */ - private transient int cachedHashCode = 0; - - /** - * cached copy of string representation. - */ - private transient SoftReference cachedToString = null; - - /** - * Returns an unmodifiable clone of the provided EndpointAddress. - * - * @param address the address to be cloned. - * @return the unmodifiable address clone. - * @deprecated All EndpointAddresses are now unmodifiable so this method is - * no longer needed. - */ - @Deprecated - public static EndpointAddress unmodifiableEndpointAddress(EndpointAddress address) { - return address; - } - - /** - * Builds an Address from a string - * - * @param address the string representation of the address. - */ - public EndpointAddress(String address) { - parseURI(address); - } - - /** - * Create an EndpointAddress whose value is initialized from the provided - * URI. - * - * @param address the URI representation of the address. - */ - public EndpointAddress(URI address) { - this(address.toString()); - } - - /** - * Constructor which builds an endpoint address from a base address and - * replacement service and params - * - * @param base The EndpointAddress on which the new EndpointAddress will be based - * @param service The service name for the endpoint address or - * {@code null} if there is no service name. - * @param serviceParam The service parameter for the endpoint address or - * {@code null} if there is no parameter. - */ - public EndpointAddress(EndpointAddress base, String service, String serviceParam) { - setProtocolName(base.getProtocolName()); - setProtocolAddress(base.getProtocolAddress()); - setServiceName(service); - setServiceParameter(serviceParam); - } - - /** - * Constructor which builds an address the four standard constituent parts. - * - * @param protocol The addressing scheme to be used for the endpoint address. - * @param address The destination for the endpoint address. - * @param service The service name for the endpoint address or - * {@code null} if there is no service name. - * @param serviceParam The service parameter for the endpoint address or - * {@code null} if there is no parameter. - */ - public EndpointAddress(String protocol, String address, String service, String serviceParam) { - setProtocolName(protocol); - setProtocolAddress(address); - setServiceName(service); - setServiceParameter(serviceParam); - } - - /** - * Constructor which builds an address from a standard jxta id and a - * service and param. - * - * @param id the ID which will be the destination of the endpoint address. - * @param service The service name for the endpoint address or - * {@code null} if there is no service name. - * @param serviceParam The service parameter for the endpoint address or - * {@code null} if there is no parameter. - */ - public EndpointAddress(ID id, String service, String serviceParam) { - setProtocolName(JXTA_ID_PROTOCOL); - setProtocolAddress(id.getUniqueValue().toString()); - setServiceName(service); - setServiceParameter(serviceParam); - } - - /** - * {@inheritDoc} - * - * @deprecated EndpointAddress objects are immutable and never need to be - * cloned. - */ - @Override - @Deprecated - public EndpointAddress clone() { - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof EndpointAddress) { - EndpointAddress likeMe = (EndpointAddress) target; - - boolean result = (hierarchical == likeMe.hierarchical) && protocol.equalsIgnoreCase(likeMe.protocol) - && protocolAddress.equalsIgnoreCase(likeMe.protocolAddress) - && ((service != null) - ? ((likeMe.service != null) && service.equals(likeMe.service)) - : (likeMe.service == null)) - && ((serviceParam != null) - ? ((likeMe.serviceParam != null) && serviceParam.equals(likeMe.serviceParam)) - : (likeMe.serviceParam == null)); - - return result; - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - if (0 == cachedHashCode) { - int calcedHashCode = protocol.toLowerCase().hashCode(); - - calcedHashCode += protocolAddress.hashCode() * 5741; // a prime - calcedHashCode += ((service != null) ? service.hashCode() : 1) * 7177; // a prime - calcedHashCode += ((serviceParam != null) ? serviceParam.hashCode() : 1) * 6733; // a prime - - cachedHashCode = (0 == calcedHashCode) ? 1 : calcedHashCode; - } - - return cachedHashCode; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized String toString() { - String result; - - if (null != cachedToString) { - result = cachedToString.get(); - - if (null != result) { - return result; - } - } - - StringBuilder newResult = new StringBuilder(protocol.length() + protocolAddress.length() + 64); - - newResult.append(protocol); - - if (hierarchical) { - newResult.append("://"); - } else { - newResult.append(':'); - } - - newResult.append(protocolAddress); - - if (null != service) { - if (hierarchical) { - newResult.append('/'); - } else { - newResult.append('#'); - } - newResult.append(service); - - if (null != serviceParam) { - newResult.append('/'); - newResult.append(serviceParam); - } - } - - result = newResult.toString(); - - cachedToString = new SoftReference(result); - - return result; - } - - /** - * Return a URI which represents the endpoint address. - * - * @return a URI which represents the endpoint address. - */ - public URI toURI() { - return URI.create(toString()); - } - - /** - * Return a String that contains the name of the protocol - * contained in the EndpointAddress - * - * @return a String containing the protocol name - */ - public String getProtocolName() { - return protocol; - } - - /** - * Return a String that contains the protocol address contained - * in the EndpointAddress - * - * @return a String containing the protocol address - */ - public String getProtocolAddress() { - return protocolAddress; - } - - /** - * Return a String that contains the service name contained in - * the EndpointAddress - * - * @return a String containing the service name - */ - public String getServiceName() { - return service; - } - - /** - * Return a String that contains the service parameter contained - * in the EndpointAddress - * - * @return a String containing the protocol name - */ - public String getServiceParameter() { - return serviceParam; - } - - /** - * Set the protocol name. - * - * @param name String containing the name of the protocol - */ - private void setProtocolName(String name) { - if ((null == name) || (0 == name.length())) { - throw new IllegalArgumentException("name must be non-null and contain at least one character"); - } - - if (-1 != name.indexOf("/")) { - throw new IllegalArgumentException("name may not contain '/' character"); - } - - // XXX 20070207 bondolo We explicitly force all use of either "jxta" or "urn:jxta" to our prefered form. - if (IDS_USE_JXTA_URL_FORM) { - if (JXTA_ID_PROTOCOL.equals(name)) { - name = "jxta"; - } - } else { - if ("jxta".equals(name)) { - name = JXTA_ID_PROTOCOL; - } - } - - int colonAt = name.indexOf(':'); - - if (-1 == colonAt) { - hierarchical = true; - } else { - if (!"urn".equalsIgnoreCase(name.substring(0, colonAt))) { - throw new IllegalArgumentException("Only urn may contain colon"); - } - - if (colonAt == (name.length() - 1)) { - throw new IllegalArgumentException("empty urn namespace!"); - } - - hierarchical = false; - } - - protocol = name; - cachedToString = null; - } - - /** - * Set the protocol address. - * - * @param address String containing the peer address. - */ - private void setProtocolAddress(String address) { - if ((null == address) || (0 == address.length())) { - throw new IllegalArgumentException("address must be non-null and contain at least one character"); - } - - if (-1 != address.indexOf("/")) { - throw new IllegalArgumentException("address may not contain '/' character"); - } - - protocolAddress = address; - cachedToString = null; - } - - /** - * Set the service name. - * - * @param name String containing the name of the destination service - */ - private void setServiceName(String name) { - if (null != name) { - if (-1 != name.indexOf("/")) { - throw new IllegalArgumentException("service name may not contain '/' character"); - } - } - - service = name; - cachedToString = null; - } - - /** - * Set the service parameter - * - * @param param String containing the service parameter - */ - private void setServiceParameter(String param) { - serviceParam = param; - cachedToString = null; - } - - /** - * Parse any EndpointAddress from a URI - * - * @param addr endpoint address to parse - */ - private void parseURI(String addr) { - int index = addr.indexOf("://"); - - if (index == -1) { - parseURN(addr); - } else { - parseURL(addr); - } - } - - /** - * Parse an EndpointAddress from a URN - * - * @param addr endpoint address to parse - */ - private void parseURN(String addr) { - int protocolEnd = addr.indexOf(':'); - - if (-1 == protocolEnd) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Address is not a valid URI: " + addr); - } - throw new IllegalArgumentException("Address is not a valid URI: " + addr); - } - - if (!"urn".equalsIgnoreCase(addr.substring(0, protocolEnd))) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Address is unrecognized URI form: " + addr); - } - throw new IllegalArgumentException("Address is unrecognized URI form: " + addr); - } - - if ((addr.length() - 1) == protocolEnd) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Address URN does not have a namespace: " + addr); - } - throw new IllegalArgumentException("Address URN does not have a namespace: " + addr); - } - - // gather the namespace as well. - int namespaceEnd = addr.indexOf(':', protocolEnd + 1); - - if (-1 == namespaceEnd) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Address URN does not have a namespace: " + addr); - } - throw new IllegalArgumentException("Address URN does not have a namespace: " + addr); - } - - setProtocolName(addr.substring(0, namespaceEnd)); - - if ((addr.length() - 1) == namespaceEnd) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Address URN does not have a NSS portion: " + addr); - } - throw new IllegalArgumentException("Address URN does not have a NSS portion: " + addr); - } - - // check for service and param - int nssEnd = addr.indexOf('#', namespaceEnd + 1); - - if (-1 == nssEnd) { - setProtocolAddress(addr.substring(namespaceEnd + 1)); - } else { - setProtocolAddress(addr.substring(namespaceEnd + 1, nssEnd)); - - int serviceEnd = addr.indexOf('/', nssEnd + 1); - - if (-1 == serviceEnd) { - setServiceName(addr.substring(nssEnd + 1)); - } else { - setServiceName(addr.substring(nssEnd + 1, serviceEnd)); - - setServiceParameter(addr.substring(serviceEnd + 1)); - } - } - } - - /** - * Parse and EndpointAddress from a URL - * - * @param addr endpoint address to parse - */ - private void parseURL(String addr) { - String remainder; - - int index = addr.indexOf("://"); - - if (index == -1) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Address is not in absolute form: " + addr); - } - throw new IllegalArgumentException("Address is not in absolute form: " + addr); - } - - if (0 == index) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Protocol is missing: " + addr); - } - throw new IllegalArgumentException("Protocol is missing: " + addr); - } - - try { - setProtocolName(addr.substring(0, index)); - remainder = addr.substring(index + 3); - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Protocol address is missing: " + addr); - } - throw new IllegalArgumentException("Protocol address is missing: " + addr); - } - index = remainder.indexOf("/"); - if (index == -1) { - setProtocolAddress(remainder); - return; - } - - setProtocolAddress(remainder.substring(0, index)); - - remainder = remainder.substring(index + 1); - - index = remainder.indexOf("/"); - if (index == -1) { - setServiceName(remainder); - return; - } - - setServiceName(remainder.substring(0, index)); - - remainder = remainder.substring(index + 1); - - setServiceParameter(remainder); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/EndpointListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/EndpointListener.java deleted file mode 100644 index a61d3cc9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/EndpointListener.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -/** - * A listener for messages. The listener is invoked for each incoming message - * which is destined for this listener. Various services register - * - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.endpoint.EndpointAddress - * @see net.jxta.endpoint.Message - */ -public interface EndpointListener { - - /** - * This method is invoked by the EndpointService for each incoming message - * which is addressed to this listener. - * - * @param message Incoming message - * @param srcAddr Endpoint Address of the source of the message. - * @param dstAddr Endpoint Address of the destination of the message. - */ - public void processIncomingMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/EndpointService.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/EndpointService.java deleted file mode 100644 index 27a8bf3c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/EndpointService.java +++ /dev/null @@ -1,552 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -import net.jxta.peergroup.PeerGroup; -import net.jxta.service.Service; - -import java.io.IOException; -import java.util.Iterator; - - -/** - * The EndpointService provides the API for sending and receiving messages - * between peers. In general, applications and services use the - * {@link net.jxta.pipe.PipeService}, or {@link net.jxta.socket.JxtaSocket} - * rather than using this API directly. - */ -public interface EndpointService extends Service, EndpointListener { - - /** - * Low Priority Messenger Event Listener. - */ - public static final int LowPrecedence = 0; - - /** - * Medium Priority Messenger Event Listener. - */ - public static final int MediumPrecedence = 1; - - /** - * High Priority Messenger Event Listener. - */ - public static final int HighPrecedence = 2; - - /** - * Returns the group to which this EndpointService is attached. - * - * @return the group. - */ - public PeerGroup getGroup(); - - /** - * Returns a messenger to the specified destination. - *

      - * The canonical messenger is shared between all channels who's - * destination contain the same protocol name and protocol address, in all - * groups that have access to the same transport. The ChannelMessenger - * returned is configured to send messages to the specified service name and - * service param when these are not specified at the time of sending. - *

      - * The channel will also ensure delivery to this EndpointService's group - * on arrival. The channel is not shared with any other module. That is, - * each endpoint service interface object (as returned by {@link - * net.jxta.peergroup.PeerGroup#getEndpointService()}) will return a - * different channel messenger for the same destination. However, there is - * no guarantee that two invocations of the same endpoint service interface - * object for the same destination will return different channel objects. - * Notably, if the result of a previous invocation is still strongly - * referenced and in a {@link Messenger#USABLE} state, then that is what - * this method will return. - *

      - * This method returns immediately. The messenger is not necessarily - * resolved (the required underlying connection established, for example), - * and it might never resolve at all. Changes in the state of a messenger - * may monitored with {@link Messenger#getState} and - * {@link Messenger#waitState}. One may monitor multiple - * {@link Messenger messengers} (and {@link Message Messages}) at a time by - * using a {@link net.jxta.util.SimpleSelector}. One may also arrange to - * have a listener invoked when resolution is complete by using - * {@link ListenerAdaptor}. - *

      - * The {@code hint} is interpreted by the transport. The only transport - * known to consider hints is the endpoint router, and the hint is a route. - * As a result, if addr is in the form: jxta://uniqueID, then hint may be a - * RouteAdvertisement. If that route is valid the router will add it to - * it's cache of route and may then use it to successfully create a messenger - * to the given destination. There is no guarantee at this time that the - * route will end up being the one specified, nor that this route will be - * used only for this messenger (likely the opposite), nor that it will - * remain in use in the future, nor that it will be used at all. However, if - * there is no other route, and if the specified route is valid, it will be - * used rather than seeking an alternative. - * - * @param addr The complete destination address. - * @param hint A optional hint to be supplied to whichever transport ends-up - * making the real messenger. May be {@code null}, when no hint applies. - * @return A messenger for the specified destination address or {@code null} - * if the address is not handled by any of the available Message Transports. - * The messenger, if returned, is not necessarily functional, nor resolved. - * @see net.jxta.endpoint.ChannelMessenger - */ - public Messenger getMessengerImmediate(EndpointAddress addr, Object hint); - - /** - * Returns a messenger for the specified destination address. - *

      - * Behaves like {@link #getMessengerImmediate(EndpointAddress,Object)}, - * except that the invoker is blocked until the Messenger either resolves or - * it is determined that no usable messenger can be created. - * - * @param addr The destination address. - * @param hint A optional hint to be supplied to whichever transport ends-up - * making the real messenger. May be {@code null}, when no hint applies. - * @return A messenger for the specified destination address or {@code null} - * if the destination address is not reachable. - */ - public Messenger getMessenger(EndpointAddress addr, Object hint); - - /** - * Creates and maps a canonical messenger to the specified destination. - *

      - * Behaves like {@link #getMessengerImmediate(EndpointAddress,Object)} - * except that it returns a canonical messenger. - *

      - * The messenger is said to be canonical, because there is only one such - * live object for any given destination address. The term "live", - * here means that the messenger is not in any of the - * {@link Messenger#TERMINAL} states as defined by {@link MessengerState}. - * Therefore, for a given destination there may be any number of messengers - * in a {@link Messenger#TERMINAL} state, but at most one in any other state. - * As long as such an object exists, all calls to - * {@code getCanonicalMessenger()} for the same address return this very - * object. - *

      - * When first created, a canonical messenger is usually in the - * {@link Messenger#UNRESOLVED} state. It becomes resolved by obtaining an - * actual transport messenger to the destination upon the first attempt at - * using it or when first forced to attempt resolution. Should resolution - * fail at that point, it becomes {@link Messenger#UNRESOLVABLE}. Otherwise, - * subsequent, failures are repaired automatically by obtaining a new - * transport messenger when needed. If a failure cannot be repaired, the - * messenger becomes {@link Messenger#BROKEN}. - *

      - * {@code getCanonicalMessenger()} is a recursive function. - * Exploration of the parent endpoint is done automatically. - *

      - * Note 1: This method is the most fundamental messenger - * instantiation method. It creates a different messenger for each variant - * of destination address passed to the constructor. In general invokers - * should use plain addresses; stripped of any service-specific destination. - *

      - * Note 2: The messengers that this method returns, are not - * generally meant to be used directly. They provide a single queue for all - * invokers, and do not perform group redirection and only support only a - * subset of the {@code sendMessage()} methods. One must get a properly - * configured channel in order to send messages. - *

      - * If one of the other {@code getMessenger()} methods fits the - * application needs, it should be preferred. - * - * @param addr The destination address. It is recommended, though not - * mandatory, that the address be stripped of its service name and service - * param elements. - * @param hint An object, of a type specific to the protocol of the address, - * that may be provide additional information to the transport in - * establishing the connection. Typically but not necessarily, this is a - * route advertisement. If the transport cannot use the hint, or if it is - * {@code null}, it will be ignored. - * @return A Canonical messenger that obtains transport messengers to the - * specified address, from LOCAL transports. Returns {@code null} if no - * local transport handles this type address. - */ - public Messenger getCanonicalMessenger(EndpointAddress addr, Object hint); - - /** - * Removes the specified listener. - * - * @param listener The listener that would have been called. - * @param priority Priority set from which to remove this listener. - * @return true if the listener was removed, otherwise false. - */ - public boolean removeMessengerEventListener(MessengerEventListener listener, int priority); - - /** - * Adds the specified listener for all messenger creation. - * - * @param listener The listener that will be called. - * @param priority Order of precedence requested (from 0 to 2). 2 has the - * highest precedence. Listeners are called in decreasing order of - * precedence. Listeners with equal precedence are called in an unspecified - * order. There cannot be more than one listener object for a given - * precedence. Redundant calls have no effect. - * @return true if the listener was added, otherwise false. - */ - public boolean addMessengerEventListener(MessengerEventListener listener, int priority); - - /** - * Propagates (broadcasts) a message via all available Message Transports. - * Each Message Transport that implements propagation will send the message - * using it's broadcast functionality to a configured broadcast address. Any - * peers in the same network scope listening on that broadcast address will - * receive the propagated message. - *

      - * The message will be sent using the default TTL value (which is - * unspecified). - * - * @param message The message to be propagated. The message will not be - * modified by this method. - * @param serviceName The name of the destination service. - * @param serviceParam An optional parameter for the destination service or - * {@code null}. - * @throws IOException Thrown if the message could not be propagated. - */ - public void propagate(Message message, String serviceName, String serviceParam) throws IOException; - - /** - * Propagates (broadcasts) a message via all available Message Transports. - * Each Message Transport that implements propagation will send the message - * using it's broadcast functionality to a configured broadcast address. Any - * peers in the same network scope listening on that broadcast address will - * receive the propagated message. - * - * @param message The message to be propagated. The message will not be - * modified by this method. - * @param serviceName The name of the destination service. - * @param serviceParam An optional parameter for the destination service or - * {@code null}. - * @param initialTTL The requested initial TTL for this message. The actual - * TTL value used may be lower than this value but will never be higher. - */ - public void propagate(Message message, String serviceName, String serviceParam, int initialTTL); - - /** - * Verifies that the given address can be reached. The method, and accuracy - * of the verification depends upon each Message Transport. In some cases - * the address may be contacted to determine connectivity but this is not - * guaranteed. - * - * @param addr is the Endpoint Address to ping. - * @return {@code true} if the address can be reached otherwise {@code false}. - * @deprecated The cost of performing this operation is generally the same - * as getting a Messenger for the destination. Using {@code getMessenger()} - * is a better approach because the resulting Messenger is generally needed - * soon after ping. - */ - @Deprecated - public boolean ping(EndpointAddress addr); - - /** - * Add a listener for the specified address. - *

      - * A single registered listener will be called for incoming messages - * when (in order of preference) :

        - *
      1. The service name and service parameter match exactly to the - * service name and service parameter specified in the destination - * address of the message.
      2. - *

        - *

      3. The service name matches exactly the service name from the - * message destination address and service parameter is {@code null}. - *
      4. - *
      - * - * @param listener The listener which will be called when messages are - * received for the registered destination. - * @param serviceName The name of the service destination which will be - * matched against incoming message destination endpoint addresses. - * @param serviceParam An optional service parameter value which will be - * matched against destination endpoint addresses. May be null. - * @return true if the listener was registered, otherwise false. - */ - public boolean addIncomingMessageListener(EndpointListener listener, String serviceName, String serviceParam); - - /** - * Get the listener for the specified address. - * - * @param serviceName The service name to which the listener is registered. - * @param serviceParam The service parameter to which the listener is - * registered. May be {@code null}. - * @return The currently registered listener or {@code null} if there is no - * listener for the specified name and parameter. - */ - public EndpointListener getIncomingMessageListener(String serviceName, String serviceParam); - - /** - * Remove the listener for the specified address. - * - * @param serviceName The service name to which the listener is registered. - * @param serviceParam The service parameter to which the listener is - * registered. May be {@code null}. - * @return The listener which was removed or {@code null} if there was - * no listener for the specified name and parameter. - */ - public EndpointListener removeIncomingMessageListener(String serviceName, String serviceParam); - - /** - * Registers a message filter listener. Each message will be tested against - * the list of filters as part of its sending or receiving. - *

      - * The listener is invoked for a message when: - *

        - *
      • The message contains a message element which matches exactly the - * values specified by namespace and name.
      • - * - *
      • The message contains a message element who's namespace value - * matches exactly the specified namespace value and the specified name is - * {@code null}.
      • - * - *
      • The message contains a message element who's names value matches - * exactly the specified name value and the specified namespace is - * {@code null}.
      • - * - *
      • The specified name value and the specified namespace are both - * {@code null}.
      • - *
      - * - * @param listener The filter which will be called. - * @param namespace Only messages containing elements of this namespace - * which also match the 'name' parameter will be processed. {@code null} - * may be use to specify all namespaces. - * @param name only messages containing elements of this name which also - * match the 'namespace' parameter will be processed. {@code null} may be - * use to specify all names. - */ - public void addIncomingMessageFilterListener(MessageFilterListener listener, String namespace, String name); - - /** - * Registers a message filter listener. Each message will be tested against - * the list of filters as part of its sending or receiving. - *

      - * The listener is invoked for a message when: - *

        - *
      • The message contains a message element which matches exactly the - * values specified by namespace and name.
      • - * - *
      • The message contains a message element who's namespace value - * matches exactly the specified namespace value and the specified name is - * {@code null}.
      • - * - *
      • The message contains a message element who's names value matches - * exactly the specified name value and the specified namespace is - * {@code null}.
      • - * - *
      • The specified name value and the specified namespace are both - * {@code null}.
      • - *
      - * - * @param listener The filter which will be called. - * @param namespace Only messages containing elements of this namespace - * which also match the 'name' parameter will be processed. {@code null} - * may be used to specify all namespaces. - * @param name only messages containing elements of this name which also - * match the 'namespace' parameter will be processed. {@code null} may be - * use to specify all names. - */ - public void addOutgoingMessageFilterListener(MessageFilterListener listener, String namespace, String name); - - /** - * Removes the given listener previously registered under the given element - * name - * - * @param listener the listener to remove - * @param namespace the name space - * @param name the name - * @return the removed listener - */ - public MessageFilterListener removeIncomingMessageFilterListener(MessageFilterListener listener, String namespace, String name); - - /** - * Removes the given listener previously registered under the given element - * name. - * - * @param listener the listener to remove - * @param namespace the name space - * @param name the name - * @return the removed listener - */ - public MessageFilterListener removeOutgoingMessageFilterListener(MessageFilterListener listener, String namespace, String name); - - /** - * Delivers the provided message to the correct listener as specified by - * the message's destination address. - *

      - * Two additional common message elements are optionally used by Message - * Transports in conjunction with the Endpoint Service. Message Transports - * may typically provide received messages to the Endpoint Service - * containing these elements and the Endpoint service will dispatch the - * messages based upon their content. Message Transports may use alternate - * mechanisms for determining message source and destination addresses and - * need not use these elements. - *

      - * The {@code jxta:EndpointSourceAddress} Message Element contains an - * Endpoint Address for the source of this message. The source address has a - * variety of meanings based upon the usage of the underlying Message - * Transport. For low level transports such as TCP or HTTP the source - * address is the return address of the peer from which the message was - * received, ie. the hop address. For higher level Message Transports such - * as the Endpoint Router Transport or the TLS transport the source address - * is the virtual Endpoint Address of the peer which originated the message - * regardless of any intervening hops the message may have made. - *

      - * The {@code jxta:EndpointDestinationAddress} Message Element contains an - * Endpoint Address which will be used by the Endpoint Service to dispatch a - * received message to the recipient specified by the service name and - * service parameter. The protocol address is also provided to the recipient - * service and can be used in some protocols for determining how the message - * was received. For example a service may wish to handle messages which - * were sent directly differently than messages which were sent via - * propagation. - * - * @param msg The message to be delivered. - * @deprecated Please convert your code to use the - * {@link EndpointListener#processIncomingMessage(Message,EndpointAddress,EndpointAddress)} - * method instead. The addressing method used by demux() was never part of - * the formal JXTA protocol specification but was a defacto part because - * demux() depended upon it. - */ - @Deprecated - public void demux(Message msg); - - /** - * Adds the specified MessageTransport to this endpoint. A MessageTransport - * may only be added if there are no other equivalent MessageTransports - * available (as determined by {@link Object#equals(Object) equals()}). - *

      - * The MessageTransport becomes usable by the endpoint service to send - * unicast messages and optionally propagation and ping messages if it is a - * {@link net.jxta.endpoint.MessageSender}. The endpoint service becomes - * usable by this MessageTransport to handle incoming messages if it is a - * {@link MessageReceiver}. - * - * @param transport the MessageTransport to be installed. - * @return A messenger event listener to invoke when incoming messengers are - * created or {@code null} if the MessageTransport was not installed. - */ - public MessengerEventListener addMessageTransport(MessageTransport transport); - - /** - * Removes the given MessageTransport protocol from this endpoint service. - *

      - * Transports remove themselves from the list when stopped. This method - * is normally only called from the stoppApp method of the transport. To - * cleanly remove a transport, call the transport's - * {@link net.jxta.platform.Module#stopApp() stopApp()}and allow it to call - * this method. - * - * @param transpt the MessageTransport to be removed. - * @return {@code true} if the Message Transport was removed, otherwise - * {@code false}. - */ - public boolean removeMessageTransport(MessageTransport transpt); - - /** - * Get an iterator of the MessageTransports available to this - * EndpointService. - * - * @return the iterator of all message transports. - */ - public Iterator getAllMessageTransports(); - - /** - * Get a Message Transport by protocol name. - * - * @param name The protocol name of the MessageTransport. - * @return The Message Transport for the specified protocol name or - * {@code null} if there is no matching Message Transport - */ - public MessageTransport getMessageTransport(String name); - - /** - * Returns a Messenger that may be used to send messages via this endpoint - * to the specified destination. - * - * @param addr the destination address. - * @return The messenger or {@code null} is returned if the destination - * address is not reachable. - */ - public Messenger getMessenger(EndpointAddress addr); - - /** - * Asynchronously acquire a messenger for the specified address. The - * listener will be called when the messenger has been constructed. - * - * @param listener the listener to call when the messenger is ready. - * @param addr the destination for the messenger. - * @param hint the messenger hint, if any, otherwise null. - * @return {@code true} if the messenger is queued for construction - * otherwise {@code false}. - * @deprecated This method is being phased out. Prefer one of the other - * non-blocking variants. If a listener style paradigm is required, use - * {@link ListenerAdaptor} which emulates this functionality. - */ - @Deprecated - public boolean getMessenger(MessengerEventListener listener, EndpointAddress addr, Object hint); - - /** - * Returns a Direct Messenger that may be used to send messages via this endpoint to the specified destination. - *

      - * Direct messengers are non self destructive, they must be explicilty closed. - * - * @param addr the destination address. - * @param hint the messenger hint, if any, otherwise null. - * @param exclusive if true avoids caching the messenger - * @return The messenger or {@code null} is returned if the destination address is not reachable. - * @throws IllegalArgumentException if hint is not of RouteAdvertisement, or PeerAdvertisement type. - */ - public Messenger getDirectMessenger(EndpointAddress addr, Object hint, boolean exclusive); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/InputStreamMessageElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/InputStreamMessageElement.java deleted file mode 100644 index 16b30edc..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/InputStreamMessageElement.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -import net.jxta.document.MimeMediaType; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.SequenceInputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.zip.CRC32; -import java.util.zip.Checksum; - - -/** - * A Message Element using {@link java.io.InputStream} as the source for the - * element data. This implementation copies all of the data from the stream at - * the time of creation. - *

      - * InputStreamMessageElement is not as efficient as other message element types - * and should only be used when an input stream is the only available source for - * the element data. - */ -public class InputStreamMessageElement extends MessageElement { - - /** - * The bytes of this element. - */ - protected final List databytes; - - /** - * The length of the data. - */ - protected final long length; - - /** - * Cached Hash Code - */ - protected transient int cachedHashCode = 0; - - /** - * Create a new MessageElement. This constructor copies the data as needed - * and closes the stream upon completion. - * - * @param name Name of the MessageElement. May be the empty string ("") if - * the MessageElement is not named. - * @param type Type of the MessageElement. null is the same as specifying - * the type "Application/Octet-stream". - * @param in the stream containing the body of the MessageElement. The - * stream will be closed by the MessageElement. - * @param sig optional message digest/digital signature element or null if - * no signature is desired. - * @throws IOException If there is a problem reading from the source stream. - */ - public InputStreamMessageElement(String name, MimeMediaType type, InputStream in, MessageElement sig) throws IOException { - this(name, type, in, Long.MAX_VALUE, sig); - } - - /** - * Create a new Message Element. - * - * @param name Name of the MessageElement. May be the empty string ("") if - * the MessageElement is not named. - * @param type Type of the MessageElement. null is the same as specifying - * the type "Application/Octet-stream". - * @param in the stream containing the body of the MessageElement. - * The stream will NOT be closed unless EOF is unexpectedly reached. - * @param len The size of the Element will be limited to len bytes - * from the stream. If you are using the stream interface and know - * the size of the stream, specifying it here improves performance - * and space efficiency a lot. The stream must contain at least - * len bytes. - * @param sig optional message digest/digital signature element or null if - * no signature is desired. - * @throws IOException if there is a problem reading from the source stream - */ - public InputStreamMessageElement(String name, MimeMediaType type, InputStream in, long len, MessageElement sig) throws IOException { - super(name, type, sig); - - if ((len < 0)) { - throw new IllegalArgumentException("len must be >= 0"); - } - - // copy the data from the stream - databytes = CopyToDataBytes(in, len); - - // calculate the length - long buffersSum = 0; - for (byte[] aBuffer : databytes) { - buffersSum += aBuffer.length; - } - - length = buffersSum; - - // fail if the length is not as promised. - if ((len != Long.MAX_VALUE) && (len != length)) { - throw new IllegalArgumentException("Stream was shorter than promised length."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof MessageElement) { - if (!super.equals(target)) { - return false; - } - - if (target instanceof InputStreamMessageElement) { - // have to do a slow stream comparison. - // XXX 20020615 bondolo@jxta.org the performance of this could be much improved. - - MessageElement likeMe = (MessageElement) target; - - try { - InputStream myStream = getStream(); - InputStream itsStream = likeMe.getStream(); - - int mine; - int its; - - do { - mine = myStream.read(); - its = itsStream.read(); - - if (mine != its) { - return false; - } // content didn't match - - } while ((-1 != mine) && (-1 != its)); - - return ((-1 == mine) && (-1 == its)); // end at the same time? - } catch (IOException fatal) { - throw new IllegalStateException("MessageElements could not be compared." + fatal); - } - } - } - - return false; // not a new message element - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int hashCode() { - if (0 == cachedHashCode) { - Checksum crc = new CRC32(); - - for (byte[] aBuffer : databytes) { - crc.update(aBuffer, 0, aBuffer.length); - } - - int result = super.hashCode() + (int) crc.getValue() * 6037; // a prime - - cachedHashCode = 0 != result ? result : 1; - } - - return cachedHashCode; - } - - /** - * {@inheritDoc} - */ - @Override - public long getByteLength() { - return length; - } - - /** - * {@inheritDoc} - */ - public InputStream getStream() throws IOException { - List buffers = new ArrayList(); - - for (byte[] aBuffer : databytes) { - buffers.add(new ByteArrayInputStream(aBuffer)); - } - - return new SequenceInputStream(Collections.enumeration(buffers)); - } - - /** - * {@inheritDoc} - */ - @Override - public void sendToStream(OutputStream sendTo) throws IOException { - for (byte[] aBuffer : databytes) { - sendTo.write(aBuffer); - } - } - - /** - * Copy data from a stream with best possible efficiency. Unfortunately, - * this still results in a lot of copying since we have often have no - * fore-knowledge of the length of the stream. - * - * @param in the stream to copy from - * @param limit the maximum number of bytes to copy from the stream. - * Long.LONG_MAX will read until EOF. - * @return A list of buffers. - * @throws IOException if there is a problem reading from the stream. - */ - protected List CopyToDataBytes(InputStream in, long limit) throws IOException { - final long INITIAL_INTERMEDIATE_BUFFERSIZE = 6; - final long MAXIMUM_INTERMEDIATE_BUFFERSIZE = 18; - - List buffs = new ArrayList(); - boolean atEOF = false; - long read = 0; - long currentIntermediateBufferSize = INITIAL_INTERMEDIATE_BUFFERSIZE; - - // build a list of buffers containing all the element data. - do { - long readRequest = (limit - read); - - if (Long.MAX_VALUE == limit) { - readRequest = Math.min(readRequest, (1L << currentIntermediateBufferSize)); - } - readRequest = Math.min(readRequest, Integer.MAX_VALUE); // limited by size of arrays which are Integer indexed. - - byte[] nextBuffer = new byte[(int) readRequest]; - int offsetInThisBuffer = 0; - - // fully read the buffer if we can. - do { - int readLength = in.read(nextBuffer, offsetInThisBuffer, nextBuffer.length - offsetInThisBuffer); - - if (readLength == -1) { - atEOF = true; - break; - } - - offsetInThisBuffer += readLength; - } while (offsetInThisBuffer < nextBuffer.length); - - // handle the final buffer. - if (atEOF) { - byte[] anotherBuffer = new byte[offsetInThisBuffer]; - - System.arraycopy(nextBuffer, 0, anotherBuffer, 0, offsetInThisBuffer); - nextBuffer = anotherBuffer; - } - - read += nextBuffer.length; - buffs.add(nextBuffer); - - if (currentIntermediateBufferSize < MAXIMUM_INTERMEDIATE_BUFFERSIZE) { - currentIntermediateBufferSize++; - } - } while (!atEOF && (read < limit)); - - // we are done, close if we are at EOF. - if (atEOF) { - in.close(); - in = null; - } - return buffs; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ListenerAdaptor.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ListenerAdaptor.java deleted file mode 100644 index 4ebc94e0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ListenerAdaptor.java +++ /dev/null @@ -1,481 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - -import net.jxta.logging.Logging; -import net.jxta.util.SimpleSelectable; -import net.jxta.util.SimpleSelectable.IdentityReference; -import net.jxta.util.SimpleSelector; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.Executor; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * The legacy getMessenger asynchronous API never returns any object to the invoker until a messenger could actually be made, - * allowing the application to supply a listener to be invoked when the operation completes. The legacy Messenger API also - * provides a method to send messages that calls a listener to report the outcome of the operation.

      - *

      - * The model has changed, so that an asynchronous messenger is made unresolved and returned immediately to the invoker, which can - * then request opening or even just send a message to force the opening. Subsequently, the messenger can be used as a control - * block to monitor progress with {@link Messenger#register} and {@link Messenger#waitState}.

      - *

      - * Likewise, the outcome of sending a message is a property of that message. Messages can be selected to monitor property changes - * with {@link Message#register} and {@link net.jxta.endpoint.Message#getMessageProperty(Object)} (the outcome property key is - * Messenger.class). - *

      - * This class here provides the legacy listener model on top of the new model for applications that prefer listeners. This class - * is used internally to emulate the legacy listener behaviour, so that applications do not need to be adapted.

      - *

      - * Note: one instance of this class gets instantiated by each EndpointService interface. However, it does not start using any - * resources until it first gets used.

      - */ -public class ListenerAdaptor implements Runnable { - - // FIXME - jice 20040413: Eventhough it is not as critical as it used to be we should get rid of old, never resolved entries. - // Attempts are supposed to always fail or succeed rather soon. Here, we trust transports in that matter. Is it safe ? - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(ListenerAdaptor.class.getName()); - - /** - * The in progress messages. - */ - private final Map inprogress = new HashMap(32); - - /** - * The thread that does the work. - */ - private Thread bgThread = null; - - /** - * The selector that we use to watch messengers progress. - */ - private final SimpleSelector selector = new SimpleSelector(); - - /** - * Have we been shutdown? - */ - private volatile boolean shutdown = false; - - /** - * The exceutor service. - */ - private final Executor executor; - - /** - * The ThreadGroup in which this adaptor will run. - */ - private final ThreadGroup threadGroup; - - /** - * Standard Constructor - * - * @param threadGroup The ThreadGroup in which this adaptor will run. - */ - public ListenerAdaptor(ThreadGroup threadGroup) { - this(threadGroup, null); - } - /** - * Creates a ListenerAdaptor with a threadpool for notification callback. - * - * @param threadGroup The ThreadGroup in which this adaptor will run. - * @param executor the excutor to use for notification callback - */ - public ListenerAdaptor(ThreadGroup threadGroup, Executor executor) { - this.executor = executor; - this.threadGroup = threadGroup; - } - - /** - * Cannot be re-started. Do not call once shutdown. - */ - private synchronized void init() { - assert !shutdown; - - if (bgThread != null) { - return; - } - - bgThread = new Thread(threadGroup, this, "Listener Adaptor"); - bgThread.setDaemon(true); - bgThread.start(); - } - - public synchronized void shutdown() { - shutdown = true; - - // Stop the thread if it was ever created. - Thread bg = bgThread; - if (bg != null) { - bg.interrupt(); - } - } - - /** - * Stop watching a given selectable. - * - * @param ts the selectable - */ - private void forgetSelectable(SimpleSelectable ts) { - // Either way, we're done with this one. - ts.unregister(selector); - - synchronized (this) { - inprogress.remove(ts.getIdentityReference()); - } - } - - /** - * Select the given message and invoke the given listener when the message sending is complete. - * - * @param listener The listener to invoke. If null the resolution will take place, but obviously no listener will be invoked. - * @param message The message being sent. - * @return true if the message was registered successfully or the listener is null. If true it is guaranteed that the listener - * will be invoked unless null. If false, it is guaranteed that the listener will not be invoked. - */ - public boolean watchMessage(OutgoingMessageEventListener listener, Message message) { - synchronized (this) { - if (shutdown) { - return false; - } - - if (listener == null) { - // We're done, then. The invoker does not really care. - return true; - } - - // Init if needed. - init(); - - // First we must ensure that if the state changes we'll get to handle it. - MessageListenerContainer allListeners = (MessageListenerContainer) inprogress.get(message.getIdentityReference()); - - if (allListeners == null) { - allListeners = new MessageListenerContainer(); - inprogress.put(message.getIdentityReference(), allListeners); - } - allListeners.add(listener); - } - - // When we do that, the selector gets notified. Therefore always check the initial state automatically. If the - // selectable is already done with, the listener will be called by the selector's handler. - message.register(selector); - - return true; - } - - /** - * Select the given messenger and invoke the given listener when the messenger is resolved. - * - * @param listener The listener to invoke. If null the resolution will take place, but obviously no listener will be invoked. - * @param messenger The messenger being resolved. - * @return true if the messenger was registered successfully or the listener is null. If true it is guaranteed that the listener - * will be invoked unless null. If false, it is guaranteed that the listener will not be invoked. - */ - public boolean watchMessenger(MessengerEventListener listener, Messenger messenger) { - synchronized (this) { - - if (shutdown) { - return false; - } - - if (listener == null) { - // We're done, then. The invoker does not really care. - return true; - } - - // Init if needed. - init(); - - // First we must ensure that if the state changes we'll get to handle it. - MessengerListenerContainer allListeners = (MessengerListenerContainer) inprogress.get(messenger.getIdentityReference()); - - if (allListeners == null) { - // Use ArrayList. The code is optimized for that. - allListeners = new MessengerListenerContainer(); - inprogress.put(messenger.getIdentityReference(), allListeners); - } - allListeners.add(listener); - } - - // When we do that, the selector get notified. Therefore we will always check the initial state automatically. If the - // selectable is already done with, the listener will be called by the selector's handler. - messenger.register(selector); - - return true; - } - - /* - * Any sort of listener type. - */ - static abstract class ListenerContainer extends ArrayList { - - public ListenerContainer() { - super(1); - } - - protected abstract void giveUp(S what, Throwable how); - - protected abstract void process(S what); - } - - - /** - * For messages - */ - @SuppressWarnings("serial") - class MessageListenerContainer extends ListenerContainer { - - private void messageDone(Message message, OutgoingMessageEvent event) { - // Note: synchronization is externally provided. When this method is invoked, this - // object has already been removed from the map, so the list of listener cannot change. - - if (event == OutgoingMessageEvent.SUCCESS) { - // Replace it with a msg-specific one. - event = new OutgoingMessageEvent(message, null); - - for (OutgoingMessageEventListener eachListener : this) { - try { - eachListener.messageSendSucceeded(event); - } catch (Throwable any) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught throwable from listener", any); - } - } - } - } else { - if (event == OutgoingMessageEvent.OVERFLOW) { - // Replace it with a msg-specific one. - event = new OutgoingMessageEvent(message, null); - } - - for (OutgoingMessageEventListener eachListener : this) { - try { - eachListener.messageSendFailed(event); - } catch (Throwable any) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught throwable in listener", any); - } - } - } - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void process(Message message) { - OutgoingMessageEvent event = (OutgoingMessageEvent) message.getMessageProperty(Messenger.class); - - if (event == null) { - return; - } - - // Remove this container-selectable binding - forgetSelectable(message); - - // Invoke app listeners - messageDone(message, event); - } - - /** - * {@inheritDoc} - */ - @Override - protected void giveUp(Message m, Throwable how) { - messageDone(m, new OutgoingMessageEvent(m, how)); - } - } - - /** - * For messengers - */ - @SuppressWarnings("serial") - class MessengerListenerContainer extends ListenerContainer { - - private void messengerDone(Messenger messenger) { - - // Note: synchronization is externally provided. When this method is invoked, this - // object has already been removed from the map, so the list of listener cannot change. - - MessengerEvent event = new MessengerEvent(ListenerAdaptor.this, messenger, null); - - for (MessengerEventListener eachListener : this) { - try { - eachListener.messengerReady(event); - } catch (Throwable any) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught throwable in listener", any); - } - } - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void process(Messenger messenger) { - if ((messenger.getState() & (Messenger.RESOLVED | Messenger.TERMINAL)) == 0) { - return; - } - - // Remove this container-selectable binding - forgetSelectable(messenger); - - if ((messenger.getState() & Messenger.USABLE) == 0) { - messenger = null; - } - - // Invoke app listeners - messengerDone(messenger); - } - - /** - * {@inheritDoc} - */ - @Override - protected void giveUp(Messenger m, Throwable how) { - messengerDone(null); - } - } - - /** - * {@inheritDoc} - */ - public void run() { - try { - while (!shutdown) { - try { - Collection changed = selector.select(); - for (SimpleSelectable simpleSelectable : changed) { - ListenerContainer listeners; - synchronized (this) { - listeners = inprogress.get(simpleSelectable.getIdentityReference()); - } - if (listeners == null) { - simpleSelectable.unregister(selector); - continue; - } - if (executor == null) { - listeners.process(simpleSelectable); - } else { - executor.execute(new ListenerProcessor(listeners, simpleSelectable)); - } - } - } catch (InterruptedException ie) { - Thread.interrupted(); - } - } - } catch (Throwable anyOther) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in background thread", anyOther); - } - - // There won't be any other thread. This thing is dead if that - // happens. And it really shouldn't. - synchronized (this) { - shutdown = true; - } - } finally { - try { - // It's only us now. Stopped is true. - IOException failed = new IOException("Endpoint interface terminated"); - for (Map.Entry entry : inprogress.entrySet()) { - SimpleSelectable simpleSelectable = entry.getKey().getObject(); - ListenerContainer listeners = entry.getValue(); - simpleSelectable.unregister(selector); - - if (listeners != null) { - listeners.giveUp(simpleSelectable, failed); - } - } - inprogress.clear(); - } catch (Throwable anyOther) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable while shutting down background thread", anyOther); - } - } - bgThread = null; - } - } - - /** - * A small class for processing individual messages. - */ - private class ListenerProcessor implements Runnable { - - private SimpleSelectable simpleSelectable; - private ListenerContainer listeners; - ListenerProcessor(ListenerContainer listeners, SimpleSelectable simpleSelectable) { - this.listeners = listeners; - this.simpleSelectable = simpleSelectable; - } - - public void run() { - listeners.process(simpleSelectable); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/Message.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/Message.java deleted file mode 100644 index 134699a8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/Message.java +++ /dev/null @@ -1,1444 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.PrintWriter; -import java.io.Serializable; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; - -import java.io.IOException; -import java.util.ConcurrentModificationException; -import java.util.NoSuchElementException; -import java.util.concurrent.atomic.AtomicInteger; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.MimeMediaType; -import net.jxta.util.AbstractSimpleSelectable; -import net.jxta.util.SimpleSelectable; - -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.id.UUID.UUIDFactory; - -/** - * Messages are abstract containers for protocol messages within JXTA. Services - * and applications are expected to use Messages as the basis for any protocols - * implemented within JXTA. Messages are exchanged through the - * {@link net.jxta.endpoint.EndpointService} or - * {@link net.jxta.pipe.PipeService}. - *

      - * A Message is composed of an ordered list of zero or more - * {@link net.jxta.endpoint.MessageElement MessageElements}. Each - * {@link net.jxta.endpoint.MessageElement} is associated with a namespace at - * the time it is added to the message. Duplicate - * {@link net.jxta.endpoint.MessageElement MessageElements} are permitted. - *

      - * Messages are not synchronized. All of the iterators returned by this - * implementation are "fail-fast". Concurrent modification of messages from - * multiple threads will produce unexpected results and - * {@code ConcurrentModificationException}. - * - * @see net.jxta.endpoint.MessageElement - * @see net.jxta.endpoint.EndpointAddress - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.pipe.InputPipe - * @see net.jxta.pipe.OutputPipe - * @see net.jxta.pipe.PipeService - */ -public class Message extends AbstractSimpleSelectable implements Serializable { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(Message.class.getName()); - - /** - * Magic value for this format of serialization version. - */ - private static final long serialVersionUID = 3418026921074097757L; - - /** - * If {@code true}, then modification logging be activated. This is a very - * expensive option as it causes a stack crawl to be captured for every - * message modification. - *

      - * To enable modification tracking, set to {@code true} and recompile. - */ - protected static final boolean LOG_MODIFICATIONS = false; - - /** - * If {@code true}, then a special tracking element is added to every - * message. This provides the ability to follow messages throughout the - * network. If a message has a tracking element then it will be used in - * the {@code toString()} representation. - *

      - * The element is currently named "Tracking UUID" and is stored in the - * "jxta" namespace. The element contains an IETF version 1 UUID in string - * form. - *

      - * To enable addition of a tracking element to every message, set the - * Java System Property {@code net.jxta.endpoint.Message.globalTracking} to - * {@code true} and restart your JXTA application. - * - * @see java.lang.System#setProperty(String,String) - */ - protected static final boolean GLOBAL_TRACKING_ELEMENT = - Boolean.getBoolean(Message.class.getName() + ".globalTracking"); - - /** - * Incremented for each standalone message instance. {@see #lineage} for - * information about how message numbers can be used. - */ - private static transient AtomicInteger messagenumber = new AtomicInteger(1); - - /** - * This string identifies the namespace which is assumed when calls are - * made that don't include a namespace specification. - */ - protected final String defaultNamespace; - - /** - * the namespaces in this message and the elements in each. - */ - protected transient Map> namespaces = new HashMap>(); - - /** - * List of the elements. - */ - protected transient List elements = new ArrayList(); - - /** - * Message properties HashMap - */ - protected transient Map properties = Collections.synchronizedMap(new HashMap()); - - /** - * A list of {@link java.lang.Integer} which details the lineage (history - * of cloning) that produced this message. This message's number is index - * 0, all of the ancestors are in order at higher indexes. - *

      - * Message numbers are not part of the message content and are only - * stored locally. The are useful for following messages throughout their - * lifetime and is normally shown as part of the toString() - * display for Messages. - */ - protected transient List lineage = new ArrayList(); - - /** - * Modification count of this message. Can be used to detect message being - * concurrently modified when message is shared. - *

      - * The modification count is part of the {@code toString()} display for - * Messages. - */ - protected transient volatile int modCount = 0; - - /** - * cached aggregate size of all the member elements. Used by - * {@link #getByteLength()} - */ - protected transient long cachedByteLength = 0; - - /** - * modcount at the time the message length was last calculated. Used by - * {@link #getByteLength()} - */ - protected transient int cachedByteLengthModCount = -1; - - /** - * If true then the message is modifiable. This is primarily - * intended as a diagnostic tool for detecting concurrent modification. - * - * @deprecated You really should not depend on this feature. - */ - @Deprecated - public boolean modifiable = true; - - /** - * If {@code LOG_MODIFICATIONS} is {@code true} then this will contain - * the history of modifications this message. - *

      - *

        - *
      • Values are {@link java.lang.Throwable} with the description - * field formatted as timeInAbsoluteMillis : threadName. - *
      • - *
      - */ - protected transient List modHistory; - - /** - * A ListIterator for MessageElements which also provides the ability to - * determine the namespace of the current message element. Message Elements - * are iterated in the order in which they were added to the Message. - *

      - * This Iterator returned is not synchronized with the message. If you - * modify the state of the Message, the iterator will throw - * ConcurrentModificationException when {@code next()} or - * {@code previous()} is called. - */ - public class ElementIterator implements ListIterator { - - /** - * The elements being iterated. - */ - ListIterator list; - - /** - * The current element - */ - element current = null; - - /** - * The modCount at the time when the iterator was created. - */ - transient int origModCount; - - /** - * Intialize the iterator from a list iterator. - * - * @param list The ListIterator we are managing. - */ - ElementIterator(ListIterator list) { - origModCount = Message.this.getMessageModCount(); - this.list = list; - } - - /** - * {@inheritDoc} - */ - public boolean hasNext() { - if (origModCount != Message.this.getMessageModCount()) { - RuntimeException failure = new ConcurrentModificationException( - Message.this + " concurrently modified. Iterator was made at mod " + origModCount); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, - Message.this + " concurrently modified. iterator mod=" + origModCount + " current mod=" - + Message.this.getMessageModCount() + "\n" + getMessageModHistory(), - failure); - } - throw failure; - } - return list.hasNext(); - } - - /** - * {@inheritDoc} - */ - public MessageElement next() { - if (origModCount != Message.this.getMessageModCount()) { - RuntimeException failure = new ConcurrentModificationException( - Message.this + " concurrently modified. Iterator was made at mod " + origModCount); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, - Message.this + " concurrently modified. iterator mod=" + origModCount + " current mod=" - + Message.this.getMessageModCount() + "\n" + getMessageModHistory(), - failure); - } - throw failure; - } - - current = list.next(); - return current.element; - } - - /** - * {@inheritDoc} - */ - public int nextIndex() { - return list.nextIndex(); - } - - /** - * {@inheritDoc} - */ - public boolean hasPrevious() { - if (origModCount != Message.this.getMessageModCount()) { - RuntimeException failure = new ConcurrentModificationException( - Message.this + " concurrently modified. Iterator was made at mod " + origModCount); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, - Message.this + " concurrently modified. iterator mod=" + origModCount + " current mod=" - + Message.this.getMessageModCount() + "\n" + getMessageModHistory(), - failure); - } - throw failure; - } - - return list.hasPrevious(); - } - - /** - * {@inheritDoc} - */ - public MessageElement previous() { - if (origModCount != Message.this.getMessageModCount()) { - RuntimeException failure = new ConcurrentModificationException( - Message.this + " concurrently modified. Iterator was made at mod " + origModCount); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, - Message.this + " concurrently modified. iterator mod=" + origModCount + " current mod=" - + Message.this.getMessageModCount() + "\n" + getMessageModHistory(), - failure); - } - throw failure; - } - - current = list.previous(); - return current.element; - } - - /** - * {@inheritDoc} - */ - public int previousIndex() { - return list.previousIndex(); - } - - /** - * {@inheritDoc} - *

      - * Not provided because the namespace cannot be specified. - */ - public void add(MessageElement obj) { - throw new UnsupportedOperationException("add() not supported"); - } - - /** - * {@inheritDoc} - */ - public void remove() { - if (origModCount != Message.this.getMessageModCount()) { - RuntimeException failure = new ConcurrentModificationException( - Message.this + " concurrently modified. Iterator was made at mod " + origModCount); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, - Message.this + " concurrently modified. iterator mod=" + origModCount + " current mod=" - + Message.this.getMessageModCount() + "\n" + getMessageModHistory(), - failure); - } - - throw failure; - } - - if (null == current) { - throw new IllegalStateException("no current element, call next() or previous()"); - } - - ListIterator elsPosition = Message.this.elements.listIterator(); - ListIterator nsPosition = namespaces.get(current.namespace).listIterator(); - - int currentPrevious = list.previousIndex(); - - // restart this iterator - while (list.previousIndex() >= 0) { - list.previous(); - } - - // readvance to the current position, but track in ns list and master list - while (list.previousIndex() < currentPrevious) { - element anElement = list.next(); - - try { - // advance to the same element in the master list. - element anElsElement; - - do { - anElsElement = elsPosition.next(); - } while (anElement != anElsElement); - - // advance to the same element in the ns list. - MessageElement anNsElement; - - if (current.namespace.equals(anElement.namespace)) { - do { - anNsElement = nsPosition.next(); - } while (anElement.element != anNsElement); - } - } catch (NoSuchElementException ranOut) { - RuntimeException failure = new ConcurrentModificationException( - Message.this + " concurrently modified. Iterator was made at mod " + origModCount); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, - Message.this + " concurrently modified. iterator mod=" + origModCount + " current mod=" - + Message.this.getMessageModCount() + "\n" + getMessageModHistory(), - failure); - } - - throw failure; - } - } - - elsPosition.remove(); - nsPosition.remove(); - list.remove(); - origModCount = Message.this.incMessageModCount(); - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "Removed " + current.namespace + "::" + current.element.getElementName() + "/" - + current.element.getClass().getName() + "@" + current.element.hashCode() + " from " + Message.this); - } - current = null; - } - - /** - * {@inheritDoc} - *

      - * Replacement MessageElement will be in the same name space as the - * replaced element. - */ - public void set(MessageElement obj) { - if (origModCount != Message.this.getMessageModCount()) { - RuntimeException failure = new ConcurrentModificationException( - Message.this + " concurrently modified. "); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, - Message.this + " concurrently modified. iterator mod=" + origModCount + " current mod=" - + Message.this.getMessageModCount() + "\n" + getMessageModHistory(), - failure); - } - throw failure; - } - - if (null == current) { - throw new IllegalStateException("no current element, call next() or previous()"); - } - - ListIterator elsPosition = Message.this.elements.listIterator(); - ListIterator nsPosition = namespaces.get(current.namespace).listIterator(); - - int currentPrevious = list.previousIndex(); - - // restart this iterator - while (list.previousIndex() >= 0) { - list.previous(); - } - - // readvance to the current position, but track in ns list and master list - while (list.previousIndex() < currentPrevious) { - element anElement = list.next(); - - try { - // advance to the same element in the master list. - element anElsElement; - - do { - anElsElement = elsPosition.next(); - } while (anElement != anElsElement); - - // advance to the same element in the ns list. - MessageElement anNsElement; - - if (current.namespace.equals(anElement.namespace)) { - do { - anNsElement = nsPosition.next(); - } while (anElement.element != anNsElement); - } - } catch (NoSuchElementException ranOut) { - RuntimeException failure = new ConcurrentModificationException( - Message.this + " concurrently modified. Iterator was made at mod " + origModCount); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, - Message.this + " concurrently modified. iterator mod=" + origModCount + " current mod=" - + Message.this.getMessageModCount() + "\n" + getMessageModHistory(), - failure); - } - throw failure; - } - } - - Message.element newCurrent = new Message.element(current.namespace, obj, null); - - elsPosition.set(newCurrent); - nsPosition.set(obj); - list.set(newCurrent); - origModCount = Message.this.incMessageModCount(); - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "Replaced " + current.namespace + "::" + current.element.getElementName() + "/" - + current.element.getClass().getName() + "@" + current.element.hashCode() + " with " - + newCurrent.namespace + "::" + newCurrent.element.getElementName() + "/" - + newCurrent.element.getClass().getName() + "@" + newCurrent.element.hashCode() + " in " + Message.this); - } - current = newCurrent; - } - - /** - * return the namespace of the current element. - * - * @return String containing the name space of the current element. - */ - public String getNamespace() { - if (null == current) { - throw new IllegalStateException("no current element, call next() or previous()"); - } - - return current.namespace; - } - - /** - * Return the signature element of the current element. - * - * @return The signature element of the current element. - */ - public MessageElement getSignature() { - if (null == current) { - throw new IllegalStateException("no current element, call next() or previous()"); - } - - return (null != current.signature) ? current.signature : current.element.getSignature(); - } - } - - - /** - * Holds an element, its namespace and optionally an override signature - * element. - */ - protected static class element { - final String namespace; - final MessageElement element; - final MessageElement signature; - - element(String namespace, MessageElement element, MessageElement signature) { - this.namespace = namespace; - this.element = element; - this.signature = signature; - } - } - - /** - * Standard Constructor for messages. The default namespace will be the - * empty string ("") - */ - public Message() { - this("", false); - } - - /** - * Standard Constructor for messages. - * - * @param defaultNamespace the namespace which is assumed by methods which - * do not require a namespace specification. - */ - protected Message(String defaultNamespace) { - this(defaultNamespace, false); - } - - /** - * Standard Constructor for messages. - * - * @param defaultNamespace the namespace which is assumed by methods which - * do not require a namespace specification. - * @param clone If {@code true} then we are creating a clone. - */ - private Message(String defaultNamespace, boolean clone) { - this.defaultNamespace = defaultNamespace; - - lineage.add(messagenumber.getAndIncrement()); - - if (LOG_MODIFICATIONS) { - modHistory = new ArrayList(); - incMessageModCount(); - } - - if (!clone && GLOBAL_TRACKING_ELEMENT) { - UUID tracking = UUIDFactory.newSeqUUID(); - - MessageElement trackingElement = new StringMessageElement("Tracking UUID", tracking.toString(), null); - - addMessageElement("jxta", trackingElement); - } - } - - /** - * {@inheritDoc} - *

      - * Duplicates the Message. The returned duplicate is a real copy. It may - * be freely modified without causing change to the originally cloned - * message. - * - * @return Message a Message that is a copy of the original message - */ - @Override - public Message clone() { - Message clone = new Message(getDefaultNamespace(), true ); - - clone.lineage.addAll(lineage); - clone.elements.addAll(elements); - - for (String aNamespace : namespaces.keySet()) { - List namespaceElements = namespaces.get(aNamespace); - - List newNamespaceElements = new ArrayList(namespaceElements.size()); - - newNamespaceElements.addAll(namespaceElements); - clone.namespaces.put(aNamespace, newNamespaceElements); - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Created clone " + clone + " of " + this); - } - - return clone; - } - - /** - * {@inheritDoc} - *

      - * Compare this Message against another. Returns {@code true} if all of the - * elements are identical and in the same order. Message properties - * (setProperty()/getProperty()) are not considered in the calculation. - * - * @param target The Message to compare against. - * @return {@code true} if the elements are identical otherwise - * {@code false}. - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof Message) { - Message likeMe = (Message) target; - - ElementIterator myElements = getMessageElements(); - ElementIterator itsElements = likeMe.getMessageElements(); - - while (myElements.hasNext()) { - if (!itsElements.hasNext()) { - return false; // it has fewer than i do. - } - - MessageElement mine = myElements.next(); - MessageElement its = itsElements.next(); - - if (!myElements.getNamespace().equals(itsElements.getNamespace())) { - return false; // elements not in the same namespace - } - - if (!mine.equals(its)) { - return false; // content didnt match - } - } - - return (!itsElements.hasNext()); // ran out at the same time? - } - - return false; // not a message - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = 0; - Iterator eachElement = getMessageElements(); - - while (eachElement.hasNext()) { - MessageElement anElement = eachElement.next(); - - result += anElement.hashCode(); - result *= 6037; // a prime - } - - if (0 == result) { - result = 1; - } - - return result; - } - - /** - * {@inheritDoc} - *

      - * This implementation is intended to assist debugging. You should not - * depend upon the format of the result. - */ - @Override - public String toString() { - StringBuilder toString = new StringBuilder(128); - - toString.append(getClass().getName()); - toString.append('@'); - toString.append(super.hashCode()); - toString.append('('); - toString.append(modCount); - toString.append("){"); - - Iterator allLineage = getMessageLineage(); - - while (allLineage.hasNext()) { - toString.append(allLineage.next().toString()); - if (allLineage.hasNext()) { - toString.append(','); - } - } - - toString.append('}'); - - if (GLOBAL_TRACKING_ELEMENT) { - toString.append("["); - Iterator eachUUID = getMessageElements("jxta", "Tracking UUID"); - - while (eachUUID.hasNext()) { - toString.append("["); - toString.append(eachUUID.next().toString()); - toString.append("]"); - if (eachUUID.hasNext()) { - toString.append(','); - } - } - toString.append("]"); - } - - return toString.toString(); - } - - /** - * Read this Object in for Java Serialization - * - * @param s The stream from which the Object will be read. - * @throws IOException for errors reading from the input stream. - * @throws ClassNotFoundException if the serialized representation contains - * references to classes which cannot be found. - */ - private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { - // reads defaultNamespace, modifiable flag - s.defaultReadObject(); - - MimeMediaType readType = new MimeMediaType(s.readUTF()); - - // XXX bondolo 20040307 Should do something with encoding here. - - Message readMessage = WireFormatMessageFactory.fromWire(s, readType, null); - - namespaces = readMessage.namespaces; - elements = readMessage.elements; - - if (!namespaces.containsKey(defaultNamespace)) { - throw new IOException("Corrupted Object--does not contain required namespace."); - } - - properties = new HashMap(); - lineage = new ArrayList(); - - lineage.add(messagenumber.getAndIncrement()); - - if (LOG_MODIFICATIONS) { - modHistory = new ArrayList(); - incMessageModCount(); - } - } - - /** - * Write this Object out for Java Serialization - * - * @param s The stream to which the Object will be written. - * @throws IOException for errors writing to the output stream. - */ - private void writeObject(ObjectOutputStream s) throws IOException { - s.defaultWriteObject(); - - MimeMediaType writeType = WireFormatMessageFactory.DEFAULT_WIRE_MIME; - - s.writeUTF(writeType.toString()); - - // XXX bondolo 20040307 Should do something with encoding here. - - WireFormatMessage serialed = WireFormatMessageFactory.toWire(this, writeType, null); - - serialed.sendToStream(s); - } - - /** - * Return the default Namespace of this message. - * - * @return The default namespace for this message. - */ - protected String getDefaultNamespace() { - return defaultNamespace; - } - - /** - * Add a MessageElement into the message. The MessageElement is stored in - * the default namespace. - * - * @param add the Element to add to the message. - */ - public void addMessageElement(MessageElement add) { - - addMessageElement(null, add); - } - - /** - * Add a MessageElement into the message using the specified namespace. - * - * @param namespace contains the namespace of the element to add. You can - * specify null as a shorthand for the default namespace. - * @param add the MessageElement to add to the message. - */ - public void addMessageElement(String namespace, MessageElement add) { - addMessageElement(namespace, add, null); - } - - /** - * Add a MessageElement into the Message using the specified namespace. - * - * @param namespace contains the namespace of the element to add. You can - * specify null as a shorthand for the default namespace. - * @param add the MessageElement to add to the message. - * @param signature The signature MessageElement associated with the - * MessageElement. This allows for an alternate signature element to the - * signature element associated with the message element. - */ - public void addMessageElement(String namespace, MessageElement add, MessageElement signature) { - if (null == namespace) { - namespace = getDefaultNamespace(); - } - - if (null == add) { - throw new IllegalArgumentException("Message Element must be non-null"); - } - - elements.add(new element(namespace, add, signature)); - - List namespaceElements = namespaces.get(namespace); - - if (null == namespaceElements) { - namespaceElements = new ArrayList(); - namespaces.put(namespace, namespaceElements); - } - - namespaceElements.add(add); - incMessageModCount(); - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( "Added " + namespace + "::" + add.getElementName() + "/" + - add.getClass().getName() + "@" + add.hashCode() + " to " + this); - } - } - - /** - * Replace a {@link net.jxta.endpoint.MessageElement} in the message. This - * method will remove all MessageElement instances in the default namespace - * which match the specified name (if any) and then insert the replacement - * element. The existing version of the element is returned, if more than - * one matching element was removed, a random matching element is returned. - *

      - * For greatest control over element replacement, use the - * {@link java.util.ListIterator#set(java.lang.Object)} method as returned - * by {@link #getMessageElements()}, - * {@link #getMessageElements(java.lang.String)} or - * {@link #getMessageElementsOfNamespace(java.lang.String)} - * - * @param replacement the Element to be inserted into to the message. - * @return One of the elements which was replaced or null if no existing - * matching item was located. - */ - public MessageElement replaceMessageElement(MessageElement replacement) { - return replaceMessageElement(null, replacement); - } - - /** - * Replace a {@link net.jxta.endpoint.MessageElement} in the message using the specified - * namespace. This method will remove all MessageElement instances which - * match the specified name (if any) and then insert the replacement - * element. The existing version of the element is returned, if more than - * one matching element was removed, a random matching element is returned. - *

      - * For greatest control over element replacement, use the - * {@link java.util.ListIterator#set(java.lang.Object)} method as returned - * by {@link #getMessageElements()}, - * {@link #getMessageElements(java.lang.String)} or - * {@link #getMessageElementsOfNamespace(java.lang.String)} - * - * @param namespace contains the namespace of the element to be replaced. - * You can specify null as a shorthand for the default namespace. - * @param replacement the Element to be inserted into to the message. - * @return One of the elements which was replaced or null if no existing - * matching item was located. - */ - public MessageElement replaceMessageElement(String namespace, MessageElement replacement) { - if (null == namespace) { - namespace = getDefaultNamespace(); - } - - if (null == replacement) { - throw new IllegalArgumentException("Message Element must be non-null"); - } - - MessageElement removed = null; - Iterator allMatching = getMessageElements(namespace, replacement.getElementName()); - - while (allMatching.hasNext()) { - MessageElement anElement = allMatching.next(); - - allMatching.remove(); - removed = anElement; - } - - addMessageElement(namespace, replacement); // updates mod count - - return removed; - } - - /** - * Returns an iterator of the namespaces present in this message. - * - * @return iterator of strings of the namespaces of this message. - */ - public Iterator getMessageNamespaces() { - return Collections.unmodifiableMap(namespaces).keySet().iterator(); - } - - /** - * Retrieve a message element by name from the message without regard to - * namespace. If there is more than one message element with this name, the - * first message element will be returned. - * - * @param name The name of the message element to attempt to retrieve. - * @return Element the element or null if no matching element could be - * found. - */ - public MessageElement getMessageElement(String name) { - Iterator eachElement = elements.listIterator(); - - while (eachElement.hasNext()) { - element anElement = eachElement.next(); - - if (name.equals(anElement.element.getElementName())) { - return anElement.element; - } - } - - return null; - } - - /** - * Retrieve a message element by name in the specified namespace from the - * message. If there is more than one message element matching this name, - * the first message element will be returned. - * - * @param namespace contains the namespace of the element to get. You can - * specify {@code null} as a shorthand for the default namespace. - * @param name The name of the message element to retrieve. - * @return The Message Element or {@code null} if no matching message - * element could be found. - */ - public MessageElement getMessageElement(String namespace, String name) { - if (null == namespace) { - namespace = getDefaultNamespace(); - } - - List namespaceElements = namespaces.get(namespace); - - // no namespace means no element. - if (null == namespaceElements) { - return null; - } - - Iterator eachElement = namespaceElements.listIterator(); - - while (eachElement.hasNext()) { - MessageElement anElement = eachElement.next(); - - if (name.equals(anElement.getElementName())) { - return anElement; - } - } - - return null; - } - - /** - * Returns a list iterator of all of the elements contained in this message. - * Elements from all namespaces are returned. - *

      - * The iterator returned is not synchronized with the message and will - * throw {@link java.util.ConcurrentModificationException} if the - * message is modified. - * - * @return Enumeration of Elements. - */ - public ElementIterator getMessageElements() { - List theMsgElements = new ArrayList(elements); - - return new ElementIterator(theMsgElements.listIterator()); - } - - /** - * Returns a list iterator of all of the elements contained in this - * message who's name matches the specified name. Elements from all - * namespaces are returned. Message Elements are iterated in the order in - * which they were added to the Message. - *

      - * The iterator returned is not synchronized with the message and will - * throw {@link java.util.ConcurrentModificationException} if the - * message is modified. - * - * @param name the name of the elements to match against - * @return iterator of the elements matching the specified name, if any. - */ - public ElementIterator getMessageElements(String name) { - List theMsgElements = new ArrayList(elements.size()); - - for (element anElement : elements) { - if (name.equals(anElement.element.getElementName())) { - theMsgElements.add(anElement); - } - } - - return new ElementIterator(theMsgElements.listIterator()); - } - - /** - * Returns a list iterator of all of the elements contained in this message - * which match the specified namespace. Message Elements are iterated in - * the order in which they were added to the Message. - *

      - * The ListIterator returned is not synchronized with the message. If - * you modify the state of the Message, the iterator will throw - * ConcurrentModificationException when {@code next()} or - * {@code previous()} is called. - * - * @param namespace contains the namespace which must be matched in the - * elements returned. You can specify {@code null} as a shorthand for the - * default namespace. - * @return Iterator of Message Elements matching namespace. - */ - public ElementIterator getMessageElementsOfNamespace(String namespace) { - List theMsgElements = new ArrayList(elements.size()); - - if (null == namespace) { - namespace = getDefaultNamespace(); - } - - for (element anElement : elements) { - if (namespace.equals(anElement.namespace)) { - theMsgElements.add(anElement); - } - } - - return new ElementIterator(theMsgElements.listIterator()); - } - - /** - * Returns a list iterator of all of the elements contained in the - * specified namespace who's name matches the specified name in the order - * in which they were added to the Message. - *

      - * The iterator returned is not synchronized with the message and will - * throw {@link java.util.ConcurrentModificationException} if the message - * is modified. - * - * @param namespace The namespace which must be matched in the elements - * returned. You can specify {@code null} as a shorthand for the default - * namespace. - * @param name The name of the elements to retrieve. - * @return Iterator of Message Elements matching namespace and name. - */ - public ElementIterator getMessageElements(String namespace, String name) { - List theMsgElements = new ArrayList(elements.size()); - - if (null == namespace) { - namespace = getDefaultNamespace(); - } - - for (element anElement : elements) { - if (namespace.equals(anElement.namespace) && name.equals(anElement.element.getElementName())) { - theMsgElements.add(anElement); - } - } - - return new ElementIterator(theMsgElements.listIterator()); - } - - /** - * Returns a list iterator of all of the elements contained in this message - * whose mime-type matchs the given in the order they were added to the - * message. Elements from all namespaces are returned. - *

      - * The iterator returned is not synchronized with the message and will - * throw {@link java.util.ConcurrentModificationException} if the - * message is modified. - * - * @param type contains the type of the elements to get - * @return Iterator of Message Elements matching type. - */ - public ElementIterator getMessageElements(MimeMediaType type) { - List theMsgElements = new ArrayList(elements.size()); - - ListIterator eachElement = elements.listIterator(); - - while (eachElement.hasNext()) { - element anElement = eachElement.next(); - - if (type.equals(anElement.element.getMimeType())) { - theMsgElements.add(anElement); - } - } - - return new ElementIterator(theMsgElements.listIterator()); - } - - /** - * Returns a list iterator of all of the elements contained in this message - * whose type matches the given in the order they were added to the message. - *

      - * The iterator returned is not synchronized with the message and will - * throw {@link java.util.ConcurrentModificationException} if the - * message is modified. - * - * @param namespace contains the namespace which must be matched in the - * elements returned. You can specify null as a shorthand for the default - * namespace. - * @param type contains the type of the elements to get - * @return Iterator of Message Elements matching namespace and matching - * type. - */ - public ElementIterator getMessageElements(String namespace, MimeMediaType type) { - List theMsgElements = new ArrayList(elements.size()); - - if (null == namespace) { - namespace = getDefaultNamespace(); - } - - for (element anElement : elements) { - if (namespace.equals(anElement.namespace) && type.equals(anElement.element.getMimeType())) { - theMsgElements.add(anElement); - } - } - - return new ElementIterator(theMsgElements.listIterator()); - } - - /** - * Remove an the first occurrence of the provided MessageElement from the - * message. - * - * @param remove the Element to remove from the message. - * @return boolean returns true if the element was removed, otherwise false. - */ - public boolean removeMessageElement(MessageElement remove) { - Iterator eachElement = getMessageElements(); - - while (eachElement.hasNext()) { - MessageElement anElement = eachElement.next(); - - if (remove == anElement) { - eachElement.remove(); // updates mod count - - return true; - } - } - - return false; - } - - /** - * Remove the first occurrence of the provided MessageElement within the - * specified namespace from the message. You can specify null as a - * shorthand for the default namespace. - * - * @param namespace the namespace from which the element is to be removed. - * @param remove the Element to remove from the message. - * @return boolean returns true if the element was removed, otherwise false. - */ - public boolean removeMessageElement(String namespace, MessageElement remove) { - Iterator eachElement = getMessageElementsOfNamespace(namespace); - - while (eachElement.hasNext()) { - MessageElement anElement = eachElement.next(); - - if (remove == anElement) { - eachElement.remove(); // updates mod count - - return true; - } - } - - return false; - } - - /** - * Removes all of the elements in all namespaces from the message. Also - * clears any properties set for this message. - */ - public void clear() { - elements.clear(); - namespaces.clear(); - properties.clear(); - // a cleared message has no ancestors - lineage.retainAll(Collections.singletonList(lineage.get(0))); - - incMessageModCount(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Cleared " + this); - } - } - - /** - * Returns the aggregate size of all the member elements. - * - * @return the sum of all element sizes in bytes. - */ - public synchronized long getByteLength() { - if (modCount != cachedByteLengthModCount) { - cachedByteLength = 0; - Iterator eachElement = getMessageElements(); - - while (eachElement.hasNext()) { - MessageElement anElement = eachElement.next(); - - cachedByteLength += anElement.getByteLength(); - } - - cachedByteLengthModCount = modCount; - } - - return cachedByteLength; - } - - /** - * Returns the modification count of this message. This ever ascending - * number can be used to determine if the message has been modified by - * another thread or for use in caching of parts of the message structure. - * - * @return the modification count of this message. - */ - public int getMessageModCount() { - return modCount; - } - - /** - * Returns the modification count of this message. This ever ascending - * number can be used to determine if the message has been modified by - * another thread or for use in caching of parts of the message structure. - * - * @return the modification count of this message. - */ - protected synchronized int incMessageModCount() { - modCount++; - - if (LOG_MODIFICATIONS) { - modHistory.add(new Throwable(Long.toString(System.currentTimeMillis()) + " : " + Thread.currentThread().getName())); - } - - if (!modifiable) { - IllegalStateException failure = new IllegalStateException("Unmodifiable message should not have been modified"); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, failure.getMessage(), failure); - } - throw failure; - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Modification to " + this); - } - - return modCount; - } - - /** - * Returns a String containing the modification history for this message - * - * @return a String containing the modification history for this message. - */ - public synchronized String getMessageModHistory() { - - if (LOG_MODIFICATIONS) { - StringBuilder modHistoryStr = new StringBuilder("Message Modification History for "); - - modHistoryStr.append(toString()); - modHistoryStr.append("\n\n"); - for (int eachMod = modHistory.size() - 1; eachMod >= 0; eachMod--) { - StringWriter aStackStr = new StringWriter(); - Throwable aStack = modHistory.get(eachMod); - - aStack.printStackTrace(new PrintWriter(aStackStr)); - modHistoryStr.append("Modification #"); - modHistoryStr.append(eachMod + 1); - modHistoryStr.append(":\n\n"); - modHistoryStr.append(aStackStr.toString()); - modHistoryStr.append("\n"); - } - return modHistoryStr.toString(); - } else { - return "Modification history tracking is disabled"; - } - } - - /** - * Returns the message number of this message. Message Numbers are intended - * to assist with debugging and the management of message cloning. - *

      - * Each message is assigned a unique number upon creation. Message - * Numbers are monotonically increasing for each message created. - *

      - * Message Numbers are transient, ie. if the message object is - * serialized then the message number after deserialization will be - * probably be a different value. Message numbers should not be used to - * record permanent relationships between messages. - * - * @return int this message's message number. - */ - public int getMessageNumber() { - return lineage.get(0); - } - - /** - * Returns an iterator which describes the lineage of this message. Each - * entry is an {@link java.lang.Integer} Message Number. The first entry is - * this message's number, following entries are the ancestors of this - * message. - * - * @return an Iterator of {@link java.lang.Integer}. Each entry is a - * message number. - */ - public Iterator getMessageLineage() { - return Collections.unmodifiableList(lineage).iterator(); - } - - /** - * Associate a transient property with this message. if there was a - * previous value for the key provided then it is returned. This feature is - * useful for managing the state of messages during processing and for - * caching. Message Properties are not transmitted as part of the - * Message when the message is serialized! - *

      - * The setting of particular keys may be controlled by a Java Security - * Manager. Keys of type 'java.lang.Class' are checked against the caller of - * this method. Only callers which are instances of the key class may modify - * the property. This check is not possible through reflection. All other - * types of keys are unchecked. - * - * @param key the property key - * @param value the value for the property - * @return previous value for the property or null if no previous - */ - public Object setMessageProperty(Object key, Object value) { - - /* - if( key instanceof java.lang.Class ) { - Class keyClass = (Class) key; - SecurityManager secure = new SecurityManager() { - public boolean checkCallerOfClass( Class toCheck ) { - Class [] context = getClassContext(); - - return toCheck.isAssignableFrom( context[2] ); - } - }; - - if( !secure.checkCallerOfClass( keyClass ) ) { - throw new SecurityException( "You can't set that key from this context." ); - } - } - */ - - Object res = properties.put(key, value); - - // Any property addition (including redundant) is notified. Removals are - // too, since removal is done by assigning null. - - // Exception: when removing what was not there: no notification. - - if (res != null || value != null) { - notifyChange(); - } - - return res; - } - - /** - * Retrieves a transient property from the set for this message. - * - * @param key the property key. - * @return value for the property or null if no property for this key. - */ - public Object getMessageProperty(Object key) { - - return properties.get(key); - } - - /** - * {@inheritDoc} - */ - public void itemChanged(SimpleSelectable o) {// For now, messages are not themselves registered with anything. - // Therefore itemChanged does not do a thing. - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageElement.java deleted file mode 100644 index 5c004c97..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageElement.java +++ /dev/null @@ -1,567 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; -import java.lang.ref.SoftReference; -import java.util.HashMap; -import java.util.Map; - -import java.io.UnsupportedEncodingException; -import java.util.UUID; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.Document; -import net.jxta.document.MimeMediaType; -import net.jxta.util.CountingOutputStream; -import net.jxta.util.DevNullOutputStream; - -// imported for implementation of {@link #getSequentialName()} -import net.jxta.impl.id.UUID.UUIDFactory; - - -/** - * JXTA Message Elements are used to add data to a JXTA Message. Message - * Elements are immutable objects. A Message Element may be shared amongst as - * many messages as is desired. - *

      - * Several Message Element sub-classes are provided for handling various types - * of data. All Message Elements are internally converted to raw bytes when sent - * as part of a Message. The various Message Element flavors are provided for - * convenience and efficiency. They enable the simplest creation and most - * efficient conversion from the individual data types to the appropriate binary - * data. Because Message Elements are merely a convenient representation for - * binary data the object type of Message Element received by a peer may not - * be the same as was sent by the sending peer. Even though the Message - * Element container may change during transmission the data contained in the - * Message Element is faithfully preserved. - *

      - * A Message Element is composed of four components: - *

      - *

        - *
      • An optional name. This may be any {@link java.lang.String}. Unnamed - * elements are assumed to have the name "" (the empty string).
      • - *
      • An optional {@link net.jxta.document.MimeMediaType}. If not specified - * the Mime Media Type is assumed to be "Application/Octet-Stream".
      • - *
      • Data. Sub-classes of MessageElement allow you to create elements based - * on a variety of data formats.
      • - *
      • An optional signature. This is a Message Element that is associated to - * this element and may contain a cryptographic signature/hash of this message - * element. - *
      • - *
      - *

      - *

      The data contained within a MessageElement is accessible in four ways: - *

      - *

        - *
      • As an {@link java.io.InputStream} from {@link #getStream()}
      • - *
      • Sending the data a {@link java.io.OutputStream} via {@link #sendToStream(OutputStream)}
      • - *
      • As a {@link java.lang.String} from {@link #toString()}
      • - *
      • As a byte array from from {@link #getBytes(boolean)}
      • - *
      - * - * @see net.jxta.endpoint.Message - */ -public abstract class MessageElement implements Document { - - /** - * Logger - */ - private static transient final Logger LOG = Logger.getLogger(MessageElement.class.getName()); - - /** - * The name of this element. May be the empty string ("") if the element is - * unnamed. - */ - protected final String name; - - /** - * The type of this element. - */ - protected final MimeMediaType type; - - /** - * The optional element which digitally signs or digests this element. - * If null then the element is has no signature element. - */ - protected final MessageElement sig; - - /** - * message properties hashmap - */ - private Map properties = null; - - /** - * cached result of {@link #getByteLength()} operation. - */ - protected transient long cachedGetByteLength = -1; - - /** - * cached result of {@link #getBytes(boolean)} operation. - */ - protected transient SoftReference cachedGetBytes = null; - - /** - * cached result of {@link #toString()} operation. - */ - protected transient SoftReference cachedToString = null; - - /** - * Returns a pseudo-random unique string which can be used as an element - * name. - * - * @return String containing a pseudo-random value - */ - public static String getUniqueName() { - return UUID.randomUUID().toString(); - } - - /** - * Returns a string containing a pseudo-random unique string. The result of - * String.compare() will be consistent with the order in which - * results were returned from this function. - *

      - *

      Security Consideration : Be aware that the pseudo random portion of - * the names generated by this string are shared amongst all peer groups - * running in the same classloader. You may be at a risk for loss of - * anonymity if you use the element names produced in more than one peer - * group. - * - * @return String containing a pseudo-random value. The result of - * String.compare() will be consistent with the order in - * which results were returned from this function. - */ - public static String getSequentialName() { - return UUIDFactory.newSeqUUID().toString(); - } - - /** - * Internal constructor for initializing everything but the data. - * - * @param name Name of the Element. May be the empty string ("") if - * the Element is not named. - * @param type Type of the Element. null is equivalent to specifying - * the type "Application/Octet-stream" - * @param sig optional message digest/digital signature element. If - * no signature is to be specified, pass null. - */ - protected MessageElement(String name, MimeMediaType type, MessageElement sig) { - this.name = (null != name) ? name : ""; - - this.type = (null != type) ? type.intern() : MimeMediaType.AOS; - - if ((null != sig) && (null != sig.sig)) { - throw new IllegalArgumentException("Invalid Signature Element. Signatures may not have signatures."); - } - - this.sig = sig; - } - - /** - * {@inheritDoc} - * - * @deprecated Since Message Elements are immutable this method does - * nothing useful. - */ - @Override - @Deprecated - public final MessageElement clone() { - return this; - } - - /** - * {@inheritDoc} - *

      - *

      Elements are considered equal if they have the same name, type and - * signatures. Element data is not considered by this implementation as - * it is mostly intended for subclass use. - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; // same object - } - - if (target instanceof MessageElement) { - MessageElement likeMe = (MessageElement) target; - - // sig is nullable so test seperatly. - boolean sigequals = (null != sig) ? sig.equals(likeMe.sig) : (null == likeMe.sig); - - return sigequals && name.equals(likeMe.name) && type.equals(likeMe.type); - } - - return false; // not a MessageElement - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int sigHash = ((null != getSignature()) && (this != getSignature())) ? getSignature().hashCode() : 1; - - int result = sigHash * 2467 + // a prime - getElementName().hashCode() * 3943 + // also a prime - getMimeType().hashCode(); - - return (0 != result) ? result : 1; - } - - /** - * {@inheritDoc} - *

      - *

      Returns a String representation of the element data. The - * 'charset' parameter of the message element's mimetype, if - * any, is used to determine encoding. If the charset specified is - * unsupported then the default encoding will be used. - *

      - *

      synchronized for caching purposes. - */ - @Override - public synchronized String toString() { - String result; - - if (null != cachedToString) { - result = cachedToString.get(); - - if (null != result) { - return result; - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("creating toString of " + getClass().getName() + '@' + Integer.toHexString(hashCode())); - } - - String charset = type.getParameter("charset"); - - StringBuilder theString = new StringBuilder(); - - Reader asString; - - try { - if (null == charset) { - asString = new InputStreamReader(getStream()); - } else { - try { - asString = new InputStreamReader(getStream(), charset); - } catch (UnsupportedEncodingException caught) { - throw new IllegalStateException("Unsupported charset : " + charset); - } - } - - char[] characters = new char[256]; - - do { - int res = asString.read(characters); - - if (res < 0) { - break; - } - - theString.append(characters, 0, res); - } while (true); - - result = theString.toString(); - - cachedToString = new SoftReference(result); - return result; - } catch (IOException caught) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not generate string for element. ", caught); - } - - throw new IllegalStateException("Could not generate string for element. " + caught); - } - } - - /** - * Returns the name of the MessageElement. Unnamed elements will return - * the empty string (""); - * - * @return String containing the name of the MessageElement. - */ - public String getElementName() { - return name; - } - - /** - * {@inheritDoc} - *

      - *

      Will return "Application/Octet-Stream" if no type was originally - * specified. - */ - public MimeMediaType getMimeType() { - return type; - } - - /** - * {@inheritDoc} - *

      - *

      We use the "unknown" extension and leave it to sub-classes to - * extend this. If we had a mailcap facility we could do better - * classification based on mimetype. - */ - public String getFileExtension() { - return "???"; - } - - /** - * Returns the size of the element data in bytes. - * - * @return long containing the size of the element data. - */ - public synchronized long getByteLength() { - if (cachedGetByteLength >= 0) { - return cachedGetByteLength; - } - - CountingOutputStream countBytes = new CountingOutputStream(new DevNullOutputStream()); - - try { - sendToStream(countBytes); - cachedGetByteLength = countBytes.getBytesWritten(); - return cachedGetByteLength; - } catch (IOException caught) { - throw new IllegalStateException("Could not get length of element : " + caught.toString()); - } - } - - /** - * Returns a byte array which contains the element data. The byte array - * returned may be shared amongst all copies of the element, - * do not modify it. The copy parameter allows you to request a - * private, modifiable copy of the element data. - *

      - *

      This implementation builds the byte array from the stream. - * - * @param copy If true then the result can be modified without damaging the state of this - * MessageElement. If false, then the result may be a shared copy of the data and - * should be considered read-only. - * @return byte[] Contents of message element. - */ - public synchronized byte[] getBytes(boolean copy) { - byte[] result; - - if (null != cachedGetBytes) { - result = cachedGetBytes.get(); - - if (null != result) { - if (copy) { - byte[] theCopy = new byte[result.length]; - - System.arraycopy(theCopy, 0, result, 0, result.length); - } else { - return result; - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("creating getBytes of " + getClass().getName() + '@' + Integer.toHexString(hashCode())); - } - - long len = getByteLength(); - - if (len > Integer.MAX_VALUE) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("MessageElement is too large to be stored in a byte array."); - } - - throw new IllegalStateException("MessageElement is too large to be stored in a byte array."); - } - - result = new byte[(int) len]; - - try { - DataInput di = new DataInputStream(getStream()); - - di.readFully(result); - } catch (IOException caught) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failed to get bytes of Message Element. ", caught); - } - throw new IllegalStateException("Failed to get bytes of Message Element. " + caught); - } - - // if this is supposed to be a shared buffer then we can cache it. - if (!copy) { - cachedGetBytes = new SoftReference(result); - } - - return result; - } - - /** - * {@inheritDoc} - *

      - *

      This version probably has sub-optimal performance. Sub-classes - * should override this implementation. - */ - public void sendToStream(OutputStream sendTo) throws IOException { - copyInputStreamToOutputStream(getStream(), sendTo); - } - - /** - * Returns the element containing the digest/digital signature for - * this element - * - * @return Element containing the digital signature. - */ - public MessageElement getSignature() { - - return sig; - } - - /** - * Associate a transient property with this element. If there was a previous - * value for the key provided then it is returned. - *

      - *

      Element properties are useful for managing the state of element - * during processing. Element properties are not transmitted with the - * message element when the message element is sent as part of a message. - *

      - *

      The setting of particular keys may be controlled by a Java Security - * Manager. Keys of type 'java.lang.Class' are checked against the caller of - * this method. Only callers which are instances of the key class may modify - * the property. This check is not possible through reflection. All other - * types of keys are unchecked. - * - * @param key the property key - * @param value the value for the property - * @return previous value for the property or null if no previous - */ - public synchronized Object setElementProperty(Object key, Object value) { - - /* - if( key instanceof java.lang.Class ) { - Class keyClass = (Class) key; - SecurityManager secure = new SecurityManager() { - public boolean checkCallerOfClass( Class toCheck ) { - Class [] context = getClassContext(); - - return toCheck.isAssignableFrom( context[2] ); - } - }; - - if( !secure.checkCallerOfClass( keyClass ) ) { - throw new SecurityException( "You can't set that key from this context." ); - } - } - */ - - if (null == properties) { - properties = new HashMap(); - } - - return properties.put(key, value); - } - - /** - * Retrieves a transient property from the set for this element. - * - *

      Element properties are useful for managing the state of element - * during processing. Element properties are not transmitted with the - * message element when the message element is sent as part of a message. - * - * @param key the property key. - * @return value for the property or null if there is no property for this - * key. - */ - public Object getElementProperty(Object key) { - - if (null == properties) { - return null; - } - - return properties.get(key); - } - - /** - * Copies an input stream to an output stream with buffering. - * - * @param source The stream to copy from. - * @param sink The stream to send the data to. - * @throws IOException if there is a problem copying the data - */ - protected static void copyInputStreamToOutputStream(InputStream source, OutputStream sink) throws IOException { - int c; - byte[] buf = new byte[4096]; - - do { - c = source.read(buf); - - if (-1 == c) { - break; - } - - sink.write(buf, 0, c); - } while (true); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageFilterListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageFilterListener.java deleted file mode 100644 index 1fd9d76d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageFilterListener.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - - -/** - * This interface is used by Message Filters. - * - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.endpoint.EndpointAddress - * @see net.jxta.endpoint.Message - */ -public interface MessageFilterListener { - - /** - * This method is invoked by the EndpointService for each message for which - * this filter is registered. - *

      - * The src and destination addresses are the addresses as they were - * before any filters were run upon the message. If your filter is dependant - * upon the current value of thse addresses it should examine the message - * directly. - * - * @param message Incoming message - * @param srcAddr Endpoint Address of the original source of the message - * @param dstAddr Endpoint Address of the original destination of the message - * @return Message The potentially modified or alternate message. If null - * is returned then the message has been discarded. - */ - public Message filterMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr); - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessagePropagater.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessagePropagater.java deleted file mode 100644 index d105c2a4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessagePropagater.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -/** - * A MessagePropagater is a MessageTransport that can send propagated - * (multicast) messages. - * - * @see net.jxta.endpoint.MessageTransport - * @see net.jxta.endpoint.Message - * @see net.jxta.endpoint.Messenger - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.endpoint.MessageSender - * @see net.jxta.endpoint.MessageReceiver - */ -public interface MessagePropagater extends MessageTransport { - - /** - * Returns the {@link EndpointAddress} which will be used as the source - * address for all messages sent by this message sender. This is the - * "preferred" address to which replies should be sent. This address is not - * necessarily the best or only address by which the peer may be reached. - *

      - * The public address may also be for a different message transport. - * - * @return an EndpointAddress containing the public address for this - * message receiver. - */ - public EndpointAddress getPublicAddress(); - - /** - * Propagates a Message via this Message Transport. - * - * @param msg The Message to be propagated. - * @param serviceName Contains the name of the destination service, if any. - * This will be integrated into the destination address. - * @param serviceParams Contains the parameters associated with the service, - * if any. This will be integrated into the destination address. - * @param initialTTL The requested initial TTL for this message. This value - * may be reduced by the implementation. - * @return {@code true} if the Message was propagated otherwise - * {@code false}. - */ - public boolean propagate(Message msg, String serviceName, String serviceParams, int initialTTL); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageReceiver.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageReceiver.java deleted file mode 100644 index 766e20a6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageReceiver.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -import java.util.Iterator; - - -/** - * A MessageReceiver is a MessageTransport that is capable of receiving messages. - * A MessageReceiver receives messages from the network and hands them to the - * the {@link EndpointService} for processing. A Message Receiver is known by - * the {@link EndpointAddress EndpointAddresses} it provides. - * - * @see net.jxta.endpoint.EndpointAddress - * @see net.jxta.endpoint.MessageTransport - * @see net.jxta.endpoint.EndpointService - **/ -public interface MessageReceiver extends MessageTransport { - - /** - * Returns an Iterator of all of the - * {@link EndpointAddress EndpointAddresses} by which this - * MessageReceiver is reachable. The list is in order of - * "preference" with the most "preferred" EndpointAddress being at the - * beginning of the list. - * - * @return an Iterator of EndpointAddresses. - */ - public Iterator getPublicAddresses(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageSender.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageSender.java deleted file mode 100644 index 84fad198..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageSender.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -import java.io.IOException; - - -/** - * A MessageSender is a MessageTransport that is able to send messages to - * remote peers using some protocol. MessageSenders provide facilities for - * sending point-to-point (unicast) messages. - * - *

      MessageSenders additionally describe themselves in terms of their - * abilities. - *

      - *
      {@link #isConnectionOriented()}
      Indicates that the - * Message Transport can provide efficient transport of a series of messages to - * the same destination
      - *
      {link@ #allowRouting()}
      Indicates that the Message Transport - * can be used in the routing of messages to destinations which are not - * directly reachable via this transport.
      - *
      - * - * @see net.jxta.endpoint.MessageTransport - * @see net.jxta.endpoint.Message - * @see net.jxta.endpoint.Messenger - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.endpoint.MessageReceiver - * @see net.jxta.endpoint.MessagePropagater - */ -public interface MessageSender extends MessageTransport { - - /** - * Returns the {@link EndpointAddress} which will be used as the source - * address for all messages sent by this message sender. This is the - * "preferred" address to which replies should be sent. This address is not - * necessarily the best or only address by which the peer may be reached. - * - *

      The public address may also be for a different message transport. - * - * @return an EndpointAddress containing the public address for this - * message receiver. - */ - public EndpointAddress getPublicAddress(); - - /** - * Returns {@code true} if the Message Transport is connection oriented - * (like TCP/IP). Indicates that the Message Transport can provide - * efficient transport of a series of messages to the same destination. - * - * @return {@code true} if the Message Transport is connection oriented. - */ - public boolean isConnectionOriented(); - - /** - * Returns true if the Message Transport can be used by the EndpointRouter. - * Indicates that the Message Transport can be used in the routing of - * messages to destinations which are not directly reachable via this - * transport. - * - *

      More specifically, this Message Transport will be used to route - * messages who's final destination is not one of the endpoint - * addresses available from {@code getReachableEndpointAddresses}. - * - * @return true if the protocol can be used by the EndpointRouter - */ - public boolean allowsRouting(); - - /** - * Return a {@link Messenger} for sending messages to the specified - * destination {@link EndpointAddress}. - * - @param dest The destination address for which a messenger is requested. - * @param hint An optional hint for the transport to use when creating the - * messenger. The format of the hint is specific to each Message Transport - * and may be {@code null} if no hint is provided. - * @return a Messenger or {@code null} if the destination is not reachable. - */ - public Messenger getMessenger(EndpointAddress dest, Object hint); - - /** - * Returns {@code true} if the specified destination address is reachable - * via this Message Transport otherwise returns {@code false}. - * - * @deprecated This operation is often very expensive and usually - * duplicates the work of {@link #getMessenger}. If you want to determine - * the reachability of a destination, get a Messenger to the destination. - * - * @param addr Address to ping - * @return {@code true} if the specified destination address is reachable - * via this Message Transport otherwise returns {@code false}. - */ - @Deprecated - public boolean ping(EndpointAddress addr); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageTransport.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageTransport.java deleted file mode 100644 index 36584cae..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessageTransport.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -/** - * A MessageTransport is responsible for sending and/or receiving JXTA - * messages from an external network. A MessageTransport may use whatever - * protocol it wishes in transporting messages. Messages passed to - * MessageTransports are required to pass the messages cleanly (unaltered). - * - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.endpoint.EndpointAddress - * @see net.jxta.endpoint.MessageSender - * @see net.jxta.endpoint.MessageReceiver - */ -public interface MessageTransport { - - /** - * Returns a String containing the name of the protocol used by this - * MessageTransport. The value will match the "protocol" portion of all - * {@link EndpointAddress}. - * - * @return a String containing the name of the protocol used by this - * MessageTransport. - */ - public String getProtocolName(); - - /** - * Returns the endpoint service with which this MessageTransport is - * registered. If it is unregistered then null will be returned. - * - * @return the EndpointService with which this MessageTransport is - * registered. - */ - public EndpointService getEndpointService(); - - /** - * Pass a transport control object to a message transport. - * - * @param operation Object that specifies the type of control operation - * to be performed - * @param value Object that specifies a value object associated - * with the control operation - * @return returned object - * @deprecated Under development, may change. - */ - @Deprecated - public Object transportControl(Object operation, Object value); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/Messenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/Messenger.java deleted file mode 100644 index 34b16337..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/Messenger.java +++ /dev/null @@ -1,696 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -import net.jxta.peergroup.PeerGroupID; -import net.jxta.util.SimpleSelectable; - -import java.io.IOException; - - -/** - * A Messenger is used to send messages to a destination. - *

      - * This interface specifies the allowed observable states for a messenger. (fine grain). This serves to normalize - * the state machines of the various messenger implementations and allows for more meaningful diagnostics. Implementations may - * use substates by adding high order bits, but these should never be reported by the public state observation methods. Most - * implementations will not use all these states. - *

      - *

      Each valid state is represented by a integer that is a power of 2. - *

      - *

      The (coarse grain) constants: USABLE, RESOLVED, TERMINAL, IDLE, SATURATED represent meaningful partitions of the space of - * states. - *

      - *

      The value of each constant is the bitwise OR of the states for which a given predicate is true: usable or not, - * confirmed or not, etc. Therefore the value of predicate p in state s is (s & p)!=0. - *

      - *

      These particular predicates are chosen so that they have a relevant truth value for all states. Therefore the bitwise negation - * of the corresponding constants represents the obvious: ~USABLE really lists all states that mean "not USABLE". - *

      - *

      These constants may be combined by bit logic operators to represent more predicates. {@link #waitState} accepts such values as - * a parameter. - *

      - *

      Applications should depend on the coarse grain constants, rather than those denoting discrete states. - * - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.util.SimpleSelector - * @see net.jxta.endpoint.EndpointAddress - * @see net.jxta.endpoint.Message - * @see MessengerState - */ -public interface Messenger extends SimpleSelectable { - - /** - * No message was ever submitted for sending. No connection has ever been attempted. - */ - public static final int UNRESOLVED = 0x1; - - /** - * Initial connection is being attempted. No message is pending. - */ - public static final int RESOLVING = 0x2; - - /** - * Currently connected. No message is pending (being sent implies pending). - */ - public static final int CONNECTED = 0x4; - - /** - * Currently not connected. No message is pending. - */ - public static final int DISCONNECTED = 0x8; - - /** - * Initial connection is being attempted. Messages are pending. - */ - public static final int RESOLPENDING = 0x10; - - /** - * Initial connection is being attempted. Messages are pending. New messages may not be submitted at this time. - */ - public static final int RESOLSATURATED = 0x20; - - /** - * Currently connected and sending messages. - */ - public static final int SENDING = 0x40; - - /** - * Currently sending messages.New messages may not be submitted at this time. - */ - public static final int SENDINGSATURATED = 0x80; - - /** - * Currently trying to re-establish connection. Messages are pending. - */ - public static final int RECONNECTING = 0x100; - - /** - * Currently trying to re-establish connection. New messages may not be submitted at this time. - */ - public static final int RECONSATURATED = 0x200; - - /** - * Attempting initial connection. Close has been requested. Messages are pending. - * New messages may no longer be submitted. - */ - public static final int RESOLCLOSING = 0x400; - - /** - * Currently sending messages. Close has been requested. New messages may no longer be submitted. - */ - public static final int CLOSING = 0x800; - - /** - * Trying to re-establish connection. Close has been requested. Messages are pending. - * New messages may no longer be submitted. - */ - public static final int RECONCLOSING = 0x1000; - - /** - * Failed to establish initial connection. Pending messages are being rejected. New messages may no longer be submitted. - */ - public static final int UNRESOLVING = 0x2000; - - /** - * Failed to re-establish connection. Pending messages are being rejected. New messages may no longer be submitted. - */ - public static final int BREAKING = 0x4000; - - /** - * Breaking established connection for expedite closure. Pending messages are being rejected. - * New messages may no longer be submitted. - */ - public static final int DISCONNECTING = 0x8000; - - /** - * Failed to establish initial connection. New messages may no longer be submitted. State will never change again. - */ - public static final int UNRESOLVABLE = 0x10000; - - /** - * Failed to re-establish connection. New messages may no longer be submitted. State will never change again. - */ - public static final int BROKEN = 0x20000; - - /** - * Closed as requested. All pending messages could be sent. New messages may no longer be submitted. - * State will never change again. - */ - public static final int CLOSED = 0x40000; - - /** - * The bitwise OR of all valid states. - */ - public static final int ANYSTATE = 0x7FFFF; - - /* Predicates. */ - - /** - * Composite state.

      - *

      - * Not known to be broken. - * Messenger may be used to send messages. Viability has not been evaluated yet. - * This is the most useful predicate to applications. USABLE means that - * it is reasonable to try and send a message. - */ - public static final int USABLE = (UNRESOLVED | RESOLVING | CONNECTED | DISCONNECTED | RESOLPENDING | RESOLSATURATED | SENDING - | SENDINGSATURATED | RECONNECTING | RECONSATURATED); - - /** - * Composite state. - *

      - *

        - *
      • Messenger was once resolved.

        - *
      • Messenger was at least once proven viable. Current usability is - * not asserted. For example a messenger may be found to be in a - * TERMINAL state, but also be in a RESOLVED state. Thus proving that - * the destination of the messenger is sometimes valid.
      • - *
      - */ - public static final int RESOLVED = (CONNECTED | SENDING | SENDINGSATURATED | CLOSING | CLOSED | DISCONNECTED | RECONNECTING - | RECONSATURATED | RECONCLOSING | BREAKING | DISCONNECTING | BROKEN); - - /** - * Composite state. - *

      - * Messenger has terminated its useful life. State will never change any more. - */ - public static final int TERMINAL = (UNRESOLVABLE | CLOSED | BROKEN); - - /** - * Composite state. - *

      - * Any message that may have been submitted in the past has been either sent or failed already. - * If a messenger is in a state IDLE & RESOLVED & USABLE, then the expected delay in sending a message - * is minimal. - */ - public static final int IDLE = (UNRESOLVED | RESOLVING | CONNECTED | DISCONNECTED | UNRESOLVABLE | CLOSED | BROKEN); - - /** - * Composite state. - *

      - * This messenger cannot take new messages for now. All available buffering space is occupied. - * Note that only the usable states can be saturated. Once a messenger is in the process of terminating - * and thus takes no new messages anyway, it no-longer shows as saturated. - */ - public static final int SATURATED = (RESOLSATURATED | SENDINGSATURATED | RECONSATURATED); - - /** - * Returns the current state. - * - * @return one of the legal discrete state values. - */ - public int getState(); - - /** - * Blocks unless and until the current state is or has become one of the desired values. The observable states are guaranteed - * to be represented by a single bit. Multiple desired values may be specified by passing them ORed together. - *

      - * This class defines the list of constants that may be used and how these may be combined. - *

      - * Note that the state can change as soon as this method returns, so any observation is only an indication of the - * past. Synchronizing on the object itself has no other effect than interfering with other threads doing the same. Obviously, - * certain transitions cannot happen unless a new message is submitted. So unless another thread is using a messenger, it is - * safe to assume that a non-saturated messenger will not become saturated spontaneously. Note that messengers returned by - * different endpoint service interface objects (what {@link net.jxta.peergroup.PeerGroup#getEndpointService()} returns) are - * different. However a given endpoint interface object will return an existing messenger to the same exact destination if - * there is a {@link Messenger#USABLE} one. - *

      - * With an unshared messenger, one can wait for any change with {@code waitState(~getState(), 0);}. - *

      - * Note that it is advisable to always include {@link #TERMINAL} as part - * of the desired states with unless being blocked past the messenger - * termination is an acceptable behaviour. - *

      - * Examples:

      - *

      - * Ensure that the messenger can take more messages (or is {@code UNUSABLE}): {@code waitState(~SATURATED)}

      - *

      - * Ensure that all submitted messages have been sent: {@code waitState(TERMINAL | IDLE)} - *

      - * Ensure that the messenger is already resolved and can take more messages: {@code waitState(TERMINAL | (RESOLVED & ~SATURATED))} - * - * @param wantedStates The binary OR of the desired states. - * @param timeout The maximum number of milliseconds to wait. A timeout of 0 means no time limit. - * @return The desired state that was reached or the current state when time ran out. - * @throws InterruptedException If the invoking thread was interrupted before the condition was realized. - */ - int waitState(int wantedStates, long timeout) throws InterruptedException; - - /** - * Returns {@code true} if this messenger is closed and no longer - * accepting messages to be sent. This is a shortcut for - * {@code (getState() & USABLE == 0)}. Once closed, a messenger should be - * discarded. - * - * @return {@code true} if this messenger is closed, otherwise {@code false}. - */ - boolean isClosed(); - - /** - * Returns an indication of whether this messenger may be worth closing. - * - * @return {@code true} if the messenger is idle otherwise {@code false}. - * @deprecated no longer relevant and always false. This notably is not equivalent to the {@link #IDLE} state. - */ - @Deprecated - boolean isIdle(); - - /** - * Returns {@code true} if the sendMessage methods of - * this messenger are fully synchronous. - * - * @deprecated all messengers are asynchronous, and the {@link #sendMessageB} method is always blocking. - * - * @return true if synchronous - */ - @Deprecated - boolean isSynchronous(); - - /** - * Returns the destination of this messenger. - * - * @return The destination address of this messenger - * @see Messenger#getLogicalDestinationAddress() - */ - EndpointAddress getDestinationAddress(); - - /** - * Returns the internal EndpointAddress object of the destination of the user. - * This method is intended to be used for applications that require a weak - * or soft reference to an EndpointMessenger: the returned Endpoint Address - * object will be unreferenced when this messenger will finalize. - * - * @deprecated EndpointAddress is now immutable which means that this result - * is the same as {@link #getDestinationAddress()}. This method will be - * eventually removed. - * - * @return EndpointAddress the destination address of this messenger - * @see #getDestinationAddress() - */ - @Deprecated - EndpointAddress getDestinationAddressObject(); - - /** - * Returns the logical destination of this messenger. This may be a - * different address than is returned by - * {@link #getDestinationAddress() getDestinationAddress} and refers to - * the entity which is located at the destination address. - *

      - * By analogy, a telephone number would be the destination address, and - * the owner of that telephone number would be the logical destination. - * Each logical destination may be known by one or more destination - * addresses. - * - * @return EndpointAddress the logical destination address of this messenger. - * @see #getDestinationAddress() - */ - EndpointAddress getLogicalDestinationAddress(); - - /** - * Returns the maximum message size that this messenger can be used to send. - * The limit refers to the cumulative size of application level elements. - * The various {@code sendMessage()} variants will refuse to send messages - * that exceed this limit. - * - * @return the limit. - */ - long getMTU(); - - /** - * If applicable, returns another messenger that will send messages to the same destination address than this one, but with - * the specified default service and serviceParam, possibly rewriting addresses to ensure delivery through the specified - * redirection. This is not generally useful to applications and most messengers will return null. This method is needed - * by the EndpointService when interacting with Messengers provided by Transport modules. If you are not implementing a - * Transport module, then you can ignore this method. - *

      - * Important: The channel so obtained is not configured to support the {@link #sendMessage(Message,String,String, - *OutgoingMessageEventListener)} legacy method. If use of this method is desired, {@link ChannelMessenger#setMessageWatcher} - * must be used first. - * - * @param redirection The requested redirection. The resulting channel messenger will use this to force - * delivery of the message only in the specified group (or possibly descendents, but not parents). If null the local - * group is assumed. This redirection is applied only to messages that are sent to a service name and service param that - * do not imply a group redirection. - * @param service The service to which the resulting channel will send messages, when they are not sent to a - * specified service. - * @param serviceParam The service parameter that the resulting channel will use to send messages, when no parameter is - * specified. - * @return a channelMessenger as specified. - * @see MessageSender#getMessenger(EndpointAddress,Object) - */ - Messenger getChannelMessenger(PeerGroupID redirection, String service, String serviceParam); - - /** - * Close this messenger after processing any pending messages. This method - * is not blocking. Upon return, the messenger will be in one of the non - * {@link #USABLE} states, which means that no message may be sent through - * it. Any other effect of this method, such as an underlying connection - * being closed, or all pending messages being processed, may be deferred - * indefinitely. When the messenger has completely processed the closure - * request, it will be in one of the {@link #TERMINAL} states (which are - * also {@link #IDLE} states). Therefore, if one is interested in the - * outcome of the closure, one may wait for the messenger to be in a - * {@link #TERMINAL} or {@link #IDLE} state, and check which it is. - * {@link #CLOSED} denotes success (all outstanding messages have been - * sent), as opposed to {@link #UNRESOLVABLE} or {@link #BROKEN}. - */ - void close(); - - /** - * Makes sure that all outstanding messages have been processed; - * successfully or not. This method waits unless and until the state of the - * messenger is an {@link #IDLE} state. If the reached state is neither - * {@link #CLOSED} or any {@link #USABLE} state, then it throws an - * IOException. Else it returns silently.

      - * - *

      If another thread keeps sending messages, this method may never - * return. - * - *

      This method is deliberately simple. If a timeout needs to be - * provided, or if more detailed conditions are required, the - * {@link #waitState(int,long)} and {@link #getState()} methods should be - * used. For example : - * - *

      -     * int myFlush(long notTooLong) {
      -     *   messenger.waitState(IDLE, notTooLong);
      -     *   if ((messenger.getState() & IDLE) == 0) return TOOLONG;
      -     *   if ((messenger.getState() & USABLE) != 0) return FLUSHED;
      -     *   if (messenger.getState() == CLOSED) return CLOSEDANDFLUSHED;
      -     *   return BROKEN;
      -     * }
      -     * 
      - * - *

      Note: {@link #close()} being asynchronous, it is valid to invoke - * flush() after close() as a form of synchronous - * variant of close(). If this messenger is not shared with any - * other thread, then invoking flush() before - * close is a more familiar means of achieving the same effect. - * - * @throws IOException This messenger failed before processing all - * outstanding messages successfully. - */ - void flush() throws IOException; - - /** - * Force the messenger to start resolving if it is not resolved yet. Any - * attempt at sending a message has the same effect, but the message may - * fail as a result, depending upon the method used. - */ - void resolve(); - - /** - * Simple sending: blocks until the message was accepted for sending or the messenger is not {@link #USABLE}; whichever occurs - * first. If a service name and service param are specified, they will replace those specified at construction for the - * purpose of sending this message only.

      - *

      - * Error Handling: - *

      - *

        - *
      • An {@link java.io.IOException} means that this message is invalid or that this messenger is now in one of the non {@link - * #USABLE} states and may no longer send new messages, and means that the message was not sent. The exact state of the - * messenger may be obtained from the {@link #getState()} method. If no exception is thrown, the message is accepted for - * sending and may or may not be fully processed.
      • - *

        - *

      • The invoker may have confirmation of completion by observing the message's properties. When the message has been - * fully processed, {@link Message#getMessageProperty(Object) Message#getMessageProperty(Messenger.class)} will return an - * object of class {@link OutgoingMessageEvent}. Changes in a message's set of properties may be tracked by selecting the - * message. If an exception was thrown, the message's properties will not be modified - *

        - *

      • There is no guarantee that the process of sending the message will not fail after that method returned. If this messenger - * subsequently reaches an {@link #IDLE} state that is either {@link #CLOSED} or a {@link #USABLE} state, then it may be inferred - * that all outstanding messages have been processed without this messenger detecting an error.
      • - *
      - *

      - *

      WARNING: The Message object should not be reused or modified until completely processed. Concurrent modification - * of a message while a messenger is sending the message will produce incorrect and unpredictable results. If completion is - * not monitored, the message should never be reused. If necessary, a clone of the message may be provided to - * {@link #sendMessageB}: - *

      - *

      -     *     messenger.sendMessageB( (Message) myMessage.clone(), theService, theParam );
      -     * 
      - *

      - * There is no guarantee that a message successfully sent will actually be received.

      - * - * @param msg the message - * @param service Optionally replaces the service in the destination - * address. If {@code null} then the destination address's default - * service will be used. If the empty string ("") is used then - * no service is included in the destination address. - * @param serviceParam Optionally replaces the service param in the - * destination address. If {@code null} then the destination address's - * default service parameter will be used. If the empty string ("") is used - * then no service param is included in the destination address. - * @throws IOException Thrown if the message cannot be sent. - */ - void sendMessageB(Message msg, String service, String serviceParam) throws IOException; - - /** - * Sends a message to the destination specified at construction. If a service name and service param are specified, they will - * replace those specified at construction for the purpose of sending this message only. - *

      - * This method is identical to {@link #sendMessage(Message,String,String)}, except that it does not throw an exception. The invoker - * has to retrieve a detailed status from the message if needed. - *

      - * Error Handling:

        - *
      • A return result of {@code false} indicates that the message was not accepted to be sent. This may be due to - * local resource limits being reached or to the messenger being in a state that is not {@link #USABLE} or to the message - * being invalid. The exact cause of the failure can be retrieved from the message by using - * {@link Message#getMessageProperty(Object) Message.getMessageProperty(Messenger.class)}. If appropriate, - * another attempt at sending the message, may be made after waiting for the congestion to clear (for example by using - * {@link #waitState(int,long)}).
      • - *

        - *

      • A return result of {@code true} indicates that the message was accepted for sending. It does not imply that - * the message will be sent or that the destination will receive the message. There will be no indication by this method - * of any errors in sending the message. If this messenger subsequently reaches an {@link #IDLE} state that is either {@link - * #CLOSED} or a {@link #USABLE} state, then it may be inferred that all outstanding messages have been processed without this - * messenger detecting an error.
      • - *

        - *

      • The invoker may have confirmation of completion (successful or not) by observing the message's properties. When the - * message has been fully processed, {@link Message#getMessageProperty(Object) Message.getMessageProperty(Messenger.class)} - * will return an object of class {@link OutgoingMessageEvent}. Changes in a message's set of properties may be tracked by - * selecting the message.
      • - *
      - *

      - *

      WARNING: The Message object should not be reused or modified until completely processed. Concurrent modification - * of a message while a messenger is sending the message will produce incorrect and unpredictable results. If completion is - * not monitored, the message should never be reused. If necessary, a clone of the message may be provided to - * {@link #sendMessageN}: - *

      - *

      -     *     messenger.sendMessageN( (Message) myMessage.clone(), theService, theParam );
      -     * 
      - *

      - * There is no guarantee that a message successfully sent will actually be received.

      - * - * @param msg The message to send. - * @param service Optionally replaces the service in the destination - * address. If {@code null} then the destination address's default - * service will be used. If the empty string ("") is used then - * no service is included in the destination address. - * @param serviceParam Optionally replaces the service param in the - * destination address. If {@code null} then the destination address's - * default service parameter will be used. If the empty string ("") is used - * then no service param is included in the destination address. - * @return boolean {@code true} if the message has been accepted for sending, otherwise {@code false}. - */ - boolean sendMessageN(Message msg, String service, String serviceParam); - - /** - * Sends a message to the destination specified at construction as if by - * invoking {@link #sendMessage(Message,String,String) sendMessage(msg, null, null)} - * - * @param msg The message to send. - * @return boolean {@code true} if the message has been accepted for sending, otherwise {@code false}. - * @throws IOException Thrown if the message cannot be sent. - */ - boolean sendMessage(Message msg) throws IOException; - - /** - * Sends a message to the destination specified at construction. If a service name and service param are specified, they will - * replace those specified at construction for the purpose of sending this message only. - *

      - * Error Handling: - *

      - *

        - *

        - *

      • An {@link java.io.IOException} means that this message is invalid or that this messenger is now in one of the - * non {@link #USABLE} states and may no longer send new messages, and that the message was not sent. The exact state of - * the messenger may be obtained from the {@link #getState()} method.
      • - *

        - *

      • A return result of {@code false} indicates that the message was not accepted to be sent. Usually this is due to - * local resource limits being reached. If needed, another attempt at sending the message, may be made after waiting for the - * congestion to clear (for example by using {@link #waitState(int,long)}).
      • - *

        - *

      • A return result of {@code true} indicates that the message was accepted for sending. It does not imply that - * the message will be sent or that the destination will receive the message. There will be no immediate indication of any - * errors in sending the message. If this messenger subsequently reaches an {@link #IDLE} state that is either {@link #CLOSED} - * or a {@link #USABLE} state, then it may be inferred that all outstanding messages have been processed without this - * messenger detecting an error.
      • - *

        - *

      • The invoker may have confirmation of completion by observing the message's properties. When the message has been fully - * processed, {@link Message#getMessageProperty(Object) Message.getMessageProperty(Messenger.class)} will return - * an object of class {@link OutgoingMessageEvent}. Changes in a message's set of properties may be tracked by selecting - * the message. - *

        - *

      - *

      - *

      WARNING: The Message object should not be reused or modified until completely processed. Concurrent modification - * of a message while a messenger is sending the message will produce incorrect and unpredictable results. If completion is - * not monitored, the message should never be reused. If necessary, a clone of the message may be provided to - * sendMessage: - *

      - *

      -     *     messenger.sendMessage( (Message) myMessage.clone(), theService, theParam );
      -     * 
      - *

      - * There is no guarantee that a message successfully sent will actually be received.

      - *

      - * Limitation: using this method along with {@link net.jxta.util.SimpleSelector#select} on the same message may occasionally - * cause some errors to not be thrown. Prefer {@link #sendMessageN} when using {@link net.jxta.util.SimpleSelector#select}. - *

      - * This is a legacy method. Modern code should prefer the other methods and select messages. - * - * @param msg The message to send. - * @param service Optionally replaces the service in the destination - * address. If {@code null} then the destination address's default - * service will be used. If the empty string ("") is used then - * no service is included in the destination address. - * @param serviceParam Optionally replaces the service param in the - * destination address. If {@code null} then the destination address's - * default service parameter will be used. If the empty string ("") is used - * then no service param is included in the destination address. - * @return boolean {@code true} if the message has been accepted for sending, otherwise {@code false}. - * @throws IOException Thrown if the message cannot be sent. - */ - boolean sendMessage(Message msg, String service, String serviceParam) throws IOException; - - /** - * Sends a message to the destination specified at construction. If a service name and service param are specified, they will - * replace those specified at construction for the purpose of sending this message only. - *

      - * WARNING: The Message object should not be reused or modified until the message has been fully processed. - * Concurrent modification of a message while a messenger is sending the message will produce incorrect and unpredictable - * results. If a listener is provided it is invoked after the message is considered fully processed. However it is recommended - * not to reuse or otherwise modify a messages after sending it. If necessary, a clone of the message may be provided to - * sendMessage: - *

      - *

      -     *     messenger.sendMessage( (Message) myMessage.clone() );
      -     * 
      - *

      - * Error Handling: - *

      - *

        - *

        - *

      • If a listener was provided, it will always be invoked. Depending upon the outcome either the - * {@link OutgoingMessageEventListener#messageSendFailed(OutgoingMessageEvent)} or the {@link - * OutgoingMessageEventListener#messageSendSucceeded(OutgoingMessageEvent)} method will be invoked:

        - *

        - *

          - *

          - *

        • If the message could not be accepted for sending due to temporary resource saturation, - * messageSendFailed will be invoked. The {@link Throwable} object returned by the {@link - * OutgoingMessageEvent#getFailure()} method of the passed event object will be null.
        • - *

          - *

        • If the message could not be accepted for sending due to the messenger not being {@link #USABLE}, - * messageSendFailed will be invoked. The {@link Throwable} object returned by the {@link - * OutgoingMessageEvent#getFailure()} method of the passed event object will reflect the messenger's condition.
        • - *

          - *

        • If the message is accepted for sending but later fails, then messageSendFailed will be invoked. The - * {@link Throwable} object returned by the {@link OutgoingMessageEvent#getFailure()} method of the passed event object - * will reflect the origin of the failure.
        • - *

          - *

        • If the message is accepted for sending and later succeeds, then messageSendSucceeded will be - * invoked.
        • - *

          - *

      • - *

        - *

      • If a listener was provided, it is always possible that it is invoked before this method returns.
      • - *

        - *

      • If no listener was provided, There will be no notification of any errors nor success in sending the message. If - * this messenger subsequently reaches an {@link #IDLE} state that is either {@link #CLOSED} or a {@link #USABLE} state, then it - * may be inferred that all outstanding messages have been processed without this messenger detecting an error.
      • - *

        - *

      • This method does not throw exceptions. As a result, when used with a {@code null} listener, it provides very - * little feedback to the invoker. A messenger should be abandoned once it is in one of the {@link #TERMINAL} states.
      • - *

        - *

      - *

      - * As with all sendMessage methods, success is not a guarantee that the message will actually be received. - *

      - *

      This is a legacy method. Modern code should prefer the other methods and select messages. If a listener API is preferred, it is possible to use a {@link ListenerAdaptor} object explicitly to have a listener called. - * - * @param msg The message to send. - * @param service Optionally replaces the service in the destination - * address. If {@code null} then the destination address's default - * service will be used. If the empty string ("") is used then - * no service is included in the destination address. - * @param serviceParam Optionally replaces the service param in the - * destination address. If {@code null} then the destination address's - * default service parameter will be used. If the empty string ("") is used - * then no service param is included in the destination address. - * @param listener listener for events about this message or null if no notification is desired. - * @throws UnsupportedOperationException If this messenger is not a channel or was not given a {@link ListenerAdaptor}. - * (all messengers obtained through {@link EndpointService#getMessenger} are configured properly. - */ - void sendMessage(Message msg, String service, String serviceParam, OutgoingMessageEventListener listener); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessengerEvent.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessengerEvent.java deleted file mode 100644 index bcf4b6a1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessengerEvent.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - -/** - * An event which indicates that a messenger has been successfully created. - *

      - * The source of Message Transport providing the messenger. - * - * @see net.jxta.endpoint.MessageTransport - * @see net.jxta.endpoint.Messenger - * @see net.jxta.endpoint.EndpointService - */ -public class MessengerEvent extends java.util.EventObject { - - /** - * The newly created messenger. - */ - final transient Messenger messenger; - - /** - * The destination address of the messenger. - */ - final EndpointAddress connectionAddress; - - /** - * Creates a new instance of MessengerEvent - * - * @param source The source of Message Transport providing the messenger - * @param messenger the messenger - * @param connectionAddress The connection address - */ - public MessengerEvent(Object source, Messenger messenger, EndpointAddress connectionAddress) { - super(source); - - this.messenger = messenger; - this.connectionAddress = connectionAddress; - } - - public Messenger getMessenger() { - return messenger; - } - - public EndpointAddress getConnectionAddress() { - return connectionAddress; - } - - /** - * {@inheritDoc} - *

      - * A simple implementation for debugging. Don't depend upon this format. - */ - @Override - public String toString() { - return source.toString() + "-->" + messenger.toString() + " (" + connectionAddress + ")"; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessengerEventListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessengerEventListener.java deleted file mode 100644 index 09896027..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessengerEventListener.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - -import java.util.EventListener; - -/** - * A listener for MessengerEvents. - */ -public interface MessengerEventListener extends EventListener { - - /** - * A messenger is ready. - * - * @param event The Messenger Event. - * @return {@code true} if the listener wants to claim the Messenger. - * (Normally means that it will not be offered to any other listener). - */ - public boolean messengerReady(MessengerEvent event); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessengerState.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessengerState.java deleted file mode 100644 index df7c1cd6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/MessengerState.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - -/** - * The complete standard messenger life cycle state machine that all messengers - * must obey. Compliant messengers can be built by implementing and using this - * class as an engine to orchestrate discrete operations. - *

      - * In order to use this class, one must implement the various abstract Action - * methods, so that they trigger the required operations. - *

      - * Synchronization has to be externally provided and usually needs to extend - * around sections wider than just the invocation of this class' methods. For - * example, if the user of this class maintains a queue, the state of the queue - * must be kept consistent with the invocation of {@link #msgsEvent}, - * {@link #saturatedEvent}, and {@link #idleEvent}, which all denote different - * states of that queue. It is suggested to use the instance of this class as - * the synchronization object. - */ -public abstract class MessengerState { - - // All the transition map setup is rather terse because java tends to make - // it extremely verbose. We do not want to end up with 1000 lines of code - // for what amounts to initializing a table. - - // Below is a method reference. It permits putting "what to do" in a field. - // The {@code doIt()} method is given the target object because we want our - // entire transition table to be a static singleton. Otherwise it would cost - // too much initializing each instance of this class. - - private interface Action { - public void doIt(MessengerState messengerState); - } - - // Action method "pointers". - // The transition table is static. Otherwise it would cost too much initializing each instance of this class. - - private final static Action Connect = new Action() { - public void doIt(MessengerState messengerState) { - messengerState.connectAction(); - } - }; - private final static Action Closein = new Action() { - public void doIt(MessengerState s) { - s.closeInputAction(); - } - }; - private final static Action Start = new Action() { - public void doIt(MessengerState s) { - s.startAction(); - } - }; - private final static Action Closeout = new Action() { - public void doIt(MessengerState messengerState) { - messengerState.closeOutputAction(); - } - }; - private final static Action Failall = new Action() { - public void doIt(MessengerState messengerState) { - messengerState.failAllAction(); - } - }; - private final static Action Closeio = new Action() { - public void doIt(MessengerState s) { - s.closeInputAction(); - s.closeOutputAction(); - } - }; - private final static Action Closefail = new Action() { - public void doIt(MessengerState messengerState) { - messengerState.closeInputAction(); - messengerState.failAllAction(); - } - }; - private final static Action Nop = new Action() { - public void doIt(MessengerState messengerState) { - } - }; - - /** - * The transition each event causes when in that state. - */ - private static class State { - private final int number; - - private State stResolve; - private Action acResolve; - - private State stMsgs; - private Action acMsgs; - - private State stSaturated; - private Action acSaturated; - - private State stClose; - private Action acClose; - - private State stShutdown; - private Action acShutdown; - - private State stUp; - private Action acUp; - - private State stDown; - private Action acDown; - - private State stIdle; - private Action acIdle; - - State(int stateNum) { - number = stateNum; - } - - void init(Object[] data) { - stResolve = (State) data[0]; - acResolve = (Action) data[1]; - stMsgs = (State) data[2]; - acMsgs = (Action) data[3]; - stSaturated = (State) data[4]; - acSaturated = (Action) data[5]; - stClose = (State) data[6]; - acClose = (Action) data[7]; - stShutdown = (State) data[8]; - acShutdown = (Action) data[9]; - stUp = (State) data[10]; - acUp = (Action) data[11]; - stDown = (State) data[12]; - acDown = (Action) data[13]; - stIdle = (State) data[14]; - acIdle = (Action) data[15]; - } - } - - - // All the states. (We put them together in a class essentially to simplify initialization). - private static class TransitionMap { - - private final static State Unresolved = new State(Messenger.UNRESOLVED); - private final static State ResPending = new State(Messenger.RESOLPENDING); - private final static State Resolving = new State(Messenger.RESOLVING); - private final static State ResolSat = new State(Messenger.RESOLSATURATED); - private final static State Connected = new State(Messenger.CONNECTED); - private final static State Disconned = new State(Messenger.DISCONNECTED); - private final static State Reconning = new State(Messenger.RECONNECTING); - private final static State ReconSat = new State(Messenger.RECONSATURATED); - private final static State Sending = new State(Messenger.SENDING); - private final static State SendingSat = new State(Messenger.SENDINGSATURATED); - private final static State ResClosing = new State(Messenger.RESOLCLOSING); - private final static State ReconClosing = new State(Messenger.RECONCLOSING); - private final static State Closing = new State(Messenger.CLOSING); - private final static State Disconning = new State(Messenger.DISCONNECTING); - private final static State Unresable = new State(Messenger.UNRESOLVABLE); - private final static State Closed = new State(Messenger.CLOSED); - private final static State Broken = new State(Messenger.BROKEN); - - // The states need to exist before init, because they refer to each other. - // We overwrite them in-place with the complete data. - - private final static Object[][] INIT_TRANSITION_MAP = { - - /* STATE resolve, msgs, saturated, close, shutdown, up, down, idle */ - - /* UNRESOLVED */ - {Resolving, Connect, ResPending, Connect, ResolSat, Connect, Closed, Closein, Broken, Closein, Connected, Nop, Unresolved, Nop, Unresolved, Nop}, - - /* RESOLPENDING */ - {ResPending, Nop, ResPending, Nop, ResolSat, Nop, ResClosing, Closein, Broken, Closefail, Sending, Start, Unresable, Closefail, Resolving, Nop}, - - /* RESOLVING */ - {Resolving, Nop, ResPending, Nop, ResolSat, Nop, Closed, Closein, Broken, Closein, Connected, Nop, Unresable, Closein, Resolving, Nop}, - - /* RESOLSATURATED */ - {ResolSat, Nop, ResPending, Nop, ResolSat, Nop, ResClosing, Closein, Broken, Closefail, SendingSat, Start, Unresable, Closefail, Resolving, Nop}, - - /* CONNECTED */ - {Connected, Nop, Sending, Start, SendingSat, Start, Closed, Closeio, Broken, Closeio, Connected, Nop, Disconned, Nop, Connected, Nop}, - - /* DISCONNECTED */ - {Disconned, Nop, Reconning, Connect, ReconSat, Connect, Closed, Closein, Broken, Closein, Connected, Nop, Disconned, Nop, Disconned, Nop}, - - /* RECONNECTING */ - {Reconning, Nop, Reconning, Nop, ReconSat, Nop, ReconClosing, Closein, Broken, Closefail, Sending, Start, Broken, Closefail, Disconned, Nop}, - - /* RECONSATURATED */ - {ReconSat, Nop, Reconning, Nop, ReconSat, Nop, ReconClosing, Closein, Broken, Closefail, SendingSat, Start, Broken, Closefail, Disconned, Nop}, - - /* SENDING */ - {Sending, Nop, Sending, Nop, SendingSat, Nop, Closing, Closein, Disconning, Closeio, Sending, Nop, Reconning, Connect, Connected, Nop}, - - /* SENDINGSATURATED*/ - {SendingSat, Nop, Sending, Nop, SendingSat, Nop, Closing, Closein, Disconning, Closeio, SendingSat, Nop, ReconSat, Connect, Connected, Nop}, - - /* RESOLCLOSING */ - {ResClosing, Nop, ResClosing, Nop, ResClosing, Nop, ResClosing, Nop, Broken, Failall, Closing, Start, Unresable, Failall, ResClosing, Nop}, - - /* RECONCLOSING */ - {ReconClosing, Nop, ReconClosing, Nop, ReconClosing, Nop, ReconClosing, Nop, Broken, Failall, Closing, Start, Broken, Failall, ReconClosing, Nop}, - - /* CLOSING */ - {Closing, Nop, Closing, Nop, Closing, Nop, Closing, Nop, Disconning, Closeout, Closing, Nop, ReconClosing, Connect, Closed, Closeout}, - - /* DISCONNECTING */ - {Disconning, Nop, Disconning, Nop, Disconning, Nop, Disconning, Nop, Disconning, Nop, Disconning, Nop, Broken, Failall, Broken, Nop}, - - /* UNRESOLVABLE */ - {Unresable, Nop, Unresable, Nop, Unresable, Nop, Unresable, Nop, Unresable, Nop, Unresable, Closeout, Unresable, Nop, Unresable, Nop}, - - /* CLOSED */ - {Closed, Nop, Closed, Nop, Closed, Nop, Closed, Nop, Closed, Nop, Closed, Closeout, Closed, Nop, Closed, Nop}, - - /* BROKEN */ - {Broken, Nop, Broken, Nop, Broken, Nop, Broken, Nop, Broken, Nop, Broken, Closeout, Broken, Nop, Broken, Nop} - }; - - static { - // install the transitions map in its proper place. - Unresolved.init(INIT_TRANSITION_MAP[0]); - ResPending.init(INIT_TRANSITION_MAP[1]); - Resolving.init(INIT_TRANSITION_MAP[2]); - ResolSat.init(INIT_TRANSITION_MAP[3]); - Connected.init(INIT_TRANSITION_MAP[4]); - Disconned.init(INIT_TRANSITION_MAP[5]); - Reconning.init(INIT_TRANSITION_MAP[6]); - ReconSat.init(INIT_TRANSITION_MAP[7]); - Sending.init(INIT_TRANSITION_MAP[8]); - SendingSat.init(INIT_TRANSITION_MAP[9]); - ResClosing.init(INIT_TRANSITION_MAP[10]); - ReconClosing.init(INIT_TRANSITION_MAP[11]); - Closing.init(INIT_TRANSITION_MAP[12]); - Disconning.init(INIT_TRANSITION_MAP[13]); - Unresable.init(INIT_TRANSITION_MAP[14]); - Closed.init(INIT_TRANSITION_MAP[15]); - Broken.init(INIT_TRANSITION_MAP[16]); - } - } - - /** - * The current state! - */ - private volatile State state = null; - - /** - * Constructs a new messenger state machine. - *

      - * The transition map is static and we refer to it only to grab the first - * state. After that, states refer to each other. The only reason they are - * members in the map is so that we can make references during init. - * - * @param connected If true, the initial state is {@link Messenger#CONNECTED} otherwise {@link Messenger#UNRESOLVED}. - */ - protected MessengerState(boolean connected) { - - state = connected ? TransitionMap.Connected : TransitionMap.Unresolved; - } - - /** - * @return The current state. - */ - public int getState() { - // getState is always just a peek. It needs no sync. - return state.number; - } - - /** - * Event input. - */ - public void resolveEvent() { - Action a = state.acResolve; - - state = state.stResolve; - a.doIt(this); - } - - /** - * Message event - */ - public void msgsEvent() { - Action a = state.acMsgs; - - state = state.stMsgs; - a.doIt(this); - } - - /** - * Saturated Event - */ - public void saturatedEvent() { - Action a = state.acSaturated; - - state = state.stSaturated; - a.doIt(this); - } - - /** - * Close Event - */ - public void closeEvent() { - Action a = state.acClose; - - state = state.stClose; - a.doIt(this); - } - - /** - * Shutdown Event - */ - public void shutdownEvent() { - Action a = state.acShutdown; - - state = state.stShutdown; - a.doIt(this); - } - - /** - * Up Event - */ - public void upEvent() { - Action a = state.acUp; - - state = state.stUp; - a.doIt(this); - } - - /** - * Down Event - */ - public void downEvent() { - Action a = state.acDown; - - state = state.stDown; - a.doIt(this); - } - - /** - * Idle Event - */ - public void idleEvent() { - Action a = state.acIdle; - - state = state.stIdle; - a.doIt(this); - } - - /** - * Actions they're always called in sequence by event methods. - * - * Actions must not call event methods in sequence. - **/ - - /** - * Try to make a connection. Called whenever transitioning from a state that neither needs nor has a connection to a state - * that needs a connection and does not have it. Call upEvent when successful, or downEvent when failed. - */ - protected abstract void connectAction(); - - /** - * Start sending. Called whenever transitioning to a state that has both a connection and messages to send from a state that - * lacked either attributes. So, will be called after sending stopped due to broken cnx or idle condition. Call downEvent - * when stopping due to broken or closed connection, call {@link #idleEvent} when no pending message is left. - */ - protected abstract void startAction(); - - /** - * Reject new messages from now on. Called whenever transitioning from a state that is {@link Messenger#USABLE} to a state - * that is not. No event expected once done. - */ - protected abstract void closeInputAction(); - - /** - * Drain pending messages, all failed. Called once output is down and there are still pending messages. - * Call {@link #idleEvent} when done, as a normal result of no pending messages being left. - */ - protected abstract void failAllAction(); - - /** - * Force close output. Called whenever the underlying connection is to be discarded and never to be needed again. That is - * either because orderly close has completed, or shutdown is in progress. No event expected once done, but this action - * must cause any sending in progress to stop eventually. The fact that the sending has stopped must be reported as - * usual: either with a {@link #downEvent}, if the output closure caused the sending process to fail, or with an {@link - * #idleEvent} if the sending of the last message could be sent successfully despite the attempt at interrupting it. - *

      - * Sending is said to be in progress if, and only if, the last call to startAction is more recent than the last call to - * {@link #idleEvent} or {@link #downEvent}. - *

      - * It is advisable to also cancel an ongoing connect action, but not mandatory. If a {@link #connectAction} later succeeds, - * then {@link #upEvent} must be called as usual. This will result in another call to {@link #closeOutputAction}. - */ - protected abstract void closeOutputAction(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/OutgoingMessageEvent.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/OutgoingMessageEvent.java deleted file mode 100644 index 47133f16..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/OutgoingMessageEvent.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - -/** - * An event which provides notification of the the transmission status of an - * outgoing message. The source of the event is the Message object. - */ -public class OutgoingMessageEvent extends java.util.EventObject { - - // Two low-cost msg events for reporting to selectors: success does not require an exception. An exception is too expensive - // for overflow. The message component is useless for select but we need a dummy src in order to construct an Event. Note, - // to convert OVERFLOW or SUCCESS to listener-compatible events, clone them and set the message member. Other events are - // already all right. - public static final OutgoingMessageEvent SUCCESS = new OutgoingMessageEvent(); - public static final OutgoingMessageEvent OVERFLOW = new OutgoingMessageEvent(); - - private Throwable failure = null; - - /** - * Create an Outgoing Message Event with a dummy src (message - * is not specified because the event is a constant). - */ - public OutgoingMessageEvent() { - super("Unspecified"); - } - - /** - * Create an Outgoing Message Event. - * - * @param source the message for which the event is occurring. - */ - public OutgoingMessageEvent(Message source) { - super(source); - } - - /** - * Create an Outgoing Message Event. - * - * @param source The message for which the event is occurring. - * @param failure The failure associated with this event. - */ - public OutgoingMessageEvent(Message source, Throwable failure) { - super(source); - this.failure = failure; - } - - /** - * Get the failure associated with this event, if any. - * - * @return the Throwable associated with the failure, if any. - * null if there was no associated failure. - */ - public Throwable getFailure() { - return failure; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/OutgoingMessageEventListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/OutgoingMessageEventListener.java deleted file mode 100644 index 9b458e14..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/OutgoingMessageEventListener.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - -/** - * A listener for events concerning the status of outgoing messages. - */ -public interface OutgoingMessageEventListener extends java.util.EventListener { - - /** - * The message identified by the event could not be sent. - *

      - * The cause of the failure, if any, is available from - * {@link OutgoingMessageEvent#getFailure()}. Failures while sending - * messages have several causes : - *

      - *

        - *
      • An {@link java.io.IOException} means that the messenger cannot - * send the message and the messenger will accept no further messages - * to be sent.
      • - *

        - *

      • A {@link java.lang.RuntimeException} mean that the message was - * not sent, but retries may or may not be possible based upon the - * status returned by {@link Messenger#isClosed()}.
      • - *

        - *

      • null means that the message was not sent, but may - * be retried. Usually the failure is due to local resource limits - * being exceeded. Attempts may be made to later resend the message, - * usually after waiting for congestion to clear.
      • - *
      - * @param event the event - */ - void messageSendFailed(OutgoingMessageEvent event); - - /** - * The message identified by the event was successfully sent. Successfully - * sending a message is not a guarantee that it will be successfully - * received by the destination. - * @param event the event - */ - void messageSendSucceeded(OutgoingMessageEvent event); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/StringMessageElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/StringMessageElement.java deleted file mode 100644 index 43254243..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/StringMessageElement.java +++ /dev/null @@ -1,546 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - - -import net.jxta.document.MimeMediaType; -import net.jxta.logging.Logging; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.Reader; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.lang.ref.SoftReference; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * A Message Element using character strings for the element data. - */ -public class StringMessageElement extends TextMessageElement { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(StringMessageElement.class.getName()); - - /** - * The MIME media type we will be use for encoding {@code String}s when no - * encoding is specified. - */ - private static final MimeMediaType DEFAULT_TEXT_ENCODING = new MimeMediaType(MimeMediaType.TEXT_DEFAULTENCODING, "charset=\"" + Charset.defaultCharset().name() + "\"", true).intern(); - - /** - * The data for this Message Element. - */ - protected String data; - - /** - * Returns an appropriate mime type for the given encoding name. The - * mimetype will contain the canonical name of the encoding. - * - * @param encoding name of the desired encoding. - * @return the mime type. - * @throws java.io.UnsupportedEncodingException - * if the mime is unsupported - */ - private static MimeMediaType makeMimeType(String encoding) throws UnsupportedEncodingException { - InputStreamReader getEncoding = new InputStreamReader(new ByteArrayInputStream(new byte[0]), encoding); - - String canonicalName = getEncoding.getEncoding(); - - return new MimeMediaType(MimeMediaType.TEXT_DEFAULTENCODING, "charset=\"" + canonicalName + "\"", true).intern(); - } - - /** - * Create a new Message Element from the provided String. The String will - * be encoded for transmission using UTF-8. - * - * @param name Name of the Element. May be the empty string ("") or null if - * the Element is not named. - * @param value A String containing the contents of this element. - * @param sig Message digest/digital signature element. If no signature is - * to be specified, pass null. - * @throws IllegalArgumentException if value is - * null. - */ - public StringMessageElement(String name, String value, MessageElement sig) { - super(name, MimeMediaType.TEXTUTF8, sig); - - if (null == value) { - throw new IllegalArgumentException("value must be non-null"); - } - - data = value; - } - - /** - * Create a new Message Element from the provided String. The string will - * be encoded for transmission using specified character encoding. - * - * @param name Name of the MessageElement. May be the empty string ("") or - * null if the MessageElement is not named. - * @param value A String containing the contents of this element. - * @param encoding Name of the character encoding to use. If - * null then the system default character encoding will be - * used. (Using the system default character encoding should be used with - * extreme caution). - * @param sig Message digest/digital signature element. If no signature is - * to be specified, pass null. - * @throws IllegalArgumentException if value is - * null. - * @throws UnsupportedEncodingException if the requested encoding is not - * supported. - */ - public StringMessageElement(String name, String value, String encoding, MessageElement sig) throws UnsupportedEncodingException { - super(name, (null == encoding) ? DEFAULT_TEXT_ENCODING : makeMimeType(encoding), sig); - - if (null == value) { - throw new IllegalArgumentException("value must be non-null"); - } - - data = value; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof MessageElement) { - if (!super.equals(target)) { - return false; - } - - if (target instanceof StringMessageElement) { - StringMessageElement likeMe = (StringMessageElement) target; - - return data.equals(likeMe.data); // same chars? - } else if (target instanceof TextMessageElement) { - // have to do a slow char by char comparison. Still better than the stream since it saves encoding. - // XXX 20020615 bondolo@jxta.org the performance of this could be much improved. - - TextMessageElement likeMe = (TextMessageElement) target; - - try { - Reader myReader = getReader(); - Reader itsReader = likeMe.getReader(); - - int mine; - int its; - - do { - mine = myReader.read(); - its = itsReader.read(); - - if (mine != its) { - return false; - } // content didn't match - - } while ((-1 != mine) && (-1 != its)); - - return ((-1 == mine) && (-1 == its)); // end at the same time? - } catch (IOException fatal) { - IllegalStateException failure = new IllegalStateException("MessageElements could not be compared."); - - failure.initCause(fatal); - throw failure; - } - } else { - // have to do a slow stream comparison. - // XXX 20020615 bondolo@jxta.org the performance of this could be much improved. - - MessageElement likeMe = (MessageElement) target; - - try { - InputStream myStream = getStream(); - InputStream itsStream = likeMe.getStream(); - - int mine; - int its; - - do { - mine = myStream.read(); - its = itsStream.read(); - - if (mine != its) { - return false; - } // content didn't match - - } while ((-1 != mine) && (-1 != its)); - - return ((-1 == mine) && (-1 == its)); // end at the same time? - } catch (IOException fatal) { - IllegalStateException failure = new IllegalStateException("MessageElements could not be compared."); - - failure.initCause(fatal); - throw failure; - } - } - } - - return false; // not a new message element - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = super.hashCode() * 6037 + // a prime - data.hashCode(); - - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return data; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized byte[] getBytes(boolean copy) { - byte[] cachedBytes = null; - - if (null != cachedGetBytes) { - cachedBytes = cachedGetBytes.get(); - } - - if (null == cachedBytes) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "Creating getBytes of " + getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(this))); - } - - String charset = type.getParameter("charset"); - - try { - cachedBytes = data.getBytes(charset); - } catch (UnsupportedEncodingException caught) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "MessageElement Data could not be generated", caught); - } - IllegalStateException failure = new IllegalStateException("MessageElement Data could not be generated"); - - failure.initCause(caught); - throw failure; - } - - cachedGetBytes = new SoftReference(cachedBytes); - } - - if (!copy) { - return cachedBytes; - } - - byte[] bytesCopy = cachedBytes.clone(); - - return bytesCopy; - } - - /** - * {@inheritDoc} - */ - @Override - public long getCharLength() { - return data.length(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized char[] getChars(boolean copy) { - char[] cachedChars = null; - - if (null != cachedGetChars) { - cachedChars = cachedGetChars.get(); - } - - if (null == cachedChars) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("creating cachedGetChars of " + getClass().getName() + '@' + Integer.toHexString(hashCode())); - } - - cachedChars = new char[data.length()]; - - data.getChars(0, data.length(), cachedChars, 0); - - // if this is supposed to be a shared buffer then we can cache it. - - cachedGetChars = new SoftReference(cachedChars); - } - - if (!copy) { - return cachedChars; - } - - char[] copyChars = cachedChars.clone(); - - return copyChars; - } - - /** - * {@inheritDoc} - */ - public InputStream getStream() throws IOException { - byte cachedBytes[] = null; - - synchronized (this) { - if (null != cachedGetBytes) { - cachedBytes = cachedGetBytes.get(); - } - } - - if (null != cachedBytes) { - return new ByteArrayInputStream(cachedBytes); - } else { - String charset = type.getParameter("charset"); - return new CharSequenceInputStream(data, charset); - } - } - - /** - * {@inheritDoc} - * - * @return InputStream of the stream containing element data. - * @throws IOException when there is a problem getting a reader. - */ - public Reader getReader() throws IOException { - - return new StringReader(data); - } - - /** - * {@inheritDoc} - */ - @Override - public void sendToStream(OutputStream sendTo) throws IOException { - - sendTo.write(getBytes(false)); - } - - /** - * {@inheritDoc} - */ - @Override - public void sendToWriter(Writer sendTo) throws IOException { - sendTo.write(data); - } - - /** - * - **/ - private static class CharSequenceInputStream extends InputStream { - - private final CharBuffer charData; - - private final CharsetEncoder conversion; - - private boolean marked = false; - private byte mark_multiByteChar[]; - private int mark_position; - - private byte multiByteChar[]; - private int position; - - /** - * @param s the char sequence - * @param encoding the charset encoding - */ - CharSequenceInputStream(CharSequence s, String encoding) { - charData = CharBuffer.wrap(s); - - Charset encodingCharset = Charset.forName(encoding); - - conversion = encodingCharset.newEncoder(); - conversion.onMalformedInput(CodingErrorAction.REPLACE); - conversion.onUnmappableCharacter(CodingErrorAction.REPLACE); - - int maxBytes = new Float(conversion.maxBytesPerChar()).intValue(); - - multiByteChar = new byte[maxBytes]; - position = multiByteChar.length; - } - - /** - * {@inheritDoc} - */ - @Override - public void mark(int ignored) { - charData.mark(); - mark_multiByteChar = multiByteChar.clone(); - mark_position = position; - marked = true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean markSupported() { - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public void reset() throws IOException { - - if (!marked) { - throw new IOException("reset() called before mark()"); - } - - charData.reset(); - multiByteChar = mark_multiByteChar.clone(); - position = mark_position; - } - - /** - * {@inheritDoc} - */ - @Override - public int read() throws IOException { - // prefill the buffer - while (multiByteChar.length == position) { - int readsome = read(multiByteChar, 0, multiByteChar.length); - - if (-1 == readsome) { - return -1; - } - - position = multiByteChar.length - readsome; - - if ((0 != position) && (0 != readsome)) { - System.arraycopy(multiByteChar, 0, multiByteChar, position, readsome); - } - } - - return (multiByteChar[position++] & 0xFF); - } - - /** - * {@inheritDoc} - */ - @Override - public int read(byte[] buffer) throws IOException { - return read(buffer, 0, buffer.length); - } - - /** - * {@inheritDoc} - */ - @Override - public int read(byte[] buffer, int offset, int length) throws IOException { - // handle partial characters; - if (multiByteChar.length != position) { - int copying = Math.min(length, multiByteChar.length - position); - - System.arraycopy(multiByteChar, position, buffer, offset, copying); - position += copying; - return copying; - } - - ByteBuffer bb = ByteBuffer.wrap(buffer, offset, length); - - int before = bb.remaining(); - - CoderResult result = conversion.encode(charData, bb, true); - - int readin = before - bb.remaining(); - - if (CoderResult.UNDERFLOW == result) { - if (0 == readin) { - return -1; - } else { - return readin; - } - } - - if (CoderResult.OVERFLOW == result) { - return readin; - } - - result.throwException(); - - // NEVERREACHED - return 0; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/TextDocumentMessageElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/TextDocumentMessageElement.java deleted file mode 100644 index 763c257d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/TextDocumentMessageElement.java +++ /dev/null @@ -1,358 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - - -import net.jxta.document.MimeMediaType; -import net.jxta.document.TextDocument; -import net.jxta.logging.Logging; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.lang.ref.SoftReference; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * A Message Element using JXTA TextDocument for the element data. - */ -public class TextDocumentMessageElement extends TextMessageElement { - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(TextDocumentMessageElement.class.getName()); - - /** - * The data for this element. - */ - protected TextDocument doc; - - /** - * Create a new Message Element from the provided Document. - * - * @param name Name of the Element. May be the empty string ("") or null if - * the Element is not named. - * @param doc A Document containing the contents of this element. - * @param sig optional message digest/digital signature elemnent. If - * no signature is to be specified, pass null. - */ - public TextDocumentMessageElement(String name, TextDocument doc, MessageElement sig) { - super(name, doc.getMimeType(), sig); - - this.doc = doc; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof MessageElement) { - if (!super.equals(target)) { - return false; - } - - if (target instanceof TextMessageElement) { - // have to do a slow char by char comparison. Still better than the stream since it saves encoding. - // XXX 20020615 bondolo@jxta.org the performance of this could be much improved. - - TextMessageElement likeMe = (TextMessageElement) target; - - try { - Reader myReader = getReader(); - Reader itsReader = likeMe.getReader(); - - int mine; - int its; - - do { - mine = myReader.read(); - its = itsReader.read(); - - if (mine != its) { - return false; - } // content didn't match - - } while ((-1 != mine) && (-1 != its)); - - return ((-1 == mine) && (-1 == its)); // end at the same time? - } catch (IOException fatal) { - throw new IllegalStateException("MessageElements could not be compared." + fatal); - } - } else { - // have to do a slow stream comparison. - // XXX 20020615 bondolo@jxta.org the performance of this could be much improved. - - MessageElement likeMe = (MessageElement) target; - - try { - InputStream myStream = getStream(); - InputStream itsStream = likeMe.getStream(); - - int mine; - int its; - - do { - mine = myStream.read(); - its = itsStream.read(); - - if (mine != its) { - return false; - } // content didn't match - - } while ((-1 != mine) && (-1 != its)); - - return ((-1 == mine) && (-1 == its)); // end at the same time? - } catch (IOException fatal) { - throw new IllegalStateException("MessageElements could not be compared." + fatal); - } - } - } - - return false; // not a new message element - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = super.hashCode() * 6037 + // a prime - toString().hashCode(); - - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized String toString() { - String result; - - if (null != cachedToString) { - result = cachedToString.get(); - - if (null != result) { - return result; - } - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("creating toString of " + getClass().getName() + "@" + super.hashCode()); - } - - result = doc.toString(); - cachedToString = new SoftReference(result); - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public MimeMediaType getMimeType() { - return doc.getMimeType(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getFileExtension() { - return doc.getFileExtension(); - } - - /** - * {@inheritDoc} - */ - public InputStream getStream() throws IOException { - byte[] sending = getBytes(false); - - return new ByteArrayInputStream(sending); - } - - /** - * {@inheritDoc} - */ - @Override - public void sendToStream(OutputStream sendTo) throws IOException { - - byte[] sending = getBytes(false); - - sendTo.write(sending, 0, sending.length); - } - - /** - * {@inheritDoc} - */ - public Reader getReader() throws IOException { - - return doc.getReader(); - } - - /** - * {@inheritDoc} - */ - @Override - public void sendToWriter(Writer sendTo) throws IOException { - doc.sendToWriter(sendTo); - } - - /** - * {@inheritDoc} - */ - @Override - public byte[] getBytes(boolean copy) { - byte[] result; - - if (null != cachedGetBytes) { - result = cachedGetBytes.get(); - - if (null != result) { - if (copy) { - byte[] theCopy = new byte[result.length]; - - System.arraycopy(theCopy, 0, result, 0, result.length); - } else { - return result; - } - } - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("creating getBytes of " + getClass().getName() + '@' + Integer.toHexString(hashCode())); - } - - String charset = type.getParameter("charset"); - - if (null == charset) { - result = toString().getBytes(); - } else { - try { - result = toString().getBytes(charset); - } catch (UnsupportedEncodingException caught) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "MessageElement Data could not be generated", caught); - } - throw new IllegalStateException("MessageElement Data could not be generated due to " + caught.getMessage()); - } - } - - // if this is supposed to be a shared buffer then we can cache it. - if (!copy) { - cachedGetBytes = new SoftReference(result); - } - - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public long getCharLength() { - return toString().length(); - } - - /** - * {@inheritDoc} - */ - @Override - public char[] getChars(boolean copy) { - char[] result; - - if (null != cachedGetChars) { - result = cachedGetChars.get(); - - if (null != result) { - if (copy) { - char[] theCopy = new char[result.length]; - - System.arraycopy(theCopy, 0, result, 0, result.length); - } else { - return result; - } - } - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("creating getChars of " + getClass().getName() + '@' + Integer.toHexString(hashCode())); - } - - String asString = toString(); - - result = asString.toCharArray(); - - // if this is supposed to be a shared buffer then we can cache it. - if (!copy) { - cachedGetChars = new SoftReference(result); - } - - return result; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/TextMessageElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/TextMessageElement.java deleted file mode 100644 index 4f866a1d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/TextMessageElement.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - - -import net.jxta.document.MimeMediaType; -import net.jxta.document.TextDocument; -import net.jxta.logging.Logging; -import net.jxta.util.CountingWriter; -import net.jxta.util.DevNullWriter; - -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; -import java.lang.ref.SoftReference; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * An extension of MessageElement for managing elements that are composed of - * character text. (as opposed to raw bytes). - *

      - * The data contained within a {@code TextMessageElement} is accessible in three - * additional ways to those provided by {@code MessageElement} : - *

      - *

        - *
      • As an {@link java.io.Reader} from {@link #getReader()}
      • - *
      • Sending the data a {@link java.io.Writer} via {@link #sendToWriter(Writer)}
      • - *
      • As a char array from from {@link #getChars(boolean)}
      • - *
      - * - */ -public abstract class TextMessageElement extends MessageElement implements TextDocument { - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(TextMessageElement.class.getName()); - - /** - * cached result of {@link #getCharLength()} operation. - */ - protected transient long cachedGetCharLength = -1; - - /** - * cached result of {@link #getBytes(boolean)} operation. - */ - protected transient SoftReference cachedGetChars = null; - - /** - * Internal constructor for initializaing everything but the data. - * - * @param name Name of the Element. May be the empty string ("") if - * the Element is not named. - * @param type Type of the Element. null is equivalent to specifying - * the type "Application/Octet-stream" - * @param sig optional message digest/digital signature elemnent. If - * no signature is to be specified, pass null. - */ - protected TextMessageElement(String name, MimeMediaType type, MessageElement sig) { - super(name, type, sig); - } - - /** - * {@inheritDoc} - *

      - * synchronized for caching purposes. - */ - @Override - public synchronized String toString() { - String result; - - if (null != cachedToString) { - result = cachedToString.get(); - - if (null != result) { - return result; - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("creating toString of " + getClass().getName() + '@' + Integer.toHexString(hashCode())); - } - - StringBuilder theString = new StringBuilder(); - - try { - Reader asString = getReader(); - char[] characters = new char[256]; - - do { - int res = asString.read(characters); - - if (res < 0) { - break; - } - - theString.append(characters, 0, res); - } while (true); - - result = theString.toString(); - - cachedToString = new SoftReference(result); - return result; - } catch (IOException caught) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not generate string for element. ", caught); - } - - throw new IllegalStateException("Could not generate string for element. " + caught); - } - } - - /** - * {@inheritDoc} - *

      - * We use the "text" extension and leave it to sub-classes to extend - * this. - */ - @Override - public String getFileExtension() { - return "txt"; - } - - /** - * Returns the size of the element data in characters - *

      - * synchronized for caching purposes. - * - * @return long containing the size of the element data. - */ - public synchronized long getCharLength() { - if (cachedGetCharLength >= 0) { - return cachedGetCharLength; - } - - CountingWriter countChars = new CountingWriter(new DevNullWriter()); - - try { - sendToWriter(countChars); - cachedGetByteLength = countChars.getCharsWritten(); - return cachedGetByteLength; - } catch (IOException caught) { - throw new IllegalStateException("Could not get length of element : " + caught.toString()); - } - } - - /** - * Returns a char array which contains the element data. The char array - * returned may be shared amongst all copies of the element, - * do not modify it. The copy parameter allows you to request a - * private, modifiable copy of the element data. - *

      - * synchronized for caching purposes. - * - * @param copy return a copy if true - * @return char[] Contents of message element. - */ - public synchronized char[] getChars(boolean copy) { - char[] result; - - if (null != cachedGetChars) { - result = cachedGetChars.get(); - - if (null != result) { - if (copy) { - char[] theCopy = new char[result.length]; - - System.arraycopy(theCopy, 0, result, 0, result.length); - } else { - return result; - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("creating getChars of " + getClass().getName() + '@' + Integer.toHexString(hashCode())); - } - - long len = getCharLength(); - - if (len > Integer.MAX_VALUE) { - throw new IllegalStateException("MessageElement is too large to be stored in a char array."); - } - - result = new char[(int) len]; - - try { - Reader reader = getReader(); - - int toRead = (int) len; - int offset = 0; - - do { - int read = reader.read(result, offset, toRead); - - if (-1 == read) { - break; - } - - toRead -= read; - offset += read; - } while (toRead < len); - - if (toRead != 0) { - IOException failure = new IOException("Unexpected EOF"); - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, failure.getMessage(), failure); - } - - throw failure; - } - } catch (IOException caught) { - IllegalStateException failure = new IllegalStateException("Failed to get bytes of Message Element"); - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, failure.getMessage(), caught); - } - throw failure; - } - - // if this is supposed to be a shared buffer then we can cache it. - if (!copy) { - cachedGetChars = new SoftReference(result); - } - - return result; - } - - /** - * {@inheritDoc} - *

      - * This version probably has sub-optimal performance. Sub-classes - * should override this implementation if possible. - */ - public void sendToWriter(Writer sendTo) throws IOException { - copyReaderToWriter(getReader(), sendTo); - } - - /** - * Copies a reader to a writer with buffering. - * - * @param source The reader to copy from. - * @param sink The writer to send the data to. - * @throws IOException if there is a problem copying the data - */ - private void copyReaderToWriter(Reader source, Writer sink) throws IOException { - int c; - char[] buf = new char[4096]; - - do { - c = source.read(buf); - - if (-1 == c) { - break; - } - - sink.write(buf, 0, c); - } while (true); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ThreadedMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ThreadedMessenger.java deleted file mode 100644 index 995c7570..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/ThreadedMessenger.java +++ /dev/null @@ -1,800 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroupID; - -import java.io.IOException; -import java.util.WeakHashMap; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This is a messenger meant to be shared by multiple channels and automatically - * distribute the available bandwidth among the channels. This one is implemented - * with a dedicated background thread. - */ -public abstract class ThreadedMessenger extends AbstractMessenger implements Runnable { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(ThreadedMessenger.class.getName()); - - /** - * Our thread group. - */ - private final static transient ThreadGroup myThreadGroup = new ThreadGroup("Threaded Messengers"); - - /** - * The logical destination address of the other party (if we know it). - */ - private volatile EndpointAddress logicalDestination = null; - - /** - * true if we have deliberately closed our input queue. - */ - private volatile boolean inputClosed = false; - - /** - * Need to know which group the transports we use live in, so that we can suppress channel redirection when in the same group. - * This is currently the norm. - */ - private PeerGroupID homeGroupID = null; - - /** - * The duration in milliseconds which the background thread will remain - * idle before quitting. - */ - private static final long THREAD_IDLE_DEAD = 15000; - - /* - * Actions that we defer to after returning from event methods. In other - * words, they cannot be done with the lock held, or they require calling - * more event methods. Because this messenger can take only one message at a - * time, actions do not cascade much. It may happen that the invoking thread - * is required to perform closure after performing send. That's about it. - * In addition, there's always only one deferred action per event. The only - * actions that cluster are closeInput and closeOutput. We do not defer - * those. - */ - private enum DeferredAction { - - /** - * No action deferred. - */ - ACTION_NONE, - - /** - * Must send the current message. - */ - ACTION_SEND, - - /** - * Must report failure to connect. - */ - ACTION_CONNECT - } - - /** - * The current deferred action. - */ - private DeferredAction deferredAction = DeferredAction.ACTION_NONE; - - /** - * The current background thread. - */ - private volatile Thread bgThread = null; - - /** - * The number of messages which may be queued for in each channel. - */ - private final int channelQueueSize; - - /** - * The active channel queue. - */ - private final BlockingQueue activeChannels = new LinkedBlockingQueue(); - - /** - * The resolving channels set. This is unordered. We use a weak hash map because abandoned channels could otherwise - * accumulate in-there until the resolution attempt completes. A buggy application could easily do much damage. - *

      - * Note: a channel with at least one message in it is not considered abandoned. To prevent it from disappearing we set a - * strong reference as the value in the map. A buggy application can do great damage, still, by queuing a single message - * and then abandoning the channel. This is has to be dealt with at another level; limiting the number of channels - * per application, or having a global limit on messages...TBD. - */ - private final WeakHashMap resolvingChannels = new WeakHashMap(4); - - /** - * A default channel where we put messages that are send directly through - * this messenger rather than via one of its channels. - */ - private ThreadedMessengerChannel defaultChannel = null; - - /** - * State lock and engine. - */ - private final ThreadedMessengerState stateMachine = new ThreadedMessengerState(); - - /** - * The implementation of channel messenger that getChannelMessenger returns: - */ - private class ThreadedMessengerChannel extends AsyncChannelMessenger { - - public ThreadedMessengerChannel(EndpointAddress baseAddress, PeerGroupID redirection, String origService, String origServiceParam, int queueSize, boolean connected) { - super(baseAddress, redirection, origService, origServiceParam, queueSize, connected); - } - - /** - * {@inheritDoc} - *

      - * We're supposed to return the complete destination, including - * service and param specific to that channel. It is not clear, whether - * this should include the cross-group mangling, though. Historically, - * it does not. - */ - public EndpointAddress getLogicalDestinationAddress() { - return logicalDestination; - } - - /** - * {@inheritDoc} - */ - @Override - protected void startImpl() { - if (!addToActiveChannels(this)) { - // We do not need to hold our lock to call this, and it is just as well since it could re-enter. - down(); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void connectImpl() { - - // If it cannot be done, it is because we known that we will never be able to generate the resulting event. That means - // that either the shared messenger is already resolved, or that it is already dead. In that case, we invoke down/up - // in sequence accordingly. - // - // NOTE: the shared messenger may become dead 1 ns from now...that or 1 hour makes no difference, the channel will - // notice when it first tries to send, in that case. The otherway around is more obvious: If the shared messenger is - // not USABLE, it cannot come back. - // - // addToResolvingChannels() garantees us that if it returns true, either of the channel's down or up methods will be - // invoked at some point. - - if (!addToResolvingChannels(this)) { - if ((ThreadedMessenger.this.getState() & USABLE) != 0) { - up(); - } else { - down(); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void resolPendingImpl() { - // If this channel is still among the ones pending resolution, make sure - // it becomes strongly referenced. - strongRefResolvingChannel(this); - } - - } - - - /** - * Our statemachine implementation; just connects the standard AbstractMessengerState action methods to - * this object. - */ - private class ThreadedMessengerState extends MessengerState { - - protected ThreadedMessengerState() { - super(false); - } - - /* - * The required action methods. - */ - - /** - * {@inheritDoc} - */ - @Override - protected void connectAction() { - deferAction(DeferredAction.ACTION_CONNECT); - } - - /** - * {@inheritDoc} - */ - @Override - protected void startAction() { - deferAction(DeferredAction.ACTION_SEND); - } - - /** - * {@inheritDoc} - *

      - * This is a synchronous action. The state machine assumes that it - * is done when we return. There is No need (nor means) to signal - * completion. No need for synchronization either: we're already - * synchronized. - */ - @Override - protected void closeInputAction() { - inputClosed = true; - ThreadedMessengerChannel[] channels = resolvingChannels.keySet().toArray(new ThreadedMessengerChannel[0]); - - resolvingChannels.clear(); - int i = channels.length; - - while (i-- > 0) { - channels[i].down(); - } - channels = null; - } - - /** - * {@inheritDoc} - */ - @Override - protected void closeOutputAction() { - // This will break the cnx; thereby causing a down event if we have a send in progress. - // If the cnx does not break before the current message is sent, then the message will be sent successfully, - // resulting in an idle event. Either of these events is enough to complete the shutdown process. - closeImpl(); - } - - /** - * {@inheritDoc} - *

      - * The input is now closed, so we can rest assured that the last - * channel is really the last one. - * This is a synchronous action. The state machine assumes that it is - * done when we return. There is no need to signal completion with an - * idleEvent. - * No need for synchronization either: we're already synchronized. - */ - @Override - protected void failAllAction() { - - while (true) { - ThreadedMessengerChannel theChannel; - - theChannel = activeChannels.poll(); - if (theChannel == null) { - break; - } - theChannel.down(); - } - } - } - - /** - * Create a new ThreadedMessenger. - * - * @param homeGroupID the group that this messenger works for. This is the group of the endpoint service or transport - * that created this messenger. - * @param destination where messages should be addressed to - * @param logicalDestination the expected logical address of the destination. Pass null if unknown/irrelevant - * @param channelQueueSize The queue size that channels should have. - */ - public ThreadedMessenger(PeerGroupID homeGroupID, EndpointAddress destination, EndpointAddress logicalDestination, int channelQueueSize) { - - super(destination); - - this.homeGroupID = homeGroupID; - - // We tell our super class that we synchronize our state on the stateMachine object. Logic would dictate - // that we pass it to super(), but it is not itself constructed until super() returns. No way around it. - - setStateLock(stateMachine); - - this.logicalDestination = logicalDestination; - this.channelQueueSize = channelQueueSize; - } - - /** - * Runs the state machine until there's nothing left to do. - *

      - * Three exposed methods may need to inject new events in the system: sendMessageN, close, and shutdown. Since they can both - * cause actions, and since connectAction and startAction are deferred, it seems possible that one of the - * actions caused by send, close, or shutdown be called while connectAction or startAction are in progress. - *

      - * However, the state machine gives us a few guarantees: All the actions except closeInput and closeOutput have an *end* - * event. No state transition that results in an action other than closeInput or closeOutput, may occur until the end event - * for an on-going action has been called. - *

      - * We perform closeInput and closeOutput on the fly, so none of the exposed methods are capable of producing deferred actions - * while an action is already deferred. So, there is at most one deferred action after returning from an event method, - * regardless the number of concurrent threads invoking the exposed methods, and it can only happen once per deferred action - * performed. - */ - public void run() { - - try { - while (true) { - switch (nextAction()) { - case ACTION_NONE: - return; - - case ACTION_SEND: - send(); - break; - - case ACTION_CONNECT: - connect(); - break; - } - } - } catch (Throwable any) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught throwable in background thread", any); - // Hope the next thread has more luck. It'll need it. - } - } finally { - synchronized (stateMachine) { - bgThread = null; - } - } - } - - private void deferAction(DeferredAction action) { - deferredAction = action; - - if (bgThread == null) { - bgThread = new Thread(myThreadGroup, this, "ThreadedMessenger for " + getDestinationAddress()); - bgThread.setDaemon(true); - bgThread.start(); - } - } - - private DeferredAction nextAction() { - - long quitAt = System.currentTimeMillis() + THREAD_IDLE_DEAD; - - synchronized (stateMachine) { - while (deferredAction == DeferredAction.ACTION_NONE) { - // Still nothing to do. Is it time to quit, or where we just awakened for nothing ? - if (System.currentTimeMillis() > quitAt) { - // Ok. Time to quit. - return DeferredAction.ACTION_NONE; - } - - // We do not need to wakeup exactly on the deadline, so there's no need to - // recompute the deadline. THREAD_IDLE_DEAD is comparatively short. - try { - stateMachine.wait(THREAD_IDLE_DEAD); - } catch (InterruptedException ie) { - // Only shutdown can force termination. - Thread.interrupted(); - } - } - - DeferredAction action = deferredAction; - - deferredAction = DeferredAction.ACTION_NONE; - return action; - } - } - - /** - * Performs the ACTION_SEND deferred action: sends the messages in our channel queues until there's none left or - * we are forced to stop by connection breakage. - * @throws InterruptedException if interrupted - */ - private void send() throws InterruptedException { - - ThreadedMessengerChannel theChannel; - - synchronized (stateMachine) { - theChannel = activeChannels.peek(); - if (theChannel == null) { - // No notifyChange: this is defensive code. NotifyChange() should have been called already. - stateMachine.idleEvent(); - stateMachine.notifyAll(); - return; - } - } - - while (true) { - AsyncChannelMessenger.PendingMessage theMsg = theChannel.peek(); - - if (theMsg == null) { - // done with that channel for now. (And it knows it). Move to the next channel. Actually - // it should have been removed when we popped the last message, except if we went down upon sending it. - // In that later case, we leave the channel queue as is so that we cannot have to report, idle - // in the same time than down. - synchronized (stateMachine) { - activeChannels.poll(); - theChannel = activeChannels.peek(); - if (theChannel != null) { - continue; // Nothing changes; we do not call msgsEvent because we never call saturatedEvent either. - } - // Done with all channels. We're now idle. - - stateMachine.idleEvent(); - stateMachine.notifyAll(); - } - notifyChange(); - return; - } - - Message currentMsg = theMsg.msg; - String currentService = theMsg.service; - String currentParam = theMsg.param; - - try { - sendMessageBImpl(currentMsg, currentService, currentParam); - } catch (Throwable any) { - - // When the current message fails, we leave it in there. sendMessageBImpl does not report failures. So that we can retry if - // applicable. It is up to us to report failures. See failall in AsyncChannel. However, there is a risk that a bad - // message causes this messenger to go down repeatedly. We need some kind of safeguard. So, if there's already a failure - // recorded for this message, we bounce it. - synchronized (stateMachine) { - if (theMsg.failure != null) { - theChannel.poll(); - currentMsg.setMessageProperty(Messenger.class, new OutgoingMessageEvent(currentMsg, theMsg.failure)); - } else { - theMsg.failure = any; - } - stateMachine.downEvent(); - stateMachine.notifyAll(); - } - notifyChange(); - return; - } - - synchronized (stateMachine) { - // Remove the message sent - theChannel.poll(); - // Rotate the queues (Things are quite a bit simpler if there's a single still active channel - // and it's frequent, so it's worth checking) - boolean empty = (theChannel.peek() == null); - - if ((activeChannels.size() != 1) || empty) { - activeChannels.poll(); - if (!empty) { - // We're not done with that channel. Put it back at the end - activeChannels.put(theChannel); - } - - // Get the next channel. - theChannel = activeChannels.peek(); - if (theChannel == null) { - // Done with all channels. We're now idle. - stateMachine.idleEvent(); - stateMachine.notifyAll(); - } - } // else {continue to use the current channel} - } - - if (theChannel == null) { - notifyChange(); - // We're about to go wait(). Yielding is a good bet. It is - // very inexpenssive and may be all it takes to get a new job - // queued. - Thread.yield(); - return; - } - } - } - - /** - * Performs the ACTION_CONNECT deferred action. Generates a down event if it does not work. - */ - private void connect() { - boolean worked = connectImpl(); - ThreadedMessengerChannel[] channels = null; - - synchronized (stateMachine) { - if (worked) { - - // we can now get the logical destination from the underlying implementation (likely obtained from a transport - // messenger) - - EndpointAddress effectiveLogicalDest = getLogicalDestinationImpl(); - - if (logicalDestination == null) { - // We did not know what was supposed to be on the other side. Anything will do. - logicalDestination = effectiveLogicalDest; - stateMachine.upEvent(); - channels = resolvingChannels.keySet().toArray(new ThreadedMessengerChannel[0]); - resolvingChannels.clear(); - } else if (logicalDestination.equals(effectiveLogicalDest)) { - // Good. It's what we expected. - stateMachine.upEvent(); - - channels = resolvingChannels.keySet().toArray(new ThreadedMessengerChannel[0]); - resolvingChannels.clear(); - } else { - // Ooops, not what we wanted. Can't connect then. (force close the underlying cnx). - closeImpl(); - stateMachine.downEvent(); - } - - } else { - stateMachine.downEvent(); - } - stateMachine.notifyAll(); - } - - // If it worked, we need to tell all the channels that were waiting for resolution. - // If it did not work, the outcome depends upon what will happen after the down event. - // It's ok to do that outside of sync. Channel.up may synchronize, but it never calls - // this class while synchronized. - if (channels != null) { - - int i = channels.length; - - while (i-- > 0) { - channels[i].up(); - } - channels = null; - } - - notifyChange(); - } - - /* - * Messenger API top level methods. - */ - - /** - * The endpoint service may call this to cause an orderly closure of its messengers. - */ - protected final void shutdown() { - synchronized (stateMachine) { - stateMachine.shutdownEvent(); - stateMachine.notifyAll(); - } - notifyChange(); - } - - /** - * {@inheritDoc} - */ - public EndpointAddress getLogicalDestinationAddress() { - - // If it's not resolved, we can't know what the logical destination is, unless we had an expectation. - // And if we had, the messenger will fail as soon as we discover that the expectation is wrong. - // In most if not all cases, either we have an expectation, or the messenger comes already resolved. - // Otherwise, if you need the logical destination, you must resolve first. We do not want this method - // to be blocking. - return logicalDestination; - } - - /** - * {@inheritDoc} - */ - public void close() { - synchronized (stateMachine) { - stateMachine.closeEvent(); - stateMachine.notifyAll(); - } - notifyChange(); - } - - /** - * {@inheritDoc} - *

      - * In this case, this method is here out of principle but is not really expected to be invoked. The normal way - * of using a ThreadedMessenger is through its channels. We do provide a default channel that all invokers that go around - * channels will share. That could be useful to send rare out of band messages for example. - */ - public final boolean sendMessageN(Message msg, String service, String serviceParam) { - - synchronized (stateMachine) { - if (defaultChannel == null) { - // Need a default channel. - defaultChannel = new ThreadedMessengerChannel(getDestinationAddress(), null, null, null, channelQueueSize, false); - } - } - - return defaultChannel.sendMessageN(msg, service, serviceParam); - } - - /** - * {@inheritDoc} - */ - public final void sendMessageB(Message msg, String service, String serviceParam) throws IOException { - - synchronized (stateMachine) { - if (defaultChannel == null) { - // Need a default channel. - defaultChannel = new ThreadedMessengerChannel(getDestinationAddress(), null, null, null, channelQueueSize, false); - } - } - - defaultChannel.sendMessageB(msg, service, serviceParam); - } - - private boolean addToActiveChannels(ThreadedMessengerChannel channel) { - - synchronized (stateMachine) { - if (inputClosed) { - return false; - } - - try { - activeChannels.put(channel); - } catch (InterruptedException failed) { - Thread.interrupted(); - return false; - } - - // There are items in the queue now. - stateMachine.msgsEvent(); - - // We called an event. The state may have changed. Notify waiters. - stateMachine.notifyAll(); - } - - notifyChange(); - - return true; - } - - private void strongRefResolvingChannel(ThreadedMessengerChannel channel) { - - // If, and only if, this channel is already among the resolving channels, add a strong ref - // to it. This is invoked when a message is queued to that channel while it is still - // resolving. However we must verify its presence in the resolvingChannels map: this method - // may be called while the channel has been removed from the list, but has not been told - // yet. - synchronized (stateMachine) { - if (resolvingChannels.containsKey(channel)) { - resolvingChannels.put(channel, channel); - } - } - } - - private boolean addToResolvingChannels(ThreadedMessengerChannel channel) { - - synchronized (stateMachine) { - // If we're in a state where no resolution event will ever occur, we must not add anything to the list. - if ((stateMachine.getState() & (RESOLVED | TERMINAL)) != 0) { - return false; - } - - // We use the weak map only for the weak part, not for the map part. - resolvingChannels.put(channel, null); - - stateMachine.resolveEvent(); - stateMachine.notifyAll(); - } - - notifyChange(); - return true; - } - - /** - * {@inheritDoc} - */ - public final void resolve() { - synchronized (stateMachine) { - stateMachine.resolveEvent(); - stateMachine.notifyAll(); - } - notifyChange(); - } - - /** - * {@inheritDoc} - */ - public final int getState() { - return stateMachine.getState(); - } - - /** - * {@inheritDoc} - */ - public Messenger getChannelMessenger(PeerGroupID redirection, String service, String serviceParam) { - - // Our transport is always in the same group. If the channel's target group is the same, no group - // redirection is ever needed. - // are we happily resolved ? - return new ThreadedMessengerChannel(getDestinationAddress(), homeGroupID.equals(redirection) ? null : redirection, service, - serviceParam, channelQueueSize, (stateMachine.getState() & (RESOLVED & USABLE)) != 0); - } - - /* - * Abstract methods to be provided by implementor. These are fully expected - * to be blocking and may be implemented by invoking transport blocking - * methods, such as EndpointServiceImpl.getLocalTransportMessenger() or - * whateverTransportMessengerWasObtained.sendMessageB(). Should the - * underlying code be non-blocking, these impl methods must simulate it. If - * it's not obvious to do, then this base class is not a good choice. - */ - - /** - * {@inheritDoc} - */ - protected abstract void closeImpl(); - - /** - * Make underlying connection. - * - * @return true if successful - */ - protected abstract boolean connectImpl(); - - /** - * Send a message blocking as needed until the message is sent. - * - * @param msg The message to send. - * @param service The destination service. - * @param param The destination serivce param. - * @throws IOException Thrown for errors encountered while sending the message. - */ - protected abstract void sendMessageBImpl(Message msg, String service, String param) throws IOException; - - /** - * {@inheritDoc} - */ - protected abstract EndpointAddress getLogicalDestinationImpl(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/WireFormatMessage.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/WireFormatMessage.java deleted file mode 100644 index e28c3297..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/WireFormatMessage.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.endpoint; - - -import java.nio.ByteBuffer; -import net.jxta.document.Document; -import net.jxta.document.DocumentByteBufferIO; -import net.jxta.document.MimeMediaType; - - -/** - * A wire serialization of an abstract message. - * - * @see net.jxta.endpoint.Message - * @see net.jxta.endpoint.WireFormatMessageFactory - */ -public interface WireFormatMessage extends Document, DocumentByteBufferIO { - - /** - * Returns the encoding used for this content. May be {@code null} for - * unencoded (raw) content. - * - * @return The encoding used for this message. - */ - MimeMediaType getContentEncoding(); - - /** - * Returns the size of the serialized and encoded form of the message in bytes. - * - * @return The size of the serialized and encoded message in bytes. - */ - long getByteLength(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/WireFormatMessageFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/WireFormatMessageFactory.java deleted file mode 100644 index 707fc0fa..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/WireFormatMessageFactory.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.endpoint; - - -import net.jxta.document.MimeMediaType; -import net.jxta.logging.Logging; -import net.jxta.util.ClassFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.util.Hashtable; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * This class is a class factory for Wire Format Messages. This class abstracts - * The implementation of Wire Format Messages and allows for construction based - * on the MimeType of InputStreams. - *

      - * The WireFormatMessageFactory extends the ClassFactory to register the - * various Message wire format implementations into a static hashtable. The - * factory is called with the Mime type requested to create the corresponding - * Wire Format type. - * - * @see net.jxta.endpoint.Message - * @see net.jxta.endpoint.WireFormatMessage - * @see net.jxta.util.ClassFactory - * @see net.jxta.document.MimeMediaType - */ -public final class WireFormatMessageFactory extends ClassFactory { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(WireFormatMessageFactory.class.getName()); - - /** - * The mime media type of preferred/default wire format. - */ - public static final MimeMediaType DEFAULT_WIRE_MIME = new MimeMediaType("application/x-jxta-msg").intern(); - - /** - * Interface for instantiators of wire format messages. - */ - public interface Instantiator { - - /** - * Returns the list of mime types supported by this serialization. All of - * mimetypes in this list should have no mime type parameters. - * - * @return Returns the list of mime types supported by this serialization. - */ - public MimeMediaType[] getSupportedMimeTypes(); - - /** - * Returns a list of the content encodings supported by this serialization. - * These content encodings apply to both the overall coding of the message - * and to the encoding of individual elements. - * - * @return a list of the content encodings supported by this serialization. - */ - public MimeMediaType[] getSupportedContentEncodings(); - - /** - * Create a WireFormatMessage from an abstract message. It is an error - * (though lazily enforced) to modify the abstract message during the - * lifetime of the WireFormatMessage. - * - * @param msg the message for which a serialization is desired. - * @param type the the serialization form desired. This can include - * mime parameters to control options. - * @param preferedContentEncoding An array of acceptable message encodings - * in descending order of preference. any or none of these encoding options - * may be used. May be null for unencoded messages. - * @return a proxy object for the abstract message which is a - * representation of the message in its serialized form. - */ - public WireFormatMessage toWire(Message msg, MimeMediaType type, MimeMediaType[] preferedContentEncoding); - - /** - * Create an abstract message from a serialization. - * - * @param is The message stream. Message serializations must either use - * internal data or EOF to determine the length of the stream. - * @param type Declared message type of the stream including any optional - * configuration parameters. - * @param contentEncoding Content encoding (including optional parameters) - * which has been applied to the message. May be null for unencoded messages. - * @return a proxy object for the abstract message which is a - * representation of the message in its serialized form. - * @throws java.io.IOException if an io error occurs - */ - public Message fromWire(InputStream is, MimeMediaType type, MimeMediaType contentEncoding) throws IOException; - - /** - * Create an abstract message from a serialization. - * - * @param buffer The byte buffer. Message serializations must either use - * internal data or EOF to determine the length of the stream. - * @param type Declared message type of the stream including any optional - * configuration parameters. - * @param contentEncoding Content encoding (including optional parameters) - * which has been applied to the message. May be null for unencoded messages. - * @return a proxy object for the abstract message which is a - * representation of the message in its serialized form. - * @throws java.io.IOException if an io error occurs - */ - public Message fromBuffer(ByteBuffer buffer, MimeMediaType type, MimeMediaType contentEncoding) throws IOException; - } - - /** - * This is the map of mime-types and constructors used by - * newStructuredDocument. - */ - private Map encodings = new Hashtable(); - - /** - * If true then the pre-defined set of StructuredDocument sub-classes has - * been registered from the property containing them. - */ - private volatile boolean loadedProperty = false; - - /** - * This class is in fact a singleton. This is the instance that backs the - * static methods. - */ - private static WireFormatMessageFactory factory = new WireFormatMessageFactory(); - - /** - * Private constructor. This class is not meant to be instantiated except - * by itself. - */ - private WireFormatMessageFactory() {} - - /** - * Registers the pre-defined set of WireFormatMessage sub-classes so that - * this factory can construct them. - * - * @return true if at least one of the WireFormatMessage sub-classes could - * be registered otherwise false. - */ - private synchronized boolean loadProviders() { - if (!factory.loadedProperty) { - factory.loadedProperty = registerProviders(WireFormatMessage.class.getName()); - } - - return factory.loadedProperty; - } - - /** - * {@inheritDoc} - */ - @Override - protected Map getAssocTable() { - return encodings; - } - - /** - * {@inheritDoc} - */ - @Override - public Class getClassOfInstantiators() { - // our key is the doctype names. - return Instantiator.class; - } - - /** - * {@inheritDoc} - */ - @Override - public Class getClassForKey() { - // our key is the mime types. - return MimeMediaType.class; - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean registerAssoc(String className) { - boolean registeredSomething = false; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Registering : " + className); - } - - try { - Class msgClass = Class.forName(className); - - Instantiator instantiator = (Instantiator) (msgClass.getField("INSTANTIATOR").get(null)); - - MimeMediaType[] mimeTypes = instantiator.getSupportedMimeTypes(); - - for (MimeMediaType mimeType : mimeTypes) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer(" Registering Type : " + mimeType); - } - - registeredSomething |= registerInstantiator(mimeType, instantiator); - } - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to register \'" + className + "\'", all); - } - } - - return registeredSomething; - } - - /** - * Register an instantiator object a mime-type of documents to be - * constructed. - * - * @param mimetype the mime-type associated. - * @param instantiator the instantiator that wants to be registered.. - * @return boolean true if the instantiator for this mime-type is now - * registered. If there was already an instantiator this mime-type then - * false will be returned. - * @throws SecurityException there were permission problems registering - * the instantiator. - */ - public static boolean registerInstantiator(MimeMediaType mimetype, Instantiator instantiator) { - boolean registered = factory.registerAssoc(mimetype, instantiator); - - return registered; - } - - /** - * Constructs an instance of {@link WireFormatMessage} matching the type - * specified by the type parameter. - * - * @param msg the message for which a serialization is desired. - * @param type the the serialization form desired. This can include - * mime parameters to control options. - * @param preferedEncodings An array of acceptable message encodings - * in descending order of preference. any or none of these encoding options - * may be used. May be null for unencoded messages. - * @return a proxy object for the abstract message which is a - * representation of the message in its serialized form. - */ - public static WireFormatMessage toWire(Message msg, MimeMediaType type, MimeMediaType[] preferedEncodings) { - factory.loadProviders(); - - Instantiator instantiator = factory.getInstantiator(type.getBaseMimeMediaType()); - - return instantiator.toWire(msg, type, preferedEncodings); - } - - /** - * Constructs an instance of Message from matching the type - * specified by the type parameter. - * - * @param is The message stream. Message serializations must either use - * internal data or EOF to determine the length of the stream. - * @param type Declared message type of the stream including any optional - * configuration parameters. - * @param contentEncoding Content encoding (including optional parameters) - * which has been applied to the message. May be null for unencoded messages. - * @return the new abstract message. - * @throws java.io.IOException if an io error occurs - */ - public static Message fromWire(InputStream is, MimeMediaType type, MimeMediaType contentEncoding) throws IOException { - factory.loadProviders(); - - Instantiator instantiator; - - try { - instantiator = factory.getInstantiator(type.getBaseMimeMediaType()); - } catch (NoSuchElementException badType) { - throw new IOException("Unable to deserialize message of type: " + type); - } - - return instantiator.fromWire(is, type, contentEncoding); - } - - /** - * Constructs an instance of Message from matching the type - * specified by the type parameter. - * - * @param buffer The message buffer. Message serializations must either use - * internal data or EOF to determine the length of the stream. - * @param type Declared message type of the stream including any optional - * configuration parameters. - * @param contentEncoding Content encoding (including optional parameters) - * which has been applied to the message. May be null for unencoded messages. - * @return the new abstract message. - * @throws java.io.IOException if an io error occurs - */ - public static Message fromBuffer(ByteBuffer buffer, MimeMediaType type, MimeMediaType contentEncoding) throws IOException { - factory.loadProviders(); - - Instantiator instantiator; - - try { - instantiator = factory.getInstantiator(type.getBaseMimeMediaType()); - } catch (NoSuchElementException badType) { - throw new IOException("Unable to deserialize message of type: " + type); - } - - return instantiator.fromBuffer(buffer, type, contentEncoding); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/package.html deleted file mode 100644 index 83bbbe58..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/endpoint/package.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - Provides interfaces and classes used for the addressing, filtering, sending, - and receiving of messages within JXTA. - - @see JXTA Protocols Specification - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/ConfiguratorException.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/ConfiguratorException.java deleted file mode 100644 index 70b6078b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/ConfiguratorException.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.exception; - - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - -/** - * This class maintains a {@link java.util.List} of all possible {@link - * java.lang.Throwable causes} that may be generated as a part of the - * configuration process. - * - * @author james todd [gonzo at jxta dot org] - */ - -public class ConfiguratorException extends JxtaException { - - private List causes = null; - - /** - * Constucts a {@link JxtaException} with no specified details. - */ - public ConfiguratorException() { - super(); - } - - /** - * Constructs a {@link JxtaException} with the specified message. - * - * @param msg message - */ - public ConfiguratorException(String msg) { - super(msg); - } - - /** - * Constructs a {@link JxtaException} with the specified {@link - * java.lang.Throwable cause}. - * - * @param ex cause - */ - public ConfiguratorException(Throwable ex) { - super(); - - addCause(ex); - } - - /** - * Constructs a {@link JxtaException} with the specified message and {@link - * java.lang.Throwable cause}. - * - * @param msg message - * @param ex cause - */ - public ConfiguratorException(String msg, Throwable ex) { - super(msg); - - addCause(ex); - } - - /** - * Constructs a {@link JxtaException} with the specified {@link - * java.util.List} of {@link java.lang.Throwable causes}. - * - * @param ex causes - */ - public ConfiguratorException(List ex) { - super(); - - addCauses(ex); - } - - /** - * Constructs a {@link JxtaException} with the specified message in - * addition to the {@link java.util.List} of {@link java.lang.Throwable - * causes}. - * - * @param msg message - * @param ex causes - */ - public ConfiguratorException(String msg, List ex) { - super(msg); - - addCauses(ex); - } - - /** - * Retrieve the {@link java.lang.Throwable causes} as a {@link - * java.util.List}. - * - * @return The causes - */ - public List getCauses() { - return this.causes != null ? this.causes : Collections.emptyList(); - } - - /** - * Add a cause of type {@link java.lang.Throwable}. - * - * @param c The cause - */ - public void addCause(Throwable c) { - if (c != null) { - if (this.causes == null) { - this.causes = new ArrayList(); - } - - this.causes.add(c); - } - } - - /** - * Add a {@link java.util.List} of {@link java.lang.Throwable causes}. - * - * @param c The causes - */ - public void addCauses(List c) { - if (c != null) { - for (Object aC : c) { - addCause((Throwable) aC); - } - } - } - - /** - * @inheritDoc

      Overload printStackTrace() to support multiple {@link java.lang.Throwable causes}. - */ - @Override - public void printStackTrace() { - super.printStackTrace(); - - for (Object o : getCauses()) { - ((Throwable) o).printStackTrace(); - } - } - - /** - * @param ps Description of the Parameter - * @inheritDoc

      Overload printStackTrace({@link java.io.PrintStream}) to support - * multiple {@link java.lang.Throwable causes}. - */ - @Override - public void printStackTrace(PrintStream ps) { - super.printStackTrace(ps); - - ps.println("Caused by:"); - int count = 1; - - for (Object o : getCauses()) { - Throwable t = (Throwable) o; - - ps.print("Cause #" + count++ + " : "); - - t.printStackTrace(ps); - } - } - - /** - * @param pw Description of the Parameter - * @inheritDoc

      Overload printStackTrace({@link java.io.PrintWriter}) to support - * multiple {@link java.lang.Throwable causes}. - */ - @Override - public void printStackTrace(PrintWriter pw) { - super.printStackTrace(pw); - - pw.println("Caused by:"); - int count = 1; - - for (Object o : getCauses()) { - Throwable t = (Throwable) o; - - pw.print("Cause #" + count++ + " : "); - - t.printStackTrace(pw); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/JxtaError.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/JxtaError.java deleted file mode 100644 index f7cab084..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/JxtaError.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.exception; - - -/** - * Thrown when JXTA cannot continue running. - */ - -public class JxtaError extends Error { - - /** - * Construct a new JxtaError with no detailed message. - * - */ - public JxtaError() {} - - public JxtaError(String msg) { - super(msg); - } - - public JxtaError(String msg, Throwable cause) { - super(msg, cause); - } - - public JxtaError(Throwable cause) { - super(cause); - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/JxtaException.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/JxtaException.java deleted file mode 100644 index 01ad8dc7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/JxtaException.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.exception; - - -/** - * The class JxtaException and its subclasses are a form of Exception that - * indicates conditions that a reasonable application might want to catch. - * - */ -@SuppressWarnings("serial") -public class JxtaException extends Exception { - - /** - * Constructs an Exception with no specified detail message. - */ - public JxtaException() { - super(); - } - - /** - * Constructs an Exception with the specified detail message. - * - *@param message the detail message. - */ - public JxtaException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified detail message and cause. - * - *@param cause the cause (which is saved for later retrieval by the - * Throwable.getCause() method). - * (A null value is permitted, and indicates that the - * cause is nonexistent or unknown.) - */ - public JxtaException(Throwable cause) { - super(cause); - } - - /** - * Constructs a new exception with the specified detail message and cause. - * - *@param message message the detail message - *@param cause the cause (which is saved for later retrieval by the - * Throwable.getCause() method). - * (A null value is permitted, and indicates that the - * cause is nonexistent or unknown.) - */ - public JxtaException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/PeerGroupException.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/PeerGroupException.java deleted file mode 100644 index 297fc492..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/PeerGroupException.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.exception; - - -/** - * Generic Peer group exception - * - */ - -public class PeerGroupException extends JxtaException { - - /** - * Constructs an Exception with no specified detail message. - */ - public PeerGroupException() { - super(); - } - - /** - * Constructs an Exception with the specified detail message. - * - *@param message the detail message. - */ - public PeerGroupException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified detail message and cause. - * - *@param cause the cause (which is saved for later retrieval by the - * Throwable.getCause() method). - * (A null value is permitted, and indicates that the - * cause is nonexistent or unknown.) - */ - public PeerGroupException(Throwable cause) { - super(cause); - } - - /** - * Constructs a new exception with the specified detail message and cause. - * - *@param message message the detail message - *@param cause the cause (which is saved for later retrieval by the - * Throwable.getCause() method). - * (A null value is permitted, and indicates that the - * cause is nonexistent or unknown.) - */ - public PeerGroupException(String message, Throwable cause) { - super(message, cause); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/ProtocolNotSupportedException.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/ProtocolNotSupportedException.java deleted file mode 100644 index feb4c5fb..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/ProtocolNotSupportedException.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.exception; - - -/** - * Signals that an error occurred while attempting to access an - * endpoint protocol - * - */ -public class ProtocolNotSupportedException extends JxtaException { - - /** - * Constructs an Exception with no specified detail message. - */ - public ProtocolNotSupportedException() { - super(); - } - - /** - * Constructs an Exception with the specified detail message. - * - *@param message the detail message. - */ - public ProtocolNotSupportedException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified detail message and cause. - * - *@param cause the cause (which is saved for later retrieval by the - * Throwable.getCause() method). - * (A null value is permitted, and indicates that the - * cause is nonexistent or unknown.) - */ - public ProtocolNotSupportedException(Throwable cause) { - super(cause); - } - - /** - * Constructs a new exception with the specified detail message and cause. - * - *@param message message the detail message - *@param cause the cause (which is saved for later retrieval by the - * Throwable.getCause() method). - * (A null value is permitted, and indicates that the - * cause is nonexistent or unknown.) - */ - public ProtocolNotSupportedException(String message, Throwable cause) { - super(message, cause); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/ServiceNotFoundException.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/ServiceNotFoundException.java deleted file mode 100644 index 11b79227..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/ServiceNotFoundException.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.exception; - - -/** - * Signals that an error occurred while trying to access a peer group service - * - */ -public class ServiceNotFoundException extends JxtaException { - - /** - * Constructs an Exception with no specified detail message. - */ - public ServiceNotFoundException() { - super(); - } - - /** - * Constructs an Exception with the specified detail message. - * - *@param message the detail message. - */ - public ServiceNotFoundException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified detail message and cause. - * - *@param cause the cause (which is saved for later retrieval by the - * Throwable.getCause() method). - * (A null value is permitted, and indicates that the - * cause is nonexistent or unknown.) - */ - public ServiceNotFoundException(Throwable cause) { - super(cause); - } - - /** - * Constructs a new exception with the specified detail message and cause. - * - *@param message message the detail message - *@param cause the cause (which is saved for later retrieval by the - * Throwable.getCause() method). - * (A null value is permitted, and indicates that the - * cause is nonexistent or unknown.) - */ - public ServiceNotFoundException(String message, Throwable cause) { - super(message, cause); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/UnknownServiceException.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/UnknownServiceException.java deleted file mode 100644 index bd531742..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/UnknownServiceException.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.exception; - - -/** - * Signals that an error occurred while trying to access a service - * - */ - -public class UnknownServiceException extends JxtaException { - - /** - * Constructs an Exception with no specified detail message. - */ - public UnknownServiceException() { - super(); - } - - /** - * Constructs an Exception with the specified detail message. - * - *@param message the detail message. - */ - public UnknownServiceException(String message) { - super(message); - } - - /** - * Constructs a new exception with the specified detail message and cause. - * - *@param cause the cause (which is saved for later retrieval by the - * Throwable.getCause() method). - * (A null value is permitted, and indicates that the - * cause is nonexistent or unknown.) - */ - public UnknownServiceException(Throwable cause) { - super(cause); - } - - /** - * Constructs a new exception with the specified detail message and cause. - * - *@param message message the detail message - *@param cause the cause (which is saved for later retrieval by the - * Throwable.getCause() method). - * (A null value is permitted, and indicates that the - * cause is nonexistent or unknown.) - */ - public UnknownServiceException(String message, Throwable cause) { - super(message, cause); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/package.html deleted file mode 100644 index 1fd5f017..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/exception/package.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - Exception classes commonly used by JXTA Components. - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/ID.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/ID.java deleted file mode 100644 index 44f52d8f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/ID.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.id; - - -import java.io.ObjectStreamException; -import java.lang.ref.Reference; -import java.lang.ref.WeakReference; -import java.net.URI; -import java.net.URL; -import java.util.Map; -import java.util.WeakHashMap; - -import java.net.MalformedURLException; -import java.net.URISyntaxException; - - -/** - * IDs are used to uniquely identify peers, peer groups, pipes and other - * types of objects manipulated by the JXTA APIs. - * - * @see net.jxta.id.IDFactory - * @see net.jxta.codat.CodatID - * @see net.jxta.peer.PeerID - * @see net.jxta.peergroup.PeerGroupID - * @see net.jxta.pipe.PipeID - * @see net.jxta.platform.ModuleClassID - * @see net.jxta.platform.ModuleSpecID - * @see JXTA Protocols Specification : IDs - */ -public abstract class ID implements java.io.Serializable { - - /** - * Collection of interned IDs. All IDs visible within in the VM are - * contained within this table. - */ - private static final Map> interned = new WeakHashMap>(1000); - - /** - * This defines the URI scheme that we will be using to present JXTA IDs. - * JXTA IDs are encoded for presentation into URIs (see - * {@link IETF RFC 2396 Uniform Resource Identifiers (URI) : Generic Syntax} - * ) as URNs (see - * {@link IETF RFC 2141 Uniform Resource Names (URN) Syntax} - * ). - */ - public static final String URIEncodingName = "urn"; - - /** - * This defines the URN Namespace that we will be using to present JXTA IDs. - * The namespace allows URN resolvers to determine which sub-resolver to use - * to resolve URN references. All JXTA IDs are presented in this namespace. - */ - public static final String URNNamespace = "jxta"; - - /** - * The null ID. The NullID is often used as a placeholder in fields which - * are uninitialized. - * - *

      This is a singleton within the scope of a VM. - */ - public static final ID nullID = (new NullID()).intern(); - - /** - * - * Creates an ID by parsing the given URI. - * - *

      This convenience factory method works as if by invoking the - * {@link IDFactory#fromURI(URI)} method; any {@link URISyntaxException} - * thrown is caught and wrapped in a new {@link IllegalArgumentException} - * object, which is then thrown. - * - *

      This method is provided for use in situations where it is known that - * the given string is a legal ID, for example for ID constants declared - * within in a program, and so it would be considered a programming error - * for the URI not to parse as such. The {@link IDFactory}, which throws - * {@link URISyntaxException} directly, should be used situations where a - * ID is being constructed from user input or from some other source that - * may be prone to errors. - * - * @param fromURI The URI to be parsed into an ID - * @return The new ID - * - * @throws NullPointerException - * If fromURI is null - * - * @throws IllegalArgumentException - * If the given URI is not a valid ID. - */ - public static ID create(URI fromURI) { - try { - return IDFactory.fromURI(fromURI); - } catch (URISyntaxException badid) { - IllegalArgumentException failure = new IllegalArgumentException(); - - failure.initCause(badid); - throw failure; - } - } - - /** - * Constructor for IDs. IDs are constructed using the {@link IDFactory} or - * {@link #create(URI)}. - * - */ - protected ID() {} - - /** - * Returns a string representation of the ID. This representation should be - * used primarily for debugging purposes. For most other situations IDs - * should be externalized as Java URI Objects via {@link #toURI()}. - * - *

      The default implementation is the toString() of the ID - * represented as a URI. - * - * @return String containing the URI - * - */ - @Override - public String toString() { - return toURI().toString(); - } - - /** - * Return the interned form of the ID. - */ - private Object readResolve() throws ObjectStreamException { - return intern(); - } - - /** - * Returns a string identifier which indicates which ID format is - * used by this ID instance. - * - * @return a string identifier which indicates which ID format is - * used by this ID instance. - */ - public abstract String getIDFormat(); - - /** - * Returns an object containing the unique value of the ID. This object - * must provide implementations of toString(), equals() and hashCode() that - * are canonical and consistent from run-to-run given the same input values. - * Beyond this nothing should be assumed about the nature of this object. - * For some implementations the object returned may be this. - * - * @return Object which can provide canonical representations of the ID. - */ - public abstract Object getUniqueValue(); - - /** - * Returns a URL representation of the ID. The - * {@link net.jxta.id.IDFactory JXTA ID Factory} can be used to construct - * ID Objects from URLs containing JXTA IDs. - * - * @deprecated URIs are now the preferred way of manipulating IDs - * - * @see net.jxta.id.IDFactory#fromURL( java.net.URL ) - * - * @return URL Object containing the URI - */ - @Deprecated - public URL getURL() { - try { - return IDFactory.jxtaURL(URIEncodingName, "", URNNamespace + ":" + getUniqueValue()); - } catch (MalformedURLException caught) { - IllegalStateException failure = new IllegalStateException("Environment incorrectly intialized."); - - failure.initCause(caught); - throw failure; - } - } - - /** - * Returns a canonical representation for the ID object. - * - *

      A pool of IDs, is maintained privately by the class. - * - *

      When the intern() method is invoked, if the pool already contains a - * ID equal to this ID object as determined by the - * equals(Object) method, then the ID from the pool is returned. - * Otherwise, this ID object is added to the pool and a reference - * to this ID object is returned. - * - *

      It follows that for any two ID s and t, - * s.intern() == t.intern() is true if and only if s.equals(t) - * is true. - * - * @return a ID that has the same value as this type, but is guaranteed to - * be from a pool of unique types. - */ - protected ID intern() { - synchronized (ID.class) { - Reference common = interned.get(this); - - ID result = null; - - if (null != common) { - result = common.get(); - } - - if (null == result) { - interned.put(this, new WeakReference(this)); - result = this; - } - - return result; - } - } - - /** - * Returns a URI representation of the ID. {@link java.net.URI URIs} are - * the preferred way of externalizing and presenting JXTA IDs. The - * {@link net.jxta.id.IDFactory JXTA ID Factory} can be used to construct - * ID Objects from URIs containing JXTA IDs. - * - * @see net.jxta.id.IDFactory#fromURI( java.net.URI ) - * - * @return URI Object containing the URI - */ - public URI toURI() { - return URI.create(URIEncodingName + ":" + URNNamespace + ":" + getUniqueValue()); - } -} - - -/** - * The NullID is often used as a placeholder in fields which are uninitialized. - */ -final class NullID extends ID { - final static String JXTAFormat = "jxta"; - - final static String UNIQUEVALUE = "Null"; - - /** - * NullID is not intended to be constructed. You should use the - * {@link #nullID} constant instead. - */ - NullID() {} - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - return (this == target); // null is only itself. - } - - /** - * deserialization has to point back to the singleton in this VM. - */ - private Object readResolve() { - return ID.nullID; - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return JXTAFormat; - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + UNIQUEVALUE; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/IDFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/IDFactory.java deleted file mode 100644 index 8e2297a1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/IDFactory.java +++ /dev/null @@ -1,1210 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.id; - - -import java.io.InputStream; -import java.lang.reflect.Field; -import java.net.URI; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.ResourceBundle; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.UnknownServiceException; -import java.util.MissingResourceException; -import java.util.NoSuchElementException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.codat.CodatID; -import net.jxta.id.jxta.IDFormat; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.pipe.PipeID; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.util.ClassFactory; - - -/** - * A factory class for creating new ID instances and for constructing ID - * instances from external representations such as strings or URIs. - * - *

      When possible the factory will create IDs of the same ID Format as any - * base ids provided. For example, PipeIDs will be created to be the same ID - * Format as the PeerGroupID provided. - * - *

      Some ID constructors allow specification of "seed" information. Each ID - * Format may use this seed information as it chooses or may require seed - * information of a specific form. In some cases the seed information will be - * used literally as provided to construct the resulting ID, but ID Formats - * may also choose to ignore the seed information entirely, use it as random - * number generator seed values, etc. Consult the implementation documentation - * for the ID Formats of interest to see how the seed information is used by - * each ID Format. - * - * @see net.jxta.id.ID - * @see net.jxta.util.ClassFactory - * @see JXTA Protocols Specification : IDs - */ -public final class IDFactory extends ClassFactory { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(IDFactory.class.getName()); - - /** - * A map of the ID Formats to instantiators. - * - */ - private final Map idFormats = new HashMap(); - - /** - * Identifies the ID format to use when creating new ID instances. - */ - private final String idNewInstances; - - /** - * This class is a singleton. This is the instance that backs the - * static methods. - */ - private final static IDFactory factory = new IDFactory(); - - /** - * Interface for instantiators of IDs. Each ID Format registered with the - * ID Factory implements a class with this interface. - */ - public interface Instantiator { - - /** - * Returns the ID Format value associated with this ID Format - * - * @return String containing the ID format value for this format. - */ - public String getSupportedIDFormat(); - - /** - * Construct a new ID instance from a JXTA ID contained in a URL. - * - * @deprecated Convert to {@code fromURI}. - * - * @param source URL which will be decoded to create a new ID instance. - * @return ID containing the new ID instance initialized from the URL. - * @throws UnknownServiceException Is thrown if the URL provided is of - * a format unrecognized by this JXTA implementation. - * @throws MalformedURLException Is thrown if the URL provided is not - * a valid, recognized JXTA URL. - */ - @Deprecated - public ID fromURL(URL source) throws MalformedURLException, UnknownServiceException; - - /** - * Construct a new ID instance from a JXTA ID contained in a URI. - * - * @param source URI which will be decoded to create a new ID instance. - * @return ID containing the new ID instance initialized from the source. - * @throws URISyntaxException if the URI provided is not a valid, - * recognized JXTA URI. - */ - public ID fromURI(URI source) throws URISyntaxException; - - /** - * Construct a new ID instance from the scheme specific portion of a jxta - * URN. - * - * @param source the scheme specific portion of a jxta URN. - * @return ID containing the new ID instance initialized from the source. - * @throws URISyntaxException if the URI provided is not a valid, - * recognized JXTA URI. - */ - public ID fromURNNamespaceSpecificPart(String source) throws URISyntaxException; - - /** - * Creates a new CodatID Instance. A new random CodatID is created for - * the provided Peer Group. This type of CodatID can be used as a - * canonical reference for dynamic content. - * - * @see net.jxta.codat.Codat - * - * @param groupID The group to which this content will belong. - * @return The newly created CodatID. - */ - public CodatID newCodatID(PeerGroupID groupID); - - /** - * Creates a new CodatID instance. A new CodatID is created for the - * provided Peer Group. This type of CodatID can be used as a - * canonical reference for dynamic content. - * - *

      This variant of CodatID allows you to create "Well-known" codats - * within the context of diverse groups. This can be useful for common - * services that need to do discovery without advertisements or for - * network organization services. Because of the potential for ID - * collisions and the difficulties with maintaining common service - * interfaces this variant of CodatID should be used with great caution - * and pre-planning. - * - * @see net.jxta.codat.Codat - * - * @param groupID The group to which this content will belong. - * @param seed The seed information which will be used in creating the - * codatID. The seed information should be at least four bytes in - * length, though longer values are better. - * @return The newly created CodatID. - */ - public CodatID newCodatID(PeerGroupID groupID, byte[] seed); - - /** - * Creates a new CodatID instance. A new random CodatID is created for - * the provided Peer Group and contains a hash value for the Codat data. - * This type of Codat ID is most appropriate for static content. By - * including a hash value this form of Codat ID provides greater - * assurance of the canonical property of IDs. It also allows the - * document content returned when this ID is used to be verified to - * ensure it has not been altered. - * - * @see net.jxta.codat.Codat - * - * @param groupID The group to which this ID will belong. - * @param in The InputStream from which the content hash is calculated. - * The stream is read until EOF and then closed. - * @return The newly created CodatID. - * @throws IOException I/O Error reading document - */ - public CodatID newCodatID(PeerGroupID groupID, InputStream in) throws IOException; - - /** - * Creates a new CodatID instance. A new CodatID is created for the - * provided Peer Group and contains a hash value for the Codat data. - * By including a hash value this form of Codat ID provides greater - * assurance of the canonical property of IDs. It also allows the - * document content returned when this ID is used to be verified to - * ensure it has not been altered. This type of Codat ID is most - * appropriate for static content. - * - *

      This variant of CodatID allows you to create "Well-known" codats - * within the context of diverse groups. This can be useful for common - * services that need to do discovery without advertisements or for - * network organization services. Because of the potential for ID - * collisions and the difficulties with maintaining common service - * interfaces this variant of CodatID should be used with great caution - * and pre-planning. - * - * @see net.jxta.codat.Codat - * - * @param groupID The group to which this ID will belong. - * @param seed The seed information which will be used in creating the - * codat ID. The seed information should be at least four bytes in - * length, though longer values are better. - * @param in The InputStream from which the content hash is calculated. - * The stream is read until EOF and then closed. - * @return The newly created CodatID. - * @throws IOException I/O Error reading document - */ - public CodatID newCodatID(PeerGroupID groupID, byte[] seed, InputStream in) throws IOException; - - /** - * Creates a new PeerID instance. A new random peer id will be generated. - * The PeerID will be a member of the provided group. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param groupID the group to which this PeerID will belong. - * @return The newly created PeerID. - */ - public PeerID newPeerID(PeerGroupID groupID); - - /** - * Creates a new PeerID instance. A new PeerID will be generated. - * The PeerID will be a member of the provided group. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param groupID the group to which this PeerID will belong. - * @param seed The seed information which will be used in creating the - * PeerID. The seed information should be at least four bytes in length, - * though longer values are better. - * @return The newly created PeerID. - */ - public PeerID newPeerID(PeerGroupID groupID, byte[] seed); - - /** - * Creates a new PeerGroupID instance. A new random peer group id will be - * generated. The PeerGroupID will be created using the default ID Format. - * - * @see net.jxta.peergroup.PeerGroup - * - * @return The newly created PeerGroupID. - */ - public PeerGroupID newPeerGroupID(); - - /** - * Creates a new PeerGroupID instance. A new PeerGroupID will be - * generated using the provided seed information. The PeerGroupID will - * be created using the default ID Format. - * - *

      This method allows you to create "Well-known" PeerGroupIDs. - * This is similar to how the JXTA "World Peer Group" and "Net - * Peer Group". "Well-known" IDs can be useful for common services - * that need to do discovery without advertisements or for network - * organization services. Because of the potential for ID collisions - * and the difficulties with maintaining common service interfaces this - * variant of PeerGroupID should be used with great caution and - * pre-planning. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param seed The seed information which will be used in creating the - * PeerGroupID. The seed information should be at least four bytes in - * length, though longer values are better. - * @return The newly created PeerGroupID. - */ - public PeerGroupID newPeerGroupID(byte[] seed); - - /** - * Creates a new PeerGroupID instance with the specified parent group. - * A new random peer group id will be generated. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param parent The group which will be the parent of this group. - * @return The newly created PeerGroupID. - */ - public PeerGroupID newPeerGroupID(PeerGroupID parent); - - /** - * Creates a new PeerGroupID instance with the specified parent group. - * A new PeerGroupID will be generated using the provided seed - * information. - * - *

      This method allows you to create "Well-known" PeerGroupIDs. - * This is similar to how the JXTA "World Peer Group" and "Net - * Peer Group". "Well-known" IDs can be useful for common services - * that need to do discovery without advertisements or for network - * organization services. Because of the potential for ID collisions - * and the difficulties with maintaining common service interfaces this - * variant of PeerGroupID should be used with great caution and - * pre-planning. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param parent The group which will be the parent of this group. - * @param seed The seed information which will be used in creating the - * PeerGroupID. The seed information should be at least four bytes in - * length, though longer values are better. - * @return The newly created PeerGroupID. - */ - public PeerGroupID newPeerGroupID(PeerGroupID parent, byte[] seed); - - /** - * Creates a new PipeID instance. A new random PipeID will be generated. - * - * - * @param groupID The group to which this Pipe ID will belong. - * @return The newly created PipeID. - */ - public PipeID newPipeID(PeerGroupID groupID); - - /** - * Creates a new PipeID instance. A new pipe id will be generated with - * the provided seed information. The Pipe ID will be a member of the - * provided group. - * - *

      This variant of PipeID allows you to create "Well-known" pipes - * within the context of diverse groups. This can be useful for common - * services that need to do discovery without advertisements or for - * network organization services. Because of the potential for ID - * collisions and the difficulties with maintaining common service - * interfaces this variant of PipeID should be used with great caution - * and pre-planning. - * - * - * @param groupID the group to which this Pipe ID will belong. - * @param seed The seed information which will be used in creating the - * pipeID. The seed information should be at least four bytes in - * length, though longer values are better. - * @return the newly created PipeID. - */ - public PipeID newPipeID(PeerGroupID groupID, byte[] seed); - - /** - * Creates a new ModuleClassID instance. A new random ModuleClassID - * will be generated with a zero value role identifier. This form of - * ModuleClassID is appropriate for cases where the module does not - * need to be distinguished from other instances of the same Module. - * The ModuleClassID will be created using the default ID Format. - * - * @see net.jxta.platform.Module - * - * @return The newly created ModuleClassID. - */ - public ModuleClassID newModuleClassID(); - - /** - * Creates a new ModuleClassID instance. A new random ModuleClassID - * will be generated with a a random value role identifier and a base - * class of the provided ModuleClassID. This form of ModuleClassID is - * appropriate for cases where it is necessary to distinguish instances - * of the same service interface. - * - * @see net.jxta.platform.Module - * - * @param baseClass The ModuleClassID which will be used as a base - * class for this new role value instance. - * @return The newly created ModuleClassID. - */ - public ModuleClassID newModuleClassID(ModuleClassID baseClass); - - /** - * Creates a new ModuleSpecID instance. A new random ModuleSpecID will - * be generated. - * - * @see net.jxta.platform.Module - * - * @param baseClass The ModuleClassID which will be used as a base - * class for this new ModuleSpecID. - * @return The newly created ModuleSpecID. - */ - public ModuleSpecID newModuleSpecID(ModuleClassID baseClass); - } - - - /** - * @deprecated This interface formerly contained optional URI based - * construction methods. These have now been moved to the primary - * instantiator interface in preparation for the removal of the URL - * based interfaces. This interface will be removed in a future release. - */ - @Deprecated - public interface URIInstantiator extends Instantiator {} - - /** - * Standard Constructor. This class is a singleton so the only constructor - * is private. - * - *

      Uses net.jxta.impl.config.properties file as the - * source for settings. - * - *

      Example entry from the file net.jxta.impl.config.properties : - * - *

      
      -     * #Default type of ID to use when creating an ID (this should not be changed in most implementations).
      -     * IDNewInstances=uuid
      -     * 
      - */ - private IDFactory() { - // required format - registerAssoc("net.jxta.id.jxta.IDFormat"); - - // required by this implementation. - registerAssoc("net.jxta.impl.id.unknown.IDFormat"); - - // Register a list of classes for association with an ID format - registerProviders(ID.class.getName()); - - try { - // Get our resource bundle - ResourceBundle jxtaRsrcs = ResourceBundle.getBundle("net.jxta.impl.config"); - - // set the default ID Format. - idNewInstances = jxtaRsrcs.getString("IDNewInstances").trim(); - } catch (MissingResourceException notFound) { - // This is an error because we can't start without a concept of ID. - IllegalStateException failure = - new IllegalStateException("Could not initialize ID defaults", notFound); - LOG.log(Level.SEVERE, "Cound not initialize IDFactory", failure); - throw failure; - } - } - - /** - * Used by ClassFactory methods to get the mapping of ID types to constructors. - * - * @return the mapping of ID types to instantiators. - */ - @Override - protected Map getAssocTable() { - return idFormats; - } - - /** - * Used by ClassFactory methods to ensure that all keys used with the mapping are - * of the correct type. - * - * @return Class object of the key type. - */ - @Override - protected Class getClassForKey() { - return String.class; - } - - /** - * Used by ClassFactory methods to ensure that all of the instance classes - * which register with this factory have the correct base class - * - * @return Class object of the key type. - */ - @Override - protected Class getClassOfInstantiators() { - return Instantiator.class; - } - - /** - * Register a class with the factory from its class name. We override the - * standard implementation to get the id format from the class and - * use that as the key to register the class with the factory. - * - * @param className The class name which will be registered. - * @return boolean true if the class was registered otherwise false. - */ - @Override - public boolean registerAssoc(String className) { - boolean registeredSomething = false; - - try { - Class idClass; - - try { - idClass = Class.forName(className); - - if (null == idClass) { - throw new ClassNotFoundException("forName() result was null"); - } - } catch (ClassNotFoundException notThere) { - LOG.severe("Could not find class named : " + className); - return false; - } catch (NoClassDefFoundError notThere) { - LOG.severe("Could not find class named : " + className); - return false; - } - - Field instantiatorField; - - try { - instantiatorField = idClass.getField("INSTANTIATOR"); - - if (null == instantiatorField) { - throw new NoSuchFieldException("getField() result was null for field 'INSTANTIATOR'"); - // caught locally - } - } catch (NoSuchFieldException notThere) { - LOG.severe("Could not find INSTANTIATOR field in class named : " + className); - return false; - } - - if (!Instantiator.class.isAssignableFrom(instantiatorField.getType())) { - throw new ClassCastException("INSTANTIATOR is not of type " + Instantiator.class.getName()); - } - - Instantiator instantiator = (Instantiator) instantiatorField.get(null); - - if (null == instantiator) { - LOG.severe("INSTANTIATOR field is null for class : " + className); - return false; - } - - String idFormat = instantiator.getSupportedIDFormat(); - - registeredSomething = registerAssoc(idFormat, instantiator); - } catch (Exception failed) { - LOG.log(Level.SEVERE, "Failed to register class : " + className, failed); - } - - return registeredSomething; - } - - /** - * Returns a String containing the name of the default ID Format. - * - * @return The current default ID Format. - */ - public static String getDefaultIDFormat() { - return factory.idNewInstances; - } - - /** - * Construct a new ID instance from a JXTA ID contained in a URI. - * - * @param source URI which will be decoded to create a new ID instance. - * @return ID containing the new ID instance initialized from the URI. - * @throws URISyntaxException If the URI provided is not a valid, - * recognized JXTA URI. - */ - public static ID fromURI(URI source) throws URISyntaxException { - ID result = null; - - // check the protocol - if (!ID.URIEncodingName.equalsIgnoreCase(source.getScheme())) { - throw new URISyntaxException(source.toString(), "URI scheme was not as expected."); - } - - String decoded = source.getSchemeSpecificPart(); - - int colonAt = decoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new URISyntaxException(source.toString(), "URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(decoded.substring(0, colonAt))) { - throw new URISyntaxException(source.toString(), - "URN namespace was not as expected. (" + - net.jxta.id.ID.URNNamespace + "!=" + decoded.substring(0, colonAt) + ")"); - } - - // skip the namespace portion and the colon - decoded = decoded.substring(colonAt + 1); - - int dashAt = decoded.indexOf('-'); - - // there's a dash, right? - if (-1 == dashAt) { - throw new URISyntaxException(source.toString(), "URN jxta namespace IDFormat was missing."); - } - - // get the encoding used for this id - String format = decoded.substring(0, dashAt); - - Instantiator instantiator; - - try { - instantiator = factory.getInstantiator(format); - } catch (NoSuchElementException itsUnknown) { - instantiator = factory.getInstantiator("unknown"); - } - - result = instantiator.fromURNNamespaceSpecificPart(decoded); - - return result.intern(); - } - - /** - * Construct a new ID instance from a JXTA ID contained in a URI. - * - * @deprecated Use of URLs for representing JXTA IDs and this method are - * deprecated. Convert to using {@link #fromURI( URI )} instead. - * - * @param source URI which will be decoded to create a new ID instance. - * @return ID containing the new ID instance initialized from the URI. - * @throws UnknownServiceException Is thrown if the URI provided is of a - * format unrecognized by this JXTA implementation. - * @throws MalformedURLException Is thrown if the URI provided is not - * a valid, recognized JXTA URI. - */ - @Deprecated - public static ID fromURL(URL source) throws MalformedURLException, UnknownServiceException { - - ID result = null; - - // check the protocol - if (!ID.URIEncodingName.equalsIgnoreCase(source.getProtocol())) { - throw new UnknownServiceException("URI protocol type was not as expected."); - } - - String encoded = source.getFile(); - - // Decode the URN to convert any % encodings and convert it from UTF8. - String decoded = sun.net.www.protocol.urn.Handler.decodeURN(encoded); - - int colonAt = decoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new MalformedURLException("URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(decoded.substring(0, colonAt))) { - throw new MalformedURLException( - "URN namespace was not as expected. (" + net.jxta.id.ID.URNNamespace + "!=" + decoded.substring(0, colonAt) - + ")"); - } - - // skip the namespace portion and the colon - decoded = decoded.substring(colonAt + 1); - - int dashAt = decoded.indexOf('-'); - - // there's a dash, right? - if (-1 == dashAt) { - throw new UnknownServiceException("URN Encodingtype was missing."); - } - - // get the encoding used for this id - decoded = decoded.substring(0, dashAt); - - Instantiator instantiator; - - try { - instantiator = factory.getInstantiator(decoded); - } catch (NoSuchElementException itsUnknown) { - instantiator = factory.getInstantiator("unknown"); - } - - result = instantiator.fromURL(source); - - return result.intern(); - } - - /** - * Creates a new CodatID Instance. A new random CodatID is created for - * the provided Peer Group. This type of CodatID can be used as a - * canonical reference for dynamic content. - * - * @see net.jxta.codat.Codat - * - * @param groupID the group to which this content will belong. - * @return The newly created CodatID. - */ - public static CodatID newCodatID(PeerGroupID groupID) { - String useFormat = groupID.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newCodatID(groupID).intern(); - } - - /** - * Creates a new CodatID instance. A new CodatID is created for the - * provided Peer Group. This type of CodatID can be used as a - * canonical reference for dynamic content. - * - *

      This variant of CodatID allows you to create "Well-known" codats - * within the context of diverse groups. This can be useful for common - * services that need to do discovery without advertisements or for - * network organization services. Because of the potential for ID - * collisions and the difficulties with maintaining common service - * interfaces this variant of CodatID should be used with great caution - * and pre-planning. - * - * @see net.jxta.codat.Codat - * - * @param groupID the group to which this content will belong. - * @param seed The seed information which will be used in creating the - * codatID. The seed information should be at least four bytes in length, - * though longer values are better. - * @return The newly created CodatID. - */ - public static CodatID newCodatID(PeerGroupID groupID, byte[] seed) { - String useFormat = groupID.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newCodatID(groupID, seed).intern(); - } - - /** - * Creates a new CodatID instance. A new random CodatID is created for - * the provided Peer Group and contains a hash value for the Codat data. - * This type of Codat ID is most appropriate for static content. By - * including a hash value this form of Codat ID provides greater assurance - * of the canonical property of IDs. It also allows the document content - * returned when this ID is used to be verified to ensure it has not been - * altered. - * - * @see net.jxta.codat.Codat - * - * @param groupID The group to which this ID will belong. - * @param in The InputStream from which the content hash is calculated. - * The stream is read until EOF and then closed. - * @return The newly created CodatID. - * @throws IOException I/O Error reading document - */ - public static CodatID newCodatID(PeerGroupID groupID, InputStream in) throws IOException { - String useFormat = groupID.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newCodatID(groupID, in).intern(); - } - - /** - * Creates a new CodatID instance. A new CodatID is created for the - * provided Peer Group and contains a hash value for the Codat data. - * By including a hash value this form of Codat ID provides greater - * assurance of the canonical property of IDs. It also allows the - * document content returned when this ID is used to be verified to - * ensure it has not been altered. This type of Codat ID is most - * appropriate for static content. - * - *

      This variant of CodatID allows you to create "Well-known" codats - * within the context of diverse groups. This can be useful for common - * services that need to do discovery without advertisements or for - * network organization services. Because of the potential for ID - * collisions and the difficulties with maintaining common service - * interfaces this variant of CodatID should be used with great caution - * and pre-planning. - * - * @see net.jxta.codat.Codat - * - * @param groupID The group to which this ID will belong. - * @param seed The seed information which will be used in creating the - * codat ID. The seed information should be at least four bytes in length, - * though longer values are better. - * @param in The InputStream from which the content hash is calculated. - * The stream is read until EOF and then closed. - * @return The newly created CodatID. - * @throws IOException I/O Error reading document - */ - public static CodatID newCodatID(PeerGroupID groupID, byte[] seed, InputStream in) throws IOException { - String useFormat = groupID.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newCodatID(groupID, seed, in).intern(); - } - - /** - * Creates a new PeerID instance. A new random peer id will be generated. - * The PeerID will be a member of the provided group. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param groupID the group to which this PeerID will belong. - * @return The newly created PeerID. - */ - public static PeerID newPeerID(PeerGroupID groupID) { - String useFormat = groupID.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newPeerID(groupID).intern(); - } - - /** - * Creates a new PeerID instance. A new PeerID will be generated. - * The PeerID will be a member of the provided group. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param groupID the group to which this PeerID will belong. - * @param seed The seed information which will be used in creating the - * PeerID. The seed information should be at least four bytes in length, - * though longer values are better. - * @return The newly created PeerID. - */ - public static PeerID newPeerID(PeerGroupID groupID, byte[] seed) { - String useFormat = groupID.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newPeerID(groupID, seed).intern(); - } - - /** - * Creates a new PeerGroupID instance. A new random peer group id will be - * generated. The PeerGroupID will be created using the default ID Format. - * - * @see net.jxta.peergroup.PeerGroup - * - * @return The newly created PeerGroupID. - */ - public static PeerGroupID newPeerGroupID() { - return newPeerGroupID(factory.idNewInstances).intern(); - } - - /** - * Creates a new PeerGroupID instance using the specified ID Format. - * A new random peer group id will be generated. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param idformat The ID Format to be used for crating the Peer Group ID. - * @return The newly created PeerGroupID. - */ - public static PeerGroupID newPeerGroupID(String idformat) { - Instantiator instantiator = factory.getInstantiator(idformat); - - return instantiator.newPeerGroupID().intern(); - } - - /** - * Creates a new PeerGroupID instance. A new PeerGroupID will be - * generated using the provided seed information. The PeerGroupID will - * be created using the default ID Format. - * - *

      This method allows you to create "Well-known" PeerGroupIDs. - * This is similar to how the JXTA "World Peer Group" and "Net - * Peer Group". "Well-known" IDs can be useful for common services - * that need to do discovery without advertisements or for network - * organization services. Because of the potential for ID collisions - * and the difficulties with maintaining common service interfaces this - * variant of PeerGroupID should be used with great caution and - * pre-planning. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param seed The seed information which will be used in creating the - * PeerGroupID. The seed information should be at least four bytes in length, - * though longer values are better. - * @return The newly created PeerGroupID. - */ - public static PeerGroupID newPeerGroupID(byte[] seed) { - return newPeerGroupID(factory.idNewInstances, seed).intern(); - } - - /** - * Creates a new PeerGroupID instance. A new PeerGroupID will be - * generated using the provided seed information. The PeerGroupID will - * be created using the default ID Format. - * - *

      This method allows you to create "Well-known" PeerGroupIDs. - * This is similar to how the JXTA "World Peer Group" and "Net - * Peer Group". "Well-known" IDs can be useful for common services - * that need to do discovery without advertisements or for network - * organization services. Because of the potential for ID collisions - * and the difficulties with maintaining common service interfaces this - * variant of PeerGroupID should be used with great caution and - * pre-planning. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param idformat The ID Format of the new Peer Group ID. - * @param seed The seed information which will be used in creating the - * PeerGroupID. The seed information should be at least four bytes in length, - * though longer values are better. - * @return The newly created PeerGroupID. - */ - public static PeerGroupID newPeerGroupID(String idformat, byte[] seed) { - Instantiator instantiator = factory.getInstantiator(idformat); - - return instantiator.newPeerGroupID(seed).intern(); - } - - /** - * Creates a new PeerGroupID instance with the specified parent group. - * A new random peer group id will be generated. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param parent The group which will be the parent of this group. - * @return The newly created PeerGroupID. - */ - public static PeerGroupID newPeerGroupID(PeerGroupID parent) { - String useFormat = parent.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newPeerGroupID(parent).intern(); - } - - /** - * Creates a new PeerGroupID instance with the specified parent group. - * A new PeerGroupID will be generated using the provided seed - * information. - * - *

      This method allows you to create "Well-known" PeerGroupIDs. - * This is similar to how the JXTA "World Peer Group" and "Net - * Peer Group". "Well-known" IDs can be useful for common services - * that need to do discovery without advertisements or for network - * organization services. Because of the potential for ID collisions - * and the difficulties with maintaining common service interfaces this - * variant of PeerGroupID should be used with great caution and - * pre-planning. - * - * @see net.jxta.peergroup.PeerGroup - * - * @param parent The group which will be the parent of this group. - * @param seed The seed information which will be used in creating the - * PeerGroupID. The seed information should be at least four bytes in length, - * though longer values are better. - * @return The newly created PeerGroupID. - */ - public static PeerGroupID newPeerGroupID(PeerGroupID parent, byte[] seed) { - String useFormat = parent.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newPeerGroupID(parent, seed).intern(); - } - - /** - * Creates a new PipeID instance. A new random PipeID will be generated. - * - * @param groupID The group to which this Pipe ID will belong. - * @return The newly created PipeID. - */ - public static PipeID newPipeID(PeerGroupID groupID) { - String useFormat = groupID.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newPipeID(groupID).intern(); - } - - /** - * Creates a new PipeID instance. A new pipe id will be generated with the - * provided seed information. The Pipe ID will be a member of the provided - * group. - * - *

      This variant of PipeID allows you to create "Well-known" pipes - * within the context of diverse groups. This can be useful for common - * services that need to do discovery without advertisements or for - * network organization services. Because of the potential for ID - * collisions and the difficulties with maintaining common service - * interfaces this variant of PipeID should be used with great caution - * and pre-planning. - * - * @param groupID the group to which this Pipe ID will belong. - * @param seed The seed information which will be used in creating the - * pipeID. The seed information should be at least four bytes in length, - * though longer values are better. - * @return the newly created PipeID. - */ - public static PipeID newPipeID(PeerGroupID groupID, byte[] seed) { - String useFormat = groupID.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newPipeID(groupID, seed).intern(); - } - - /** - * Creates a new ModuleClassID instance. A new random ModuleClassID will - * be generated with a zero value role identifier. This form of - * ModuleClassID is appropriate for cases where the module does not - * need to be distinguished from other instances of the same Module. - * The ModuleClassID will be created using the default ID Format. - * - * @see net.jxta.platform.Module - * - * @return The newly created ModuleClassID. - */ - public static ModuleClassID newModuleClassID() { - return newModuleClassID(factory.idNewInstances).intern(); - } - - /** - * Creates a new ModuleClassID instance using the specified ID Format. - * A new random ModuleClassID will be generated with a zero value role - * identifier. This form of ModuleClassID is appropriate for cases - * where the module does not need to be distinguished from other - * instances of the same Module. - * - * @see net.jxta.platform.Module - * - * @param idformat The ID Format of the new ModuleClassID. - * @return The newly created ModuleClassID. - */ - public static ModuleClassID newModuleClassID(String idformat) { - Instantiator instantiator = factory.getInstantiator(idformat); - - return instantiator.newModuleClassID().intern(); - } - - /** - * Creates a new ModuleClassID instance. A new random ModuleClassID will - * be generated with a a random value role identifier and a base class of - * the provided ModuleClassID. This form of ModuleClassID is - * appropriate for cases where it is necessary to distinguish instances - * of the same service interface. - * - * @see net.jxta.platform.Module - * - * @param baseClass The ModuleClassID which will be used as a base - * class for this new role value instance. - * @return The newly created ModuleClassID. - */ - public static ModuleClassID newModuleClassID(ModuleClassID baseClass) { - String useFormat = baseClass.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newModuleClassID(baseClass).intern(); - } - - /** - * Creates a new ModuleSpecID instance. A new random ModuleSpecID will - * be generated. - * - * @see net.jxta.platform.Module - * - * @param baseClass The ModuleClassID which will be used as a base - * class for this new ModuleSpecID. - * @return The newly created ModuleSpecID. - */ - public static ModuleSpecID newModuleSpecID(ModuleClassID baseClass) { - String useFormat = baseClass.getIDFormat(); - - // is the group netpg or worldpg? - if (IDFormat.INSTANTIATOR.getSupportedIDFormat().equals(useFormat)) { - useFormat = factory.idNewInstances; - } - - Instantiator instantiator = factory.getInstantiator(useFormat); - - return instantiator.newModuleSpecID(baseClass).intern(); - } - - /** - * This method should be used instead of using - * {@code new java.net.URL( )} to create URLs for use with IDFactory. - * URL construction can cause classes to be loaded using the system - * classLoader (JXTA IDs require the class - * {@code sun.net.www.protocol.urn.Handler} for Sun JVMs). - * This class loading will fail in many environments such as web-servers, - * servlet containers, application servers, or java web start where a user - * class loader is used to load all JXTA resources. - * - * @deprecated You should convert code which creates JXTA IDs to instead - * use {@code IDFactory.fromURI( new URI(...) )}. This method was only - * provided to overcome problems with registration of URL handlers in - * foreign class loader environments (Servlets, Applets, JNLP, etc.). - * - * @param protocol The protocol for this URL - * @param host The host for this URL - * @param file The file for this URL - * @return a newly created URL for the resource specified. - * @throws MalformedURLException if an unknown protocol is specified. - */ - @Deprecated - public static URL jxtaURL(String protocol, String host, String file) throws MalformedURLException { - return new URL(protocol, host, -1, file, sun.net.www.protocol.urn.Handler.handler); - } - - /** - * This method should be used instead of using - * {@code new java.net.URL( )} to create URLs for use with IDFactory. - * URL construction can cause classes to be loaded using the system - * classLoader (JXTA IDs require the class - * {@code sun.net.www.protocol.urn.Handler} for Sun JVMs). - * This class loading will fail in many environments such as web-servers, - * servlet containers, application servers, or java web start where a user - * class loader is used to load all JXTA resources. - * - * @deprecated You should convert code which creates JXTA IDs from strings - * to instead use {IDFactory.fromURI( new URI(String) )}. This - * method was only provided to overcome problems with registration of URL - * handlers in foreign class loader environments (Servlets, Applets, JNLP, - * etc.). - * - * @param uri The {@code String} to parse as a URL. - * @return a newly created URL for the resource specified. - * @throws MalformedURLException if an unknown protocol is specified. - */ - @Deprecated - public static URL jxtaURL(String uri) throws MalformedURLException { - final String file = net.jxta.id.ID.URNNamespace + ":"; - URL urlCnxt = jxtaURL(net.jxta.id.ID.URIEncodingName, "", file); - - return new URL(urlCnxt, uri); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/jxta/IDFormat.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/jxta/IDFormat.java deleted file mode 100644 index 80fa3c21..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/jxta/IDFormat.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.id.jxta; - - -import net.jxta.id.IDFactory; - - -/** - * The 'jxta' ID Format is used for the presentation of a limited number of - * well-known ids. These are the null id, the world peer group id, and the - * default net peer group id. JXTA depends on being able to refer to these - * standard entities in a common way regardless of what other id formats are - * used, indeed this ID Format and these ids exist so that there are not a - * different representations for the ids of these entities with each ID Format. - * - *

      Rather than return its own version of these well known IDs, each ID - * Format MUST return these IDs as appropriate. - * - *

        - *
      • the null id - the NullID is often used as a placeholder in fields which - * are uninitialized.
      • - * - *
      • the world peer group id - the id of the world peer group.
      • - * - *
      • the default net peer group id - the id of the default net peer group.
      • - *
      - * - * @see net.jxta.id.ID - * @see net.jxta.id.IDFactory - @see JXTA Protocols Specification : IDs - @see JXTA Protocols Specification : ?jxta? ID Format - * - **/ -public final class IDFormat { - - /** - * The name associated with this ID Format. - */ - final static String JXTAFormat = "jxta"; - - /** - * The instantiator for this ID Format which is used by the IDFactory. - * - * @since JXTA 1.0 - **/ - public static final IDFactory.URIInstantiator INSTANTIATOR = new Instantiator(); - - /** - * Private Constructor. This class cannot be instantiated. - **/ - private IDFormat() {} -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/jxta/Instantiator.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/jxta/Instantiator.java deleted file mode 100644 index cb6f438d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/jxta/Instantiator.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.id.jxta; - - -import net.jxta.codat.CodatID; -import net.jxta.id.ID; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.pipe.PipeID; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.UnknownServiceException; -import java.security.ProviderException; - - -/** - * Instantiator for the 'jxta' ID Format. - * - * @see net.jxta.id.ID - * @see net.jxta.id.IDFactory - * @see net.jxta.id.jxta.IDFormat - */ -final class Instantiator implements net.jxta.id.IDFactory.URIInstantiator { - - /** - * This table maps the textual values of the well known ids to the - * singleton classes which match those textual names. - */ - final static Object[][] wellKnownIDs = { - { net.jxta.id.ID.nullID.getUniqueValue(), net.jxta.id.ID.nullID} - , - - { net.jxta.peergroup.PeerGroupID.worldPeerGroupID.getUniqueValue(), net.jxta.peergroup.PeerGroupID.worldPeerGroupID} - , - - { - net.jxta.peergroup.PeerGroupID.defaultNetPeerGroupID.getUniqueValue() - , - net.jxta.peergroup.PeerGroupID.defaultNetPeerGroupID} - }; - - /** - * {@inheritDoc} - */ - public String getSupportedIDFormat() { - return IDFormat.JXTAFormat; - } - - /** - * {@inheritDoc} - */ - @Deprecated - public ID fromURL(URL source) throws MalformedURLException, UnknownServiceException { - - // check the protocol - if (!ID.URIEncodingName.equalsIgnoreCase(source.getProtocol())) { - throw new UnknownServiceException("URI protocol type was not as expected."); - } - - String encoded = source.getFile(); - - int colonAt = encoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new UnknownServiceException("URN namespace was missing."); - } - - // check the namespace - if (!ID.URNNamespace.equalsIgnoreCase(encoded.substring(0, colonAt))) { - throw new UnknownServiceException("URN namespace was not as expected."); - } - - // skip the namespace portion and the colon - encoded = encoded.substring(colonAt + 1); - - int dashAt = encoded.indexOf('-'); - - // there's a dash, right? - if (-1 == dashAt) { - throw new UnknownServiceException("JXTA ID Format was missing."); - } - - if (!encoded.substring(0, dashAt).equals(getSupportedIDFormat())) { - throw new UnknownServiceException("JXTA ID Format was not as expected."); - } - - for (Object[] wellKnownID : wellKnownIDs) { - if (encoded.equalsIgnoreCase(wellKnownID[0].toString())) { - return (ID) wellKnownID[1]; - } - } - - throw new MalformedURLException("unrecognized id"); - } - - /** - * {@inheritDoc} - */ - public CodatID newCodatID(PeerGroupID groupID) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public CodatID newCodatID(PeerGroupID groupID, byte[] seed) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public CodatID newCodatID(PeerGroupID groupID, InputStream in) throws IOException { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public CodatID newCodatID(PeerGroupID groupID, byte[] seed, InputStream in) throws IOException { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public PeerID newPeerID(PeerGroupID groupID) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public PeerID newPeerID(PeerGroupID groupID, byte[] seed) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID() { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(byte[] seed) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(net.jxta.peergroup.PeerGroupID parent) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(net.jxta.peergroup.PeerGroupID parent, byte[] seed) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public PipeID newPipeID(PeerGroupID groupID) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public PipeID newPipeID(PeerGroupID groupID, byte[] seed) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public ModuleClassID newModuleClassID() { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public ModuleClassID newModuleClassID(ModuleClassID classID) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public ModuleSpecID newModuleSpecID(ModuleClassID classID) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - */ - public ID fromURI(URI source) throws URISyntaxException { - - // check the protocol - if (!ID.URIEncodingName.equalsIgnoreCase(source.getScheme())) { - throw new URISyntaxException(source.toString(), "URI scheme was not as expected."); - } - - String decoded = source.getSchemeSpecificPart(); - - int colonAt = decoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new URISyntaxException(source.toString(), "URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(decoded.substring(0, colonAt))) { - throw new URISyntaxException(source.toString() - , - "URN namespace was not as expected. (" + net.jxta.id.ID.URNNamespace + "!=" + decoded.substring(0, colonAt) - + ")"); - } - - // skip the namespace portion and the colon - decoded = decoded.substring(colonAt + 1); - - return fromURNNamespaceSpecificPart(decoded); - } - - /** - * {@inheritDoc} - */ - public ID fromURNNamespaceSpecificPart(String source) throws URISyntaxException { - int dashAt = source.indexOf('-'); - - // there's a dash, right? - if (-1 == dashAt) { - throw new URISyntaxException(source, "URN jxta namespace IDFormat was missing."); - } - - if (!source.substring(0, dashAt).equals(getSupportedIDFormat())) { - throw new URISyntaxException(source, "JXTA ID Format was not as expected."); - } - - for (Object[] wellKnownID : wellKnownIDs) { - if (source.equalsIgnoreCase(wellKnownID[0].toString())) { - return (ID) wellKnownID[1]; - } - } - - throw new URISyntaxException(source, "unrecognized id"); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/jxta/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/jxta/package.html deleted file mode 100644 index 2e98afe4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/jxta/package.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - The 'jxta' ID Format is used for the presentation of a limited number of - well-known ids. These are the null id, the world peer group id, and the - default net peer group id. JXTA depends on being able to refer to these - standard entities in a common way regardless of what other id formats are - used, indeed this ID format and these ids exist so that there are not a - different representations for the ids of these entities with each id format. - -

      Rather than return its own version of these well known ids, each ID - format MUST return these IDs as appropriate. - -

        -
      • the null id - the NullID is often used as a placeholder in fields which - are uninitialized.
      • - -
      • the world peer group id - the id of the world peer group.
      • - -
      • the default net peer group id - the id of the default net peer group.
      • -
      - - @see JXTA Protocols Specification : IDs - @see JXTA Protocols Specification : ?jxta? ID Format - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/package.html deleted file mode 100644 index 85423115..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/id/package.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - IDs are used within JXTA to refer to peers, peer groups, pipes and other - types of resources. - - @see JXTA Protocols Specification : IDs - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/logging/Logging.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/logging/Logging.java deleted file mode 100644 index b1624cd9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/logging/Logging.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) 2001-2004 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.logging; - - -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * This class defines constants for JXTA JSE's logging facilities. In this - * implementation the constants are initialized based upon the value of the - * Java System property {@code net.jxta.logging.Logging}. This implementation - * defines all of the public constants as {@code final} which enables the - * JVM/JIT to optimize out the logging code when appropriately configured. - *

      - *

      Alternate implementations of this class could; - *

      - *

        - *
      • Initialize the public constants with manifest constants, ie. - * {@code true} or {@code false} which would allow the Java compiler to - * optimize out logging code at compile time.
      • - *

        - *

      • Remove the {@code final} qualifier from the constants and provide - * additional methods to dynamically set the logging configuration at runtime. - *
      • - *
      - * - * To control logging within applications : - * - *
      - * 
      - * System.setProperty("net.jxta.logging.Logging", "FINEST");
      - * System.setProperty("net.jxta.level", "FINEST");
      - * System.setProperty("java.util.logging.config.file", "/home/userhome/logging.properties");
      - * 
      - * 
      - * - *

      - * Sample logging properties : - *

      - *

      - * 
      - * # default file output is in user's home directory.
      - * java.util.logging.FileHandler.pattern = %h/java%u.log
      - * java.util.logging.FileHandler.limit = 50000
      - * java.util.logging.FileHandler.count = 1
      - * java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter
      - * 
      - * # Limit the message that are printed on the console to INFO and above
      - * java.util.logging.ConsoleHandler.level = FINEST
      - * java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
      - *
      - * # Facility specific properties.
      - * # Provides extra control for each logger.
      - * #
      - * # For example, set the net.jxta.impi.pipe.PipeResolver logger to only log SEVERE
      - * # messages:
      - * net.jxta.impi.pipe.PipeResolver.level = FINEST
      - * 
      - * 
      - */ -public final class Logging { - - /** - * Our Logger ! - */ - private final static Logger LOG = Logger.getLogger(Logging.class.getName()); - - /** - * The name of the system property from which we will attempt to read our - * logging configuration. - */ - public final static String JXTA_LOGGING_PROPERTY = "net.jxta.logging.Logging"; - - /** - * The default logging level. - */ - private final static Level DEFAULT_LOGGING_LEVEL = Level.FINEST; - - /** - * The logging level for this run. - */ - public final static Level MIN_SHOW_LEVEL; - - /** - * Is Level.FINEST enabled? - */ - public final static boolean SHOW_FINEST; - - /** - * Is Level.FINER enabled? - */ - public final static boolean SHOW_FINER; - - /** - * Is Level.FINE enabled? - */ - public final static boolean SHOW_FINE; - - /** - * Is Level.CONFIG enabled? - */ - public final static boolean SHOW_CONFIG; - - /** - * Is Level.INFO enabled? - */ - public final static boolean SHOW_INFO; - - /** - * Is Level.WARNING enabled? - */ - public final static boolean SHOW_WARNING; - - /** - * Is Level.SEVERE enabled? - */ - public final static boolean SHOW_SEVERE; - - /* Initialize the constants */ - static { - Level setLevel = DEFAULT_LOGGING_LEVEL; - - try { - String propertyLevel = System.getProperty(JXTA_LOGGING_PROPERTY); - - if (null != propertyLevel) { - setLevel = Level.parse(propertyLevel); - } - } catch (SecurityException disallowed) { - LOG.log(Level.WARNING, "Could not read configuration property.", disallowed); - } - - // Set the default level for the JXTA packages so that everything below - // inherits our default. - MIN_SHOW_LEVEL = setLevel; - - SHOW_FINEST = MIN_SHOW_LEVEL.intValue() <= Level.FINEST.intValue(); - SHOW_FINER = MIN_SHOW_LEVEL.intValue() <= Level.FINER.intValue(); - SHOW_FINE = MIN_SHOW_LEVEL.intValue() <= Level.FINE.intValue(); - SHOW_CONFIG = MIN_SHOW_LEVEL.intValue() <= Level.CONFIG.intValue(); - SHOW_INFO = MIN_SHOW_LEVEL.intValue() <= Level.INFO.intValue(); - SHOW_WARNING = MIN_SHOW_LEVEL.intValue() <= Level.WARNING.intValue(); - SHOW_SEVERE = MIN_SHOW_LEVEL.intValue() <= Level.SEVERE.intValue(); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Logging enabled for level : " + MIN_SHOW_LEVEL); - } - } - - /** - * This class is not meant be instantiated. - */ - private Logging() {} -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/logging/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/logging/package.html deleted file mode 100644 index d2b0468f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/logging/package.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - Provides global control over use of logging by JXSE. - -

      The provided Logging.java file is only one of several - practical implementations. The implementation strategies for - Logging.java fall into three basic categories: - -

      -
      final static SHOW_* = <value>;
      -
      All of the SHOW_ fields are defined with literal - expressions allowing their value to be calculated at compile time. This - varient allows JXSE to be compiled such that logging is entirely - disabled (if <value> is false) and - the logging code is not even present in the compiled bytecode.
      - -
      final static SHOW_*;
      -
      The default. All of the SHOW_ fields are defined in - a static initializer based upon a calculated value. Since their value - cannot be known at compile time the resulting bytecode will contain - the conditional logging code. Since the SHOW_ fields are - final the JVM JIT can still optimize the bytecode as it is - dynamically compiled.
      - -
      static SHOW_*;
      -
      All of the SHOW_ fields are defined in - a static initializer based upon a calculated value and may be redefined - at any time. Since their value cannot be known at compile time the - resulting bytecode will contain the conditional logging code. The values - of the SHOW_ may be changed at any time to dynamically - alter the logging behaviour. -
      -
      - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/Authenticator.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/Authenticator.java deleted file mode 100644 index 8f197365..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/Authenticator.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.membership; - - -import net.jxta.credential.AuthenticationCredential; - - -/** - * An Authenticator is returned by the - * {@linkplain MembershipService#apply(AuthenticationCredential) apply()} to the - * Membership Service of a peergroup. The Membership - When the authenticator has been completed it is - * returned to the Membership Service via the "Join" operation. - * - *

      The mechanism for completing the authentication object is unique for each - * authentication method. (That's the whole point of writing a Membership - * Service). The only common operation is isReadyForJoin, which - * provides information as to whether you have completed the authenticator - * correctly. - * - * @see net.jxta.membership.MembershipService - * @see net.jxta.credential.Credential - * @see net.jxta.credential.AuthenticationCredential - */ -public interface Authenticator { - - /** - * Returns the name of this authentication method. This should be the same - * name which was used in the Authentication credential. - * - * @return String containing the name of this authentication method. - **/ - public String getMethodName(); - - /** - * Return the Authentication Credential associated with this authenticator, - * if any. - * - * @return the AutheticationCredential which was provided to the - * {@link MembershipService#apply(AuthenticationCredential)}. - **/ - public AuthenticationCredential getAuthenticationCredential(); - - /** - * Returns the service which generated this authenticator. This is the - * service which provided this authenticator and the service which will - * accept this authenticator when the authenticator is - * completed. - * - * @return the MembershipService service associated with this authenticator. - **/ - public MembershipService getSourceService(); - - /** - * Returns true if this Authenticator has been satisfied and is ready - * for submission to {@link MembershipService#join(Authenticator)}. Some - * authenticators may behave asynchronously and this method can be used to - * determine if the authentication process has completed. - *

      This method provides no distinction between incomplete authentication - * and failed authentication. - * - * @see MembershipService#join(Authenticator) - * - * @return true if the authenticator object is complete and ready for - * submitting to the Membership Service service for - * {@link MembershipService#join(Authenticator)}, otherwise false. - **/ - public boolean isReadyForJoin(); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/InteractiveAuthenticator.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/InteractiveAuthenticator.java deleted file mode 100644 index 24a2322e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/InteractiveAuthenticator.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.membership; - - -/** - * Extension to standard Authenticator for authenticators which support - * interactive authentication with a human user. - * - *

      May be requested as authentication method - * "InteractiveAuthentication" of Membership services which support - * it. (this will be an alias for one of the service's own methods). - **/ -public interface InteractiveAuthenticator extends Authenticator { - - /** - * Perform user interface interaction with user. If result is - * false then - * {@link net.jxta.membership.Authenticator#isReadyForJoin()} will - * also return false. - * - * @return true if the interaction was not cancelled otherwise - * false. - **/ - public boolean interact(); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/MembershipService.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/MembershipService.java deleted file mode 100644 index 398d2058..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/MembershipService.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.membership; - - -import java.beans.PropertyChangeListener; -import java.util.Enumeration; - -import net.jxta.credential.AuthenticationCredential; -import net.jxta.credential.Credential; -import net.jxta.document.Element; -import net.jxta.service.Service; - -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.ProtocolNotSupportedException; - - -/** - * Allows a peer to establish an identity within a peer group. Identities are - * used by services and applications to determine the capabilities available to - * peers. A peer have any number of identities at one time. Once an identity - * has been established a Credential object is available which allows the peer - * to prove that it rightfully has that identity. - * - *

      The sequence for associating an identity with a peer within a peer - * group is as follows: - * - *

      - * - * - * - * - * - * - * - * - *
      ApplyAn application or service provides the membership service with an - * initial credential which may be used by the membership service to determine - * the method of authentication to be used for establishing the identity. - * If the membership service implementations allows authentication using the - * requested mechanism then an {@link Authenticator} object is returned. - *
      JoinThe application or service completes the authenticator. This may involve - * presenting a user interface, completing challenges, etc. How the - * authenticator is completed depends on the type of membership service and - * authenticator in use. - * - *

      Once completed, the authenticator is returned to the membership service. - * If the authenticator has been correctly completed, a new credential for the - * new identity will be available to the peer from the membership service. - *

      ResignWhenever the application or service no longer wishes to no longer use the - * identities it has claimed, it may resign from the peergroup. This will cause - * any identity credentials held by the membership service to discarded. - *
      - * - * @see net.jxta.credential.Credential - * @see net.jxta.credential.AuthenticationCredential - * - */ -public interface MembershipService extends Service { - - /** - * Property name for the default credential bound property. - */ - public final static String DEFAULT_CREDENTIAL_PROPERTY = "defaultCredential"; - - /** - * Property name for credential addition bound property. - */ - public final static String ADD_CREDENTIAL_PROPERTY = "addCredential"; - - /** - * Request the necessary credentials to join the group with which this - * service is associated. - * - * @param application The authentication Credential associated with this - * membership application. See - * {@link net.jxta.credential.AuthenticationCredential} - * for more information. - * @return An Authenticator for the membership service. - * - * @throws PeerGroupException Thrown in the event of errors. - * @throws ProtocolNotSupportedException if the authentication method requested - * in the application is not supported by this service. - */ - public Authenticator apply(AuthenticationCredential application) throws PeerGroupException, ProtocolNotSupportedException; - - /** - * Join the group by virtue of the completed authentication provided. - * - * @param authenticated the completed authentication. - * @return Credential the credential for this completed authentication. - * @throws PeerGroupException Thrown in the event of errors. - */ - public Credential join(Authenticator authenticated) throws PeerGroupException; - - /** - * Resign all credentials which were previously gained through prior - * {@link #join(Authenticator) join()} operations. - * - * @throws PeerGroupException Thrown in the event of errors. - */ - public void resign() throws PeerGroupException; - - /** - * Returns the default credential for this peer. - * - * @return The current default Credential or {@code null} if there is no - * current default. - * @throws PeerGroupException Thrown in the event of errors. - */ - public Credential getDefaultCredential() throws PeerGroupException; - - /** - * Returns the current credentials for this peer. - * - * @return Enumeration of the Credentials currently associated with this - * peer for this peergroup. - * @throws PeerGroupException Thrown in the event of errors. - */ - public Enumeration getCurrentCredentials() throws PeerGroupException; - - /** - * Returns the authentication credentials which were used to establish the - * current identities. - * - * @deprecated This interface is being removed in favour of individual - * Credentials providing their AuthenticationCredential as appropriate. - * - * @return Enumeration of the AuthenticationCredentials which were used to - * establish the current identities. - * @throws PeerGroupException Thrown in the event of errors. - */ - @Deprecated - public Enumeration getAuthCredentials() throws PeerGroupException; - - /** - * Given a fragment of a StructuredDocument, reconstruct a Credential object - * from that fragment. - * - * @return Credential The created credential - * @param element The StructuredDocument fragment to use for building the - * credential. - * @throws PeerGroupException Thrown in the event of errors. - * @throws Exception Thrown in the event of errors. - */ - public Credential makeCredential(Element element) throws PeerGroupException, Exception; - - /** - * Add a listener - * - * @param listener the listener - */ - public void addPropertyChangeListener(PropertyChangeListener listener); - - /** - * Add a listener. Available properties from all Membership Services are : - * - *

        - *
      • {@code defaultCredential}
      • - *
      • {@code addCredential}
      • - *
      - * - *

      Membership Services may offer additional properties. - * - * @param propertyName The property to watch - * @param listener The listener - */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener); - - /** - * Remove a listener - * - * @param listener the listener - */ - public void removePropertyChangeListener(PropertyChangeListener listener); - - /** - * Remove a listener - * - * @param propertyName the property which was watched - * @param listener the listener - */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/doc-files/memberAndAccess.png b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/doc-files/memberAndAccess.png deleted file mode 100644 index 993ca71b..00000000 Binary files a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/doc-files/memberAndAccess.png and /dev/null differ diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/package.html deleted file mode 100644 index 44e272cc..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/membership/package.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - The Membership Service allows a peer to establish an identity within a peer - group. A peer have any number of identities at one time. Once an identity - has been established a credential object is available which allows the peer - to prove that it rightfully has that identity. Applications and services - may restrict certain operations to specific identities. JXTA J2SE provides - the Access Service to assist applications in matching privledges to - identities. - -

      The Membership Service is not associated with a particular JXTA - protocol. Each Membership Service implementation is responsible for its own - protocol definition (if any). This approach is used primarily so that JXTA - bridges well to existing common Membership and Access technologies. For - example; PKI, Kerberos, NTLM and API based interfaces such as PAM and JAAS. - -

      - Diagram
-showing common flow of usage for Membership and Access Services - - @see net.jxta.credential.Credential - @see net.jxta.credential.AuthenticationCredential - @see net.jxta.access.AccessService - @see JXTA Protocols Specification : Protocols - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorEvent.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorEvent.java deleted file mode 100644 index befd0941..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorEvent.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import net.jxta.peergroup.*; -import net.jxta.peer.*; - - -/** - * Information regarding a Remote Monitor's Report - **/ -public class MonitorEvent { - - /** Report received and is available in the event **/ - public static final int OK = 200; - - /** Report will not come because the registration was cancelled locally **/ - public static final int CANCELLED_LOCALLY = 201; - - /** Report will not come because the registration was cancelled remotely **/ - public static final int CANCELLED_REMOTELY = 202; - - /** Report will not come because the of a Timeout **/ - public static final int TIMEOUT = 203; - - /** Report will not come because the Remote peer has refused it (for security, not supported or load reasons) **/ - public static final int REFUSED = 204; - - /** Report will not come because the requested report rate is not supported/invalid **/ - public static final int INVALID_REPORT_RATE = 205; - - /** Report will not come because the provided MonitorFilter was invalid **/ - public static final int INVALID_MONITOR_FILTER = 206; - - /** Further Reports will not come because the lease was cancelled **/ - public static final int LEASE_CANCELLED = 207; - - /** Further Reports will not come because the lease renewal request did not receive a response. - * In all likelihood the remote peer has failed (ie crashed) - **/ - public static final int LEASE_RENEWAL_TIMEOUT = 208; - - /** Internal Error processing Reports, probably due to a bad Monitor Implementation **/ - public static final int ERROR = 209; - - /** Further Reports will not come because this PeerGroup was destroyed locally **/ - public static final int PEERGROUP_DESTROYED = 210; - - private int type; - private int requestId; - private PeerID peerID; - private PeerGroupID peerGroupID; - private MonitorFilter monitorFilter; // FIX-ME: Is this necessary? - private long reportRate; // FIX-ME: Is this necessary? - private long leaseTime; // FIX-ME: Is this necessary? - private MonitorReport monitorReport; - - private MonitorEvent() {} - - public MonitorEvent(PeerGroupID peerGroupID, MonitorReport monitorReport) { - this.peerGroupID = peerGroupID; - this.monitorReport = monitorReport; - } - - /** - * Get the Type of Event (one of the above constants) - * - */ - public int getType() { - return type; - } - - /** - * PeerID of reporting Peer. My PeerID if local - */ - public PeerID getPeerID() { - return peerID; - } - - /** - * PeerGroup of reported event - */ - public PeerGroupID getPeerGroupID() { - return peerGroupID; - } - - /** - * MonitorFilter provided when the report was requested - */ - public MonitorFilter getMonitorFilter() { - return monitorFilter; - } - - /** - * Reporting rate (unless Cumulative) specified when the report was requested - */ - public long getReportRate() { - return reportRate; - } - - /** - * Most recent Lease time granted (not specified if a cumulative Report) - */ - public long getLeaseTime() { - return leaseTime; - } - - /** - * Get the corresponding MonitorReport - */ - public MonitorReport getMonitorReport() { - return monitorReport; - } - - /** - * The Validated MonitorFilter from the registration or query - * - * @return MonitorFilter - */ - public MonitorFilter getValidMonitorFilter() { - return monitorFilter; - } - - /** - * Convenience factory method - */ - public static MonitorEvent createRemoteMonitorReportEvent(PeerID peerID, int requestId, MonitorReport monitorReport) { - MonitorEvent event = new MonitorEvent(); - - event.type = OK; - event.peerID = peerID; - event.requestId = requestId; - event.monitorReport = monitorReport; - return event; - } - - /** - * Convenience factory method - */ - public static MonitorEvent createFailureEvent(int type, PeerID peerID, int requestId) { - MonitorEvent event = new MonitorEvent(); - - event.type = type; - event.peerID = peerID; - event.requestId = requestId; - return event; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorException.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorException.java deleted file mode 100644 index ca4df043..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorException.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import net.jxta.exception.*; - -@SuppressWarnings("serial") -public class MonitorException extends JxtaException { - - /** Monitoring Not Supported **/ - public final static int METERING_NOT_SUPPORTED = 7000; - - /** Error during Serialization/Deserialization **/ - public final static int SERIALIZATION = 7001; - - /** Monitor Report Provided **/ - public final static int MONITOR_REPORT = 7002; - - /** Invalid MonitorFilter **/ - public final static int FILTER_EXCEPTION = 7003; - - private int type; - - /** - * MonitorException - * - * @param type (see above) - * @param message - */ - public MonitorException(int type, String message) { - super(message); - this.type = type; - } - - /** - * MonitorException - * - * @param type - * @param message - * @param e - */ - public MonitorException(int type, String message, Exception e) { - super(message, e); - this.type = type; - } - - /** - * get Type of event (see constants above) - */ - public int getType() { - return type; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorFilter.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorFilter.java deleted file mode 100644 index 06acba89..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorFilter.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import net.jxta.document.*; -import net.jxta.id.*; -import net.jxta.platform.*; -import net.jxta.util.documentSerializable.*; -import java.util.*; -import java.net.*; -import net.jxta.exception.*; -import net.jxta.util.*; - - -/** - * A Monitor Filter specifies which service-specific metrics should be obtained by the Monitor. - * It contains a collection of ServiceMonitor specific ServiceMonitorFilters. - * - **/ -public class MonitorFilter implements DocumentSerializable { - private String description; - private Map serviceMonitorFilters = new HashMap(); - private List unknownModuleClassIDs; - - /** - * MonitorFilter - * - **/ - public MonitorFilter() {} - - /** - * MonitorFilter - * - * @param description - **/ - public MonitorFilter(String description) { - this.description = description; - } - - /** - * Add a ServiceMonitorFilter to this MonitorFilter - * - * @param serviceMonitorFilter Service Specific Filter - * @exception MonitorFilterException - * @return ServiceMonitorFilter Modified Filter to the capabilities of the service - **/ - public ServiceMonitorFilter addServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter) throws MonitorFilterException { - ModuleClassID moduleClassID = serviceMonitorFilter.getModuleClassID(); - - if (serviceMonitorFilters.get(moduleClassID) != null) { - throw new MonitorFilterException("Attempt to add a second Monitor Filter for: " + moduleClassID); - } - serviceMonitorFilters.put(moduleClassID, serviceMonitorFilter); - return serviceMonitorFilter; - } - - /** - * Get ServiceMonitorFilter subfilter - * - * @param moduleClassID ServiceMonitor's moduleClassID - * @return ServiceMonitorFilter SubFilter or null if not found - **/ - public ServiceMonitorFilter getServiceMonitorFilter(ModuleClassID moduleClassID) { - return serviceMonitorFilters.get(moduleClassID); - } - - /** - * remove ServiceMonitorFilter - * - * @param moduleClassID ServiceMonitor's moduleClassID - **/ - public void removeServiceMonitorFilter(ModuleClassID moduleClassID) { - serviceMonitorFilters.remove(moduleClassID); - } - - /** - * Get the number of subfilters - * - * @return int - **/ - public int getServiceMonitorFilterCount() { - return serviceMonitorFilters.size(); - } - - /** - * get ModuleClassIDs of contained subfilters - * - * @return Iterator of ServiceMonitor ClassIDs - **/ - public Iterator getModuleClassIDs() { - return serviceMonitorFilters.keySet().iterator(); - } - - /** - * Get Iterator of all ServiceMonitorFilters subfilters - * - * @return Iterator of all ServiceMonitorFilters subfilters - **/ - public Iterator getServiceMonitorFilters() { - return serviceMonitorFilters.values().iterator(); - } - - /** - * Were any filters removed from this MonitorFilter (particularly when received remotely and deserialized) - * - **/ - public boolean isUnknownModuleClassIDs() { - return (unknownModuleClassIDs != null); - } - - /** - * Get a list of ModuleClassIDs for subfilters that could not be deserialized because they weren't registered - * @see MonitorResources - * - * @return Iterator - **/ - public Iterator getUnknownModuleClassIDs() { - if (unknownModuleClassIDs != null) { - return unknownModuleClassIDs.iterator(); - } else { - return new LinkedList().iterator(); - } - } - - /** - * Get Description - * - **/ - public String getDescription() { - return description; - } - - /** - * {@inheritDoc} - **/ - public void serializeTo(Element element) throws DocumentSerializationException { - DocumentSerializableUtilities.addString(element, "description", description); - - for (Iterator i = serviceMonitorFilters.values().iterator(); i.hasNext();) { - ServiceMonitorFilter serviceMonitorFilter = (ServiceMonitorFilter) i.next(); - - Element serviceElement = DocumentSerializableUtilities.createChildElement(element, "service"); - - DocumentSerializableUtilities.addString(serviceElement, "moduleClassID" - , - serviceMonitorFilter.getModuleClassID().toString()); - DocumentSerializableUtilities.addDocumentSerializable(serviceElement, "serviceFilter", serviceMonitorFilter); - } - } - - /** - * {@inheritDoc} - **/ - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element serviceElement = (TextElement) e.nextElement(); - String tagName = (String) serviceElement.getKey(); - - if (tagName.equals("service")) { - try { - ModuleClassID moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI(DocumentSerializableUtilities.getString(serviceElement, "moduleClassID", "ERROR"))); - - try { - ServiceMonitorFilter serviceMonitorFilter = MonitorResources.createServiceMonitorFilter(moduleClassID); - - serviceMonitorFilter.init(moduleClassID); - Element serviceMonitorFilterElement = DocumentSerializableUtilities.getChildElement(serviceElement - , - "serviceFilter"); - - serviceMonitorFilter.initializeFrom(serviceMonitorFilterElement); - serviceMonitorFilters.put(moduleClassID, serviceMonitorFilter); - } catch (Exception ex) { - if (unknownModuleClassIDs == null) { - unknownModuleClassIDs = new LinkedList(); - } - - unknownModuleClassIDs.add(moduleClassID); - } - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Can't get ModuleClassID", jex); - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorFilterException.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorFilterException.java deleted file mode 100644 index b0d459ef..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorFilterException.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import net.jxta.platform.*; - - -/** - * Monitor Filter Exception - */ -public class MonitorFilterException extends MonitorException { - public final static String SERVICE_NOT_SUPPORTED = "Service Not Supported"; - public final static String REPORT_RATE_NOT_SUPPORTED = "Report Rate Not Supported"; - ModuleClassID moduleClassID; - long reportRate; - - /** - * MonitorFilterException - * - * @param message - **/ - public MonitorFilterException(String message) { - super(MonitorException.FILTER_EXCEPTION, message); - } - - /** - * MonitorFilterException - * - * @param message - * @param e - **/ - public MonitorFilterException(String message, Exception e) { - super(MonitorException.FILTER_EXCEPTION, message, e); - } - - /** - * MonitorFilterException - * - * @param message - * @param moduleClassID - **/ - public MonitorFilterException(String message, ModuleClassID moduleClassID) { - super(MonitorException.FILTER_EXCEPTION, message); - this.moduleClassID = moduleClassID; - } - - /** - * MonitorFilterException - * - * @param message - * @param reportRate - **/ - public MonitorFilterException(String message, long reportRate) { - super(MonitorException.FILTER_EXCEPTION, message); - this.reportRate = reportRate; - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorListener.java deleted file mode 100644 index 59ffc1f1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorListener.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -/** - * Monitor Listener for Local or Remote Monitoring - **/ -package net.jxta.meter; - - -public interface MonitorListener { - - /** - * A Report is ready for Processing. It may either be a cumulative or delta Report - * - * @param monitorEvent Event containing MonitorReport - **/ - public void processMonitorReport(MonitorEvent monitorEvent); - - /** - * Monitor Reporting has been cancelled. The Event contains the reason - * - * @param monitorEvent Event containing Reason - **/ - public void monitorReportingCancelled(MonitorEvent monitorEvent); - - /** - * Request for Monitoring Failed - * - * @param monitorEvent Event containing Reason - **/ - public void monitorRequestFailed(MonitorEvent monitorEvent); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorReport.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorReport.java deleted file mode 100644 index 3be7ab2b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorReport.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import java.net.URI; -import java.net.URISyntaxException; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.id.*; -import net.jxta.peer.*; -import net.jxta.platform.*; -import net.jxta.util.*; -import net.jxta.exception.*; - -import java.util.*; - - -/** - * A Monitor Report contains service-specific metrics for each service specified in the - * corresponding MonitorFilter (provided when the report was requested). - * - **/ -public class MonitorReport implements DocumentSerializable { - private long toTime; - private long fromTime; - private boolean isCumulative; - private Map serviceMetrics = new HashMap(); - private List unknownModuleClassIDs; - - /** - * Monitor Reports are generally not created by applications, but by the Monitor or PeerInfoService - * - **/ - public MonitorReport() {} - - /** - * Monitor Reports are generally not created by applications, but by the Monitor or PeerInfoService - * - * @param fromTime - * @param toTime - * @param isCumulative - **/ - public MonitorReport(long fromTime, long toTime, boolean isCumulative) { - this.fromTime = fromTime; - this.toTime = toTime; - this.isCumulative = isCumulative; - } - - /** - * Begin time that this report is representing - **/ - public long getFromTime() { - return fromTime; - } - - /** - * End time that this report is representing - * - * @return long - **/ - public long getToTime() { - return toTime; - } - - /** - * Does this report contain metrics from the last time the monitor was reset or is this a delta report - **/ - public boolean isCumulative() { - return isCumulative; - } - - /** - * Get the contained service-specific ServiceMetrics - * - **/ - public Iterator getServiceMetrics() { - return serviceMetrics.values().iterator(); - } - - /** - * Get the contained service-specific ServiceMetric for the specified ServiceMonitor's classID - * - * @param moduleClassID ServiceMonitor's classID - * @return ServiceMetric ServiceMetric or null if Not Found - **/ - public ServiceMetric getServiceMetric(ModuleClassID moduleClassID) { - return serviceMetrics.get(moduleClassID); - } - - /** - * addServiceMetric are generally not created by applications, but by the Monitor or PeerInfoService - **/ - public void addServiceMetric(ServiceMetric serviceMetric) { - serviceMetrics.put(serviceMetric.getModuleClassID(), serviceMetric); - } - - /** - * addServiceMetric are generally not created by applications, but by the Monitor or PeerInfoService - **/ - public void addServiceMetric(ModuleClassID moduleClassID, ServiceMetric serviceMetric) { - serviceMetrics.put(moduleClassID, serviceMetric); - } - - /** - * Did this report contain any serviceMetrics for which there weren't registered ServiceMetric classes - * @see MonitorResources - **/ - public boolean isUnknownModuleClassIDs() { - return (unknownModuleClassIDs != null); - } - - /** - * Get iterator of ModuleClassIDs of serviceMetrics for which there weren't registered ServiceMetric classes - * - * @return Iterator - **/ - public Iterator getUnknownModuleClassIDs() { - if (unknownModuleClassIDs != null) { - return unknownModuleClassIDs.iterator(); - } else { - return new LinkedList().iterator(); - } - } - - /** - * {@inheritDoc} - **/ - public void serializeTo(Element element) throws DocumentSerializationException { - DocumentSerializableUtilities.addLong(element, "toTime", toTime); - DocumentSerializableUtilities.addLong(element, "fromTime", fromTime); - DocumentSerializableUtilities.addBoolean(element, "isCumulative", isCumulative); - - for (Iterator i = serviceMetrics.values().iterator(); i.hasNext();) { - ServiceMetric serviceMetric = (ServiceMetric) i.next(); - - Element serviceMetricElement = DocumentSerializableUtilities.createChildElement(element, "service"); - - DocumentSerializableUtilities.addString(serviceMetricElement, "moduleClassID" - , - serviceMetric.getModuleClassID().toString()); - DocumentSerializableUtilities.addDocumentSerializable(serviceMetricElement, "serviceMetric", serviceMetric); - } - - } - - /** - * {@inheritDoc} - **/ - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("toTime")) { - toTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("fromTime")) { - fromTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("isCumulative")) { - isCumulative = DocumentSerializableUtilities.getBoolean(childElement); - } else if (tagName.equals("service")) { - try { - ModuleClassID moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI(DocumentSerializableUtilities.getString(childElement, "moduleClassID", "ERROR"))); - - try { - ServiceMetric serviceMetric = MonitorResources.createServiceMetric(moduleClassID); - - serviceMetric.init(moduleClassID); - Element serviceMetricElement = DocumentSerializableUtilities.getChildElement(childElement, "serviceMetric"); - - serviceMetric.initializeFrom(serviceMetricElement); - serviceMetrics.put(moduleClassID, serviceMetric); - } catch (Exception ex) { - if (unknownModuleClassIDs == null) { - unknownModuleClassIDs = new LinkedList(); - } - - unknownModuleClassIDs.add(moduleClassID); - } - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Can't get ModuleClassID", jex); - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorResources.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorResources.java deleted file mode 100644 index cf593fa6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/MonitorResources.java +++ /dev/null @@ -1,548 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import java.net.URI; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Map; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.TextElement; -import net.jxta.exception.JxtaException; -import net.jxta.id.ID; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.util.AdvertisementUtilities; -import net.jxta.util.documentSerializable.DocumentSerializableUtilities; - - -/** - * Registration point for types of ServiceMonitors's Advertisements, ServiceMetrics and ServiceMonitorFilters - * based upon the ModuleClassID for the ServiceMonitor - **/ - -public class MonitorResources { - public static final String SERVICE_MONITOR_TAG = "serviceMonitor"; - public static final String SERVICE_MONITOR_ADVERTISEMENT_TAG = ModuleImplAdvertisement.getAdvertisementType(); - public static final String CLASS_ID_TAG = "moduleClassID"; - public static final String SERVICE_TITLE_TAG = "serviceTitle"; - public static final String SERVICE_MONITOR_IMPL_TAG = "serviceMonitorImpl"; - public static final String METRIC_CLASS_TAG = "serviceMetric"; - public static final String FILTER_CLASS_TAG = "serviceMonitorFilter"; - - private static Map registeredMonitorResources = new Hashtable(); - - /** - * Prefix string for all of the Well Known IDs declared in this interface. - **/ - private static final String WK_ID_PREFIX = ID.URIEncodingName + ":" + ID.URNNamespace + ":uuid-DeadBeefDeafBabaFeedBabe"; - - /** - * Well known classes for the basic service Monitors. - - * To keep their string representation shorter, we put our small spec - * or role pseudo unique ID at the front of the second UUID string. - * Base classes do not need an explicit second UUID string because it is - * all 0. - * The type is always the last two characters, nomatter the total length. - */ - - /** - * Well known module class identifier: monitor service - */ - public static final ModuleClassID monitorServiceClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000011F05")); - - /** - * Well known module class identifier: resolver service - */ - public static final ModuleClassID resolverServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010205")); - - /** - * Well known module class identifier: discovery service - */ - public static final ModuleClassID discoveryServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010305")); - - /** - * Well known module class identifier: pipe service - */ - public static final ModuleClassID pipeServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010405")); - - /** - * Well known module class identifier: membership service - */ - public static final ModuleClassID membershipServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010505")); - - /** - * Well known module class identifier: rendezvous service - */ - public static final ModuleClassID rendezvousServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010605")); - - /** - * Well known module class identifier: peerinfo service - */ - public static final ModuleClassID peerinfoServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010705")); - - /** - * Well known module class identifier: endpoint service - */ - public static final ModuleClassID endpointServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010805")); - - /* - * FIXME: EndpointProtocols should probably all be of the same class - * and of different specs and roles... But we'll take a shortcut for now. - */ - - /** - * Well known module class identifier: transport protocol - */ - public static final ModuleClassID transportServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010905")); - - /** - * Well known module class identifier: router protocol - */ - public static final ModuleClassID routerServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010B05")); - - /** - * Well known module class identifier: tlsProtocol - */ - public static final ModuleClassID tlsProtoServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "00000105")); - - /** - * Well known module class identifier: ProxyService - */ - public static final ModuleClassID proxyServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010E05")); - - /** - * Well known module class identifier: RelayProtocol - */ - public static final ModuleClassID relayServiceMonitorClassID = (ModuleClassID) - ID.create(URI.create(WK_ID_PREFIX + "0000010F05")); - - /** - * Well known service specification identifier: the standard monitor - */ - public static final ModuleSpecID refMonitorServiceSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "0000011F0106")); - - /** - * Well known service specification identifier: the standard resolver - */ - public static final ModuleSpecID refResolverServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "000001020106")); - - /** - * Well known service specification identifier: the standard discovery - */ - public static final ModuleSpecID refDiscoveryServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "000001030106")); - - /** - * Well known service specification identifier: the standard pipe - */ - public static final ModuleSpecID refPipeServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "000001040106")); - - /** - * Well known service specification identifier: the standard membership - */ - public static final ModuleSpecID refMembershipServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "000001050106")); - - /** - * Well known service specification identifier: the standard rendezvous - */ - public static final ModuleSpecID refRendezvousServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "000001060106")); - - /** - * Well known service specification identifier: the standard peerinfo - */ - public static final ModuleSpecID refPeerinfoServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "000001070106")); - - /** - * Well known service specification identifier: the standard endpoint - */ - public static final ModuleSpecID refEndpointServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "000001080106")); - - /** - * Well known endpoint protocol specification identifier: the standard - * transport Service Monitor - */ - public static final ModuleSpecID refTransportServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "000001090106")); - - /** - * Well known endpoint protocol specification identifier: the standard - * router - */ - public static final ModuleSpecID refRouterServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "0000010B0106")); - - /** - * Well known endpoint protocol specification identifier: the standard - * tls endpoint protocol - */ - public static final ModuleSpecID refTlsServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "0000010D0106")); - - /** - * Well known application: the Proxy - */ - public static final ModuleSpecID refProxyServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "0000010E0106")); - - /** - * Well known endpoint protocol specification identifier: the standard - * relay endpoint protocol - */ - public static final ModuleSpecID refRelayServiceMonitorSpecID = (ModuleSpecID) - ID.create(URI.create(WK_ID_PREFIX + "0000010F0106")); - - private static ModuleClassID standardServiceMonitorClassIDs[] = new ModuleClassID[] { - resolverServiceMonitorClassID, rendezvousServiceMonitorClassID, endpointServiceMonitorClassID - , - transportServiceMonitorClassID }; - - public static ModuleImplAdvertisement getReferenceAllPurposeMonitorServiceImplAdvertisement(boolean includeTransports) { - ModuleImplAdvertisement moduleImplAdvertisement = AdvertisementUtilities.createModuleImplAdvertisement( - refMonitorServiceSpecID, "net.jxta.impl.meter.MonitorManager", "Service Monitor"); - StructuredTextDocument param = (StructuredTextDocument) StructuredDocumentFactory.newStructuredDocument( - MimeMediaType.XMLUTF8, "serviceMonitor"); - - addServiceMonitorServiceAdvertisement(param, refResolverServiceMonitorSpecID, "Resolver" - , - "net.jxta.impl.resolver.resolverMeter.ResolverServiceMonitor" - , - "net.jxta.impl.resolver.resolverMeter.ResolverServiceMetric" - , - "net.jxta.impl.resolver.resolverMeter.ResolverServiceMonitorFilter"); - - addServiceMonitorServiceAdvertisement(param, refEndpointServiceMonitorSpecID, "Endpoint" - , - "net.jxta.impl.endpoint.endpointMeter.EndpointServiceMonitor" - , - "net.jxta.impl.endpoint.endpointMeter.EndpointServiceMetric" - , - "net.jxta.impl.endpoint.endpointMeter.EndpointServiceMonitorFilter"); - - addServiceMonitorServiceAdvertisement(param, refTransportServiceMonitorSpecID, "Transport" - , - "net.jxta.impl.endpoint.transportMeter.TransportServiceMonitor" - , - "net.jxta.impl.endpoint.transportMeter.TransportServiceMetric" - , - "net.jxta.impl.endpoint.transportMeter.TransportServiceMonitorFilter"); - - addServiceMonitorServiceAdvertisement(param, refRendezvousServiceMonitorSpecID, "Rendezvous" - , - "net.jxta.impl.rendezvous.rendezvousMeter.RendezvousServiceMonitor" - , - "net.jxta.impl.rendezvous.rendezvousMeter.RendezvousServiceMetric" - , - "net.jxta.impl.rendezvous.rendezvousMeter.RendezvousServiceMonitorFilter"); - - moduleImplAdvertisement.setParam(param); - return moduleImplAdvertisement; - } - - private static void addServiceMonitorServiceAdvertisement(Element root, ModuleSpecID moduleSpecID, String title, String implClassName, String metricClassName, String filterClassName) { - ModuleImplAdvertisement moduleImplAdvertisement = createServiceMonitorModuleImplAdvertisement(moduleSpecID, title - , - implClassName, metricClassName, filterClassName); - - Element serviceMonitorElement = DocumentSerializableUtilities.createChildElement(root, SERVICE_MONITOR_TAG); - - ModuleClassID moduleClassID = moduleSpecID.getBaseClass(); - - DocumentSerializableUtilities.addString(serviceMonitorElement, CLASS_ID_TAG, moduleClassID.toString()); - - Element serviceMonitorAdvertisementElement = DocumentSerializableUtilities.createChildElement(serviceMonitorElement - , - SERVICE_MONITOR_ADVERTISEMENT_TAG); - Element advDoc = (Element) moduleImplAdvertisement.getDocument(MimeMediaType.XMLUTF8); - - DocumentSerializableUtilities.copyChildren(serviceMonitorAdvertisementElement, advDoc); - } - - public static ModuleImplAdvertisement createServiceMonitorModuleImplAdvertisement(ModuleSpecID moduleSpecID, String title, String implClassName, String metricClassName, String filterClassName) { - ModuleImplAdvertisement moduleImplAdvertisement = AdvertisementUtilities.createModuleImplAdvertisement(moduleSpecID - , - implClassName, "Service Monitor"); - - StructuredTextDocument param = (StructuredTextDocument) StructuredDocumentFactory.newStructuredDocument( - MimeMediaType.XMLUTF8, "serviceMonitor"); - - DocumentSerializableUtilities.addString(param, SERVICE_TITLE_TAG, title); - DocumentSerializableUtilities.addString(param, METRIC_CLASS_TAG, metricClassName); - DocumentSerializableUtilities.addString(param, FILTER_CLASS_TAG, filterClassName); - moduleImplAdvertisement.setParam(param); - - return moduleImplAdvertisement; - } - - public static ModuleImplAdvertisement getServiceMonitorImplAdvertisement(ModuleClassID serviceMonitorModuleClassID, ModuleImplAdvertisement monitorServiceImplAdvertisement) { - - String classIDText = serviceMonitorModuleClassID.toString(); - - StructuredDocument param = monitorServiceImplAdvertisement.getParam(); - - for (Enumeration e = param.getChildren(SERVICE_MONITOR_TAG); e.hasMoreElements();) { - Element serviceMonitorElement = (Element) e.nextElement(); - - String serviceMonitorClassIDText = DocumentSerializableUtilities.getString(serviceMonitorElement, CLASS_ID_TAG, ""); - - if (classIDText.equals(serviceMonitorClassIDText)) { - TextElement serviceMonitorAdvertisementElement = (TextElement) DocumentSerializableUtilities.getChildElement( - serviceMonitorElement, SERVICE_MONITOR_ADVERTISEMENT_TAG); - - return (ModuleImplAdvertisement) AdvertisementFactory.newAdvertisement(serviceMonitorAdvertisementElement); - } - } - - return null; - - } - - private static class ServiceResource { - String serviceMonitorClassName; - Class serviceMonitorClass; - String serviceMonitorFilterClassName; - Class serviceMonitorFilterClass; - String serviceMetricClassName; - Class serviceMetricClass; - - ServiceResource(ModuleImplAdvertisement moduleImplAdvertisement) throws JxtaException { - try { - serviceMonitorClassName = moduleImplAdvertisement.getCode(); - - serviceMonitorFilterClassName = getServiceMonitorFilterClassName(moduleImplAdvertisement); - serviceMonitorFilterClass = Class.forName(serviceMonitorFilterClassName); - - if (!(ServiceMonitorFilter.class).isAssignableFrom(serviceMonitorFilterClass)) { - throw new JxtaException( - "Bad ServiceMonitorImplAdvertisment: " + serviceMonitorFilterClassName - + " is not a ServiceMonitorFilter"); - } - - serviceMetricClassName = getServiceMetricClassName(moduleImplAdvertisement); - serviceMetricClass = Class.forName(serviceMetricClassName); - - if (!(ServiceMetric.class).isAssignableFrom(serviceMetricClass)) { - throw new JxtaException( - "Bad ServiceMonitorImplAdvertisment: " + serviceMetricClassName + " is not a ServiceMetric"); - } - } catch (Exception e) { - throw new JxtaException("Bad ServiceMonitorImplAdvertisment: Unable to load constituent parts", e); - } - } - } - - /** - * Register the Implementation Advertisement for a ServiceMonitor Type - * This contains the Monitor, Metric and Filter classNames - */ - public static void registerServiceMonitorModuleImplAdvertisement(ModuleImplAdvertisement moduleImplAdvertisement) throws JxtaException { - ModuleClassID moduleClassID = moduleImplAdvertisement.getModuleSpecID().getBaseClass(); - - if (registeredMonitorResources.get(moduleClassID) != null) { - return; - } - - registeredMonitorResources.put(moduleClassID, new ServiceResource(moduleImplAdvertisement)); - } - - /** - * Create an empty ServiceMonitorFilter for the corresponding ModuleClassID - * - * @exception JxtaException If not found or other errors - */ - public static ServiceMonitorFilter createServiceMonitorFilter(ModuleClassID moduleClassID) throws MonitorFilterException { - try { - ServiceResource serviceResource = registeredMonitorResources.get(moduleClassID); - ServiceMonitorFilter serviceMonitorFilter = (ServiceMonitorFilter) serviceResource.serviceMonitorFilterClass.newInstance(); - - serviceMonitorFilter.init(moduleClassID); - return serviceMonitorFilter; - } catch (Exception e) { - throw new MonitorFilterException("Unable to Create Filter: " + moduleClassID); // this should never happen, we already did our checks - } - } - - /** - * Create an empty Service Metric for the corresponding ModuleClassID - * - * @exception JxtaException If not found or other errors - */ - public static ServiceMetric createServiceMetric(ModuleClassID moduleClassID) throws JxtaException { - try { - ServiceResource serviceResource = registeredMonitorResources.get(moduleClassID); - ServiceMetric serviceMetric = (ServiceMetric) serviceResource.serviceMetricClass.newInstance(); - - serviceMetric.init(moduleClassID); - return serviceMetric; - } catch (Exception e) { - throw new JxtaException("Unable to Create Service Metric"); // this should never happen, we already did our checks - } - } - - /** - * get ServiceMetric ClassName from its ImplAdvertisement - */ - public static String getServiceMetricClassName(ModuleImplAdvertisement serviceMonitorModuleImplAdvertisement) { - Element param = serviceMonitorModuleImplAdvertisement.getParam(); - - return DocumentSerializableUtilities.getString(param, METRIC_CLASS_TAG, null); - } - - /** - * get ServiceMonitorFilter ClassName from its ImplAdvertisement - */ - public static String getServiceMonitorFilterClassName(ModuleImplAdvertisement serviceMonitorModuleImplAdvertisement) { - Element param = serviceMonitorModuleImplAdvertisement.getParam(); - - return DocumentSerializableUtilities.getString(param, FILTER_CLASS_TAG, null); - } - - /** - * Get a list of all registered Service Monitor types - */ - public static ModuleClassID[] getRegisteredModuleClassIDs() { - return standardServiceMonitorClassIDs.clone(); - } - - /** - * Get the name of standard Monitor Type - **/ - public static String getMonitorTypeName(ModuleClassID moduleClassID) { - if (moduleClassID.equals(monitorServiceClassID)) { - return "monitor"; - } - - if (moduleClassID.equals(resolverServiceMonitorClassID)) { - return "Resolver"; - } - - if (moduleClassID.equals(discoveryServiceMonitorClassID)) { - return "Discovery"; - } - - if (moduleClassID.equals(pipeServiceMonitorClassID)) { - return "Pipe"; - } - - if (moduleClassID.equals(membershipServiceMonitorClassID)) { - return "Membership"; - } - - if (moduleClassID.equals(rendezvousServiceMonitorClassID)) { - return "Rendezvous"; - } - - if (moduleClassID.equals(peerinfoServiceMonitorClassID)) { - return "PeerInfo"; - } - - if (moduleClassID.equals(endpointServiceMonitorClassID)) { - return "Endpoint"; - } - - if (moduleClassID.equals(transportServiceMonitorClassID)) { - return "Transport"; - } - - if (moduleClassID.equals(routerServiceMonitorClassID)) { - return "monitor"; - } - - if (moduleClassID.equals(tlsProtoServiceMonitorClassID)) { - return "Tls"; - } - - if (moduleClassID.equals(proxyServiceMonitorClassID)) { - return "Proxy"; - } - - if (moduleClassID.equals(relayServiceMonitorClassID)) { - return "Relay"; - } - - return null; - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/PeerMonitorInfo.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/PeerMonitorInfo.java deleted file mode 100644 index 69645fe8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/PeerMonitorInfo.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import java.net.URI; -import java.util.Enumeration; - -import java.net.URISyntaxException; - -import net.jxta.document.Element; -import net.jxta.id.IDFactory; -import net.jxta.platform.ModuleClassID; -import net.jxta.util.documentSerializable.DocumentSerializable; -import net.jxta.util.documentSerializable.DocumentSerializableUtilities; -import net.jxta.util.documentSerializable.DocumentSerializationException; - -import net.jxta.exception.JxtaException; - - -/** - * The Monitoring Capabilities of a Local or Remote Peer as a list of ServiceMonitor ClassIDs and supported Reporting Rates. - **/ -public class PeerMonitorInfo implements DocumentSerializable { - public static final PeerMonitorInfo NO_PEER_MONITOR_INFO = new PeerMonitorInfo(false, null, null, 0, 0); - private boolean allowsMonitoring; - private ModuleClassID[] moduleClassIDs; - private long[] reportRates; - private long lastResetTime; - private long runningTime; - - /** - * PeerMonitorInfo - * - */ - public PeerMonitorInfo() {} - - /** - * PeerMonitorInfo - * - * @param allowsMonitoring - * @param moduleClassIDs - * @param reportRates - */ - public PeerMonitorInfo(boolean allowsMonitoring, ModuleClassID[] moduleClassIDs, long[] reportRates, long lastResetTime, long runningTime) { - this.allowsMonitoring = allowsMonitoring; - this.moduleClassIDs = moduleClassIDs; - this.reportRates = reportRates; - this.lastResetTime = lastResetTime; - this.runningTime = runningTime; - } - - /** - * Allows Monitoring - */ - public boolean allowsMonitoring() { - return allowsMonitoring; - } - - /** - * Get Suported Reporting Rates (in Milliseconds) - * - * @return long[] - */ - public long[] getReportRates() { - return reportRates; - } - - /** - * Get Suported Service Monitors as a list of ModuleClassIDs - */ - public ModuleClassID[] getModuleClassIDs() { - return moduleClassIDs; - } - - /** - * Get Time that the Monitor was last Reset (probably same as startTime) - */ - public long getLastResetTime() { - return lastResetTime; - } - - /** - * Get the running time since the monitor was reset (probably same as upTime) - */ - public long getRunningTime() { - return runningTime; - } - - /** - * @inheritDoc - **/ - public void serializeTo(Element element) throws DocumentSerializationException { - DocumentSerializableUtilities.addBoolean(element, "allowsMonitoring", allowsMonitoring); - DocumentSerializableUtilities.addLong(element, "lastResetTime", lastResetTime); - DocumentSerializableUtilities.addLong(element, "runningTime", runningTime); - - if (allowsMonitoring) { - DocumentSerializableUtilities.addInt(element, "numModuleClassIDs", moduleClassIDs.length); - for (int i = 0; i < moduleClassIDs.length; i++) { - ModuleClassID moduleClassID = moduleClassIDs[i]; - - DocumentSerializableUtilities.addString(element, "moduleClassID", moduleClassID.toString()); - } - - DocumentSerializableUtilities.addInt(element, "numReportRates", reportRates.length); - for (int i = 0; i < reportRates.length; i++) { - long reportRate = reportRates[i]; - - DocumentSerializableUtilities.addLong(element, "reportRate", reportRate); - } - } - } - - /** - * @inheritDoc - **/ - public void initializeFrom(Element element) throws DocumentSerializationException { - int numModuleClassIDs = DocumentSerializableUtilities.getInt(element, "numModuleClassIDs", 0); - - moduleClassIDs = new ModuleClassID[numModuleClassIDs]; - int moduleClassIDIndex = 0; - - int numReportRates = DocumentSerializableUtilities.getInt(element, "numReportRates", 0); - - reportRates = new long[numReportRates]; - int reportRateIndex = 0; - - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (Element) e.nextElement(); - String key = (String) childElement.getKey(); - - if (key.equals("allowsMonitoring")) { - allowsMonitoring = DocumentSerializableUtilities.getBoolean(childElement); - } else if (key.equals("lastResetTime")) { - lastResetTime = DocumentSerializableUtilities.getLong(childElement); - } else if (key.equals("runningTime")) { - runningTime = DocumentSerializableUtilities.getLong(childElement); - } else if (key.equals("reportRate")) { - long reportRate = DocumentSerializableUtilities.getLong(childElement); - - reportRates[reportRateIndex] = reportRate; - reportRateIndex++; - } else if (key.equals("moduleClassID")) { - try { - ModuleClassID moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI(DocumentSerializableUtilities.getString(childElement))); - - moduleClassIDs[moduleClassIDIndex] = moduleClassID; - moduleClassIDIndex++; - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Can't get ModuleClassID", jex); - } - } - } - - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/PeerMonitorInfoEvent.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/PeerMonitorInfoEvent.java deleted file mode 100644 index a7655f63..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/PeerMonitorInfoEvent.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import net.jxta.peer.PeerID; - - -/** - * Event containing status of request for remote PeerMonitorInfo - **/ -public class PeerMonitorInfoEvent { - - PeerID peerID; - PeerMonitorInfo peerMonitorInfo; - - /** - * PeerMonitorInfoEvent - * - * @param peerID - * @param peerMonitorInfo - */ - public PeerMonitorInfoEvent(PeerID peerID, PeerMonitorInfo peerMonitorInfo) { - this.peerID = peerID; - this.peerMonitorInfo = peerMonitorInfo; - } - - /** - * Get PeerID of remote Peer - * - * @return PeerID - */ - public PeerID getPeerID() { - return peerID; - } - - /** - * PeerMonitorInfo of remote peer - * - * @return PeerMonitorInfo - */ - public PeerMonitorInfo getPeerMonitorInfo() { - return peerMonitorInfo; - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/PeerMonitorInfoListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/PeerMonitorInfoListener.java deleted file mode 100644 index aa5875bd..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/PeerMonitorInfoListener.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -/** - * PeerInfo Reporting capabilities Received from a Remote Monitor - */ -public interface PeerMonitorInfoListener { - - /** - * PeerMonitorInfo has arrived - * - * @param peerMonitorInfoEvent Event contains PeerMonitorInfo - */ - public void peerMonitorInfoReceived(PeerMonitorInfoEvent peerMonitorInfoEvent); - - /** - * PeerMonitorInfo is not forthcoming due to Timeout - * - * @param peerMonitorInfoEvent contains PeerID of remote Peer - */ - public void peerMonitorInfoNotReceived(PeerMonitorInfoEvent peerMonitorInfoEvent); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/ServiceMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/ServiceMetric.java deleted file mode 100644 index 5e565e25..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/ServiceMetric.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import net.jxta.util.documentSerializable.*; -import net.jxta.platform.*; - - -/** - * The base interface for Service-Specific Metrics to be included in a Monitor Report - **/ -public interface ServiceMetric extends DocumentSerializable { - - /** - * init - * - * @param moduleClassID - */ - public void init(ModuleClassID moduleClassID); - - /** - * getModuleClassID - * - * @return ModuleClassID - */ - public ModuleClassID getModuleClassID(); - - /** - * Additively Merge Metrics from this Metric - * - * @param otherServiceMetric The metric being merged into this metric - */ - public void mergeMetrics(ServiceMetric otherServiceMetric); - - /** - * Subtractively Remove Metrics from this Metric - * - * @param otherServiceMetric The metric being removed into this metric - */ - public void diffMetrics(ServiceMetric otherServiceMetric); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/ServiceMonitor.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/ServiceMonitor.java deleted file mode 100644 index 7e72fa15..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/ServiceMonitor.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.*; - - -/** - * The base interface for all ServiceMonitors - * For complete information about Service Monitors see the - * Document Designing and Implementing Service Monitors - */ -public interface ServiceMonitor extends Module { - - /** - * Get ModuleClassID of this ServiceMonitor - */ - public ModuleClassID getModuleClassID(); - - /** - * Get ServiceMetrics accrued in during this pulse interval - * - * @param serviceMonitorFilter Filter Metrics based upon this MonitorFilter - * @param fromTime Beginning time as determined by the MonitorManager - * @param toTime Ending time as determined by the MonitorManager - * @param pulseIndex Pulse Index of the reporting rate Pyramid - * @param reportRate Reporting Rate (corresponding to the PulseNumber's index) - */ - public ServiceMetric getServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime, int pulseIndex, long reportRate); - - /** - * A request for a cumulative Report(s) are coming, prepare to receive them - * @see #endCumulativeReport() - * - */ - public void beginCumulativeReport(); - - /** - * Get ServiceMetrics since the start (or last reset time) of this ServiceMonitor. - * Calls to this will only occurr between calls to beginCumulativeReport() and endCumulativeReport() - * @see #beginCumulativeReport() - * @see #endCumulativeReport() - * @param serviceMonitorFilter Filter Metrics based upon this MonitorFilter - * @param fromTime Beginning time as determined by the MonitorManager - * @param toTime Ending time as determined by the MonitorManager - */ - public ServiceMetric getCumulativeServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime); - - /** - * Indication that the flurry of requests for cumulative Report is over - * @see #beginCumulativeReport() - */ - public void endCumulativeReport(); - - /** - * Validate ServiceMonitorFilter for a cumulative Report - */ - public void validateCumulativeServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter) throws MonitorFilterException; - - /** - * Validate ServiceMonitorFilter for a periodic Reporting - */ - public void validateServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter, long reportRate) throws MonitorFilterException; - - /** - * Transform the provided ServiceMonitorFilter into one that is supported for cumulative reporting - */ - public ServiceMonitorFilter createSupportedCumulativeServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter) throws MonitorFilterException; - - /** - * Transform the provided ServiceMonitorFilter into one that is supported for periodic reporting at the specified rate - */ - public ServiceMonitorFilter createSupportedServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter, long reportRate) throws MonitorFilterException; - - /** - * Information that the Monitor Manager has accepted a Monitoring for this filter at this rate - * - * @param serviceMonitorFilter Accepted Filter - * @param reportRateIndex Pulse Index into pyramid of accepted rate - * @param reportRate Accepted reporting rate - * @param newRate Is this a new reporting rate (ie you don't have any currently registered at this rate) - */ - public void serviceMonitorFilterRegistered(ServiceMonitorFilter serviceMonitorFilter, int reportRateIndex, long reportRate, boolean newRate); - - /** - * Information that the Monitor Manager is deregistering the Monitoring for this filter at this rate - * - * @param serviceMonitorFilter Deregistered Filter - * @param reportRateIndex Pulse Index into pyramid of deregistered filter - * @param reportRate Reporting rate of deregistered filter - * @param retiredRate Is this a retired filter the last one registered at this rate (ie you don't have to keep metrics for this rate any longer) - */ - public void serviceMonitorFilterDeregistered(ServiceMonitorFilter serviceMonitorFilter, int reportRateIndex, long reportRate, boolean retiredRate); - - /** - * Clean up. The PeerGroup is probably about to be destroyed - */ - public void destroy(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/ServiceMonitorFilter.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/ServiceMonitorFilter.java deleted file mode 100644 index 72ac4e23..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/ServiceMonitorFilter.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.meter; - - -import net.jxta.util.documentSerializable.*; -import net.jxta.platform.*; - - -/** - * The base interface for all ServiceMonitorFilters. - * See the Service-Specific filter for any interesting information - */ -public interface ServiceMonitorFilter extends DocumentSerializable { - - /** - * init - * - * @param moduleClassID - */ - public void init(ModuleClassID moduleClassID); - - /** - * get ModuleClassID - */ - public ModuleClassID getModuleClassID(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/package.html deleted file mode 100644 index dc046f31..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/meter/package.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - Provides logging and monitoring facilities for debugging and auditing of - messaging and service invocation within JXTA. - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/overview.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/overview.html deleted file mode 100644 index e731cd15..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/overview.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - These packages provide the standard API for the JXTA Protocols using - Java Standard Edition 5.0. The implementation is divided into two - parts: the JSE Standard JXTA API (these packages) and the - JSE JXTA Reference Implementation -

      - Additional optional packages which are useful for developers building JXTA - applications can be found in the - JSE JXTA Extensions - - -

      Important Note: Applications and services are very - strongly encouraged to not import classes or interfaces from the - implementation packages. Specificially do not import from - net.jxta.impl.*. The content of these packages may change - significantly (including removal) from release to release with no advance - notice. - - @see JXTA Protocols Specification - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerID.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerID.java deleted file mode 100644 index fbd517a7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerID.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.peer; - - -import java.net.URI; -import net.jxta.id.ID; - - -/** - * This class implements a PeerID. Each peer is assigned a unique peer id. - * - * @see net.jxta.id.ID - * @see net.jxta.id.IDFactory - * @see net.jxta.peergroup.PeerGroupID - */ -public abstract class PeerID extends ID { - - /** - * Creates an ID by parsing the given URI. - * - *

      This convenience factory method works as if by invoking the - * {@link net.jxta.id.IDFactory#fromURI(URI)} method; any - * {@link java.net.URISyntaxException} thrown is caught and wrapped in a - * new {@link IllegalArgumentException} object, which is then thrown. - * - *

      This method is provided for use in situations where it is known that - * the given string is a legal ID, for example for ID constants declared - * within in a program, and so it would be considered a programming error - * for the URI not to parse as such. The {@link net.jxta.id.IDFactory}, - * which throws {@link java.net.URISyntaxException} directly, should be used - * situations where a ID is being constructed from user input or from some - * other source that may be prone to errors. - * - * @param fromURI The URI to be parsed into an ID - * @return The new ID - * - * @throws NullPointerException If {@code fromURI} is {@code null}. - * @throws IllegalArgumentException If the given URI is not a valid ID. - */ - public static PeerID create(URI fromURI) { - return (PeerID) ID.create(fromURI); - } - - /** - * {@inheritDoc} - */ - public PeerID intern() { - return (PeerID) super.intern(); - } - - /** - * Returns PeerGroupID of the Peer Group to which this Peer ID belongs. - * - * @return PeerGroupID of the Peer Group to which this Peer ID belongs. - */ - public abstract ID getPeerGroupID(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerInfoEvent.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerInfoEvent.java deleted file mode 100644 index 6f08b77f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerInfoEvent.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.peer; - - -import java.util.EventObject; - -import net.jxta.protocol.PeerInfoResponseMessage; - - -/** - * Container for PeerInfoEvent events. - */ -public class PeerInfoEvent extends EventObject { - - private PeerInfoResponseMessage piResp = null; - private int queryID = -1; - - /** - * Creates a new event - * - *@param source The object on which the Event initially occurred - *@param queryid The query id associated with the response returned in - * this event - *@param piResp PeerInfoResponseMessage received - *@see net.jxta.protocol.ResolverResponseMsg - */ - - public PeerInfoEvent(Object source, PeerInfoResponseMessage piResp, int queryid) { - super(source); - this.piResp = piResp; - this.queryID = queryid; - - } - - /** - * Returns the response associated with the event - * - *@return PeerInfoResponseMessage - *@see net.jxta.protocol.ResolverResponseMsg - */ - public PeerInfoResponseMessage getPeerInfoResponseMessage() { - - return piResp; - } - - /** - * Returns The query id associated with the response returned in this - * event - * - *@return query id associated with the response - */ - public int getQueryID() { - - return queryID; - } - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerInfoListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerInfoListener.java deleted file mode 100644 index 0ac3b92b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerInfoListener.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.peer; - - -import java.util.EventListener; - - -/** - * The listener interface for receiving PeerInfoService events. - * - * The following example illustrates how to implement a PeerInfoListener: - * - * - *

      - *        PeerInfoListener myPeerListener = new PeerInfoListener() {
      - *            public void peerInfoResponse(PeerInfoEvent e) {
      - *                PeerInfoResponseMessage adv = e.getPeerInfoResponse();
      - *                if (myQueryID == e.getQueryID()) {
      - *                 ...
      - *                 ...
      - *                }
      - *            }
      - *        peerinfo.addPeerInfoListener(myPeerListener);
      - *        int myQueryID = peerinfo.getRemotePeerInfo(peer);
      - * 
      - */ - -public interface PeerInfoListener extends EventListener { - - /** - * PeerInfoService Event - * - * @param event the peer info event - */ - void peerInfoResponse(PeerInfoEvent event); - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerInfoService.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerInfoService.java deleted file mode 100644 index f148a0ab..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/PeerInfoService.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.peer; - - -import net.jxta.meter.*; -import net.jxta.platform.ModuleClassID; -import net.jxta.service.Service; - - -/** - * The PeerInfoService is a generic API for getting information about - * the local Peer as well as remote Peers.

      - *

      - * The most important type of information about a Peer may be gotten through - * the Monitoring Service that may be accessed via the PeerInfoService. The - * Monitoring Service provides an open mechanism for reporting any type of - * Metrics gathered on a Peer by a ServiceMonitor. Attached Service Monitors - * are identified by their ModuleClassID. A ServiceMonitor may monitor anything - * (ie it is not restricted to JXTA Services).

      - *

      - * There are several methods for accessing the capabilities and metrics - * from ServiceMonitors - * attached to the Peer (either locally or from remote peers).

      - *

      - * Cumulative MonitorReports containing metrics since the Monitoring began - * (or was reset) on a local/remote Peer may be obtained. Alternatively, you may - * register listeners get periodic MonitorReports (at a specified rate) of - * metrics (since the previous report). The amount of information obtained (either - * cumulatively or periodically) is determined by a MonitorFilter whi - *

      - * The PeerInfoService utilizes the ResolverService to send queries and receive - * responses (PeerInfoQueryMessage / PeerInfoResponseMessage). These contain - * requests and responses that are specific to the type of info being requested. - * Depending upon the type of information requested, a peer may provide multiple - * varying responses over time (as is the case for periodic remote peer Monitoring).

      - *

      - * At the time of writing this documentation Service Monitoring is the only type - * of Peer Information available though the implementation and underlying protocol - * can support other types of information.

      - *

      - * See the document: - *

        - *
      • JXTA Metering and Monitoring Project
      • - *
      • The JXTA Metering and Monitoring Project Architecture
      • - *
      • Building and Configuring JXTA with Monitoring Capabilities
      • - *
      • JXTA Monitor: GUI Rendering of Metered Peer Info
      • - *
      - * - * @see net.jxta.meter.MonitorFilter - * @see net.jxta.meter.MonitorReport - * @see net.jxta.meter.ServiceMonitor - * @see net.jxta.meter.PeerMonitorInfo - * @see net.jxta.protocol.PeerInfoQueryMessage - * @see net.jxta.protocol.PeerInfoResponseMessage - * @since JXTA 1.0 - */ - -public interface PeerInfoService extends Service { - - /** - * See if Local Monitoring is available on this Peer - * Local monitoring is only available if you are using a version of - * of jxta.jar that was build with metering activated.

      - *

      - * See the document: - *

        - *
      • Building and Configuring JXTA with Monitoring Capabilities
      • - *
      - * - * @return true if local monitoring is available - */ - public boolean isLocalMonitoringAvailable(); - - /** - * See if Local monitoring is available from a specific ServiceMonitor. - * Local monitoring is only available if you are using a version of - * of jxta.jar that was build with metering activated.

      - *

      - * See the document: - *

        - *
      • Building and Configuring JXTA with Monitoring Capabilities
      • - *
      - * - * @param moduleClassID The Module classID of the ServiceMonitor. Note that the ServiceMonitor - * moduleClassID is not the same as moduleClassID of the Service - * being monitored. - * @return true if local monitoring is available for a specific module - */ - public boolean isLocalMonitoringAvailable(ModuleClassID moduleClassID); - - /** - * Asynchronous reporting of Monitored data may be obtained only at rates supported by - * the MonitorManager on the peer. This method returns the locally supported rates (in milliseconds) - * @return all supported rates - */ - public long[] getSupportedReportRates(); - - /** - * Asynchronous reporting of Monitored data may be obtained only at rates supported by - * the MonitorManager on the peer. This method validates whether a specific - * rate (in milliseconds) is locally supported. - * @param reportRate the report rate to check - * @return true if a report rate is supported - */ - public boolean isSupportedReportRate(long reportRate); - - /** - * Asynchronous reporting of Monitored data may be obtained only at rates supported by - * the MonitorManager on the peer. This method supplies the closest (rounded up) - * rate (in milliseconds) to the specified rate that is locally supported. - * @param desiredReportRate the desired rate - * @return the desired rate - */ - public long getBestReportRate(long desiredReportRate); - - /** - * Obtain the monitoring capabilities of the Local Peer.

      - * The PeerMonitorInfo provides: - *

        - *
      • Whether any monitoring is available for this Peer
      • - *
      • The supported rates of asynchronous monitoring
      • - *
      • A list (as ModuleClassIDs) of ServiceMonitors attached to this Peer
      • - *
      - * @return PeerMonitorInfo - */ - public PeerMonitorInfo getPeerMonitorInfo(); - - /** - * Obtain the monitoring capabilities of a Remote Peer.

      - * The PeerMonitorInfo provides: - *

        - *
      • Whether any monitoring is available for this Peer
      • - *
      • The supported rates of asynchronous monitoring
      • - *
      • A list (as ModuleClassIDs) of ServiceMonitors attached to this Peer
      • - *
      - *

      - * Via the PeerMonitorInfoListener, you will be informed of the PeerMonitorInfo or why it was - * not provided (error, timeout, unavailable, etc) - * - * @param peerID The PeerID of the Peer you wish information about - * @param peerMonitorInfoListener The Listener to be told about the obtained PeerMonitorInfo - * @param timeout Generate a timeout event if no answer has been received in this time (in Milliseconds) - * @throws net.jxta.meter.MonitorException if a monitor error occurs - */ - public void getPeerMonitorInfo(PeerID peerID, PeerMonitorInfoListener peerMonitorInfoListener, long timeout) throws MonitorException; - - /** - * Get a MonitorReport of total accumulated metrics from the ServiceMonitors (specified in the - * MonitorFilter) since they were created/reset for the local Peer. - * - * @param monitorFilter The MonitorFilter containing the specific ServiceMonitors and types of Service Metrics desired - * @return the report - * @throws net.jxta.meter.MonitorException if a monitor error occurs - */ - public MonitorReport getCumulativeMonitorReport(MonitorFilter monitorFilter) throws MonitorException; - - /** - * Get a MonitorReport of total accumulated metrics from the ServiceMonitors (specified in the - * MonitorFilter) since they were created/reset for the specified remote Peer. - * - * @param peerID The PeerID of the Peer you wish information about - * @param monitorFilter The MonitorFilter containing the specific ServiceMonitors and types of Service Metrics desired - * @param monitorListener The Listener to obtain the report when it arrives (or timed out) - * @param timeout The timeout for reporting that the information has not arrived. - * @throws net.jxta.meter.MonitorException if a monitor error occurs - */ - public void getCumulativeMonitorReport(PeerID peerID, MonitorFilter monitorFilter, MonitorListener monitorListener, long timeout) throws MonitorException; - - /** - * Get MonitorReports at a specified rates of metrics accrued over time from the ServiceMonitors - * (specified in the MonitorFilter) about the local Peer. For many applications it is required to obtain metrics from - * the beginning of time and then augment over time as more data arrives.

      - *

      - * There is a problem with the following approach: - *

        - *
      1. Call getCumulativeMonitorReport to get the cumulative totals
      2. - *
      3. Call addMonitorListener to get periodic changes
      4. - *
      5. Add the periodic data to the totals
      6. - *
      - *

      - * Because of a potential race condition related to metrics that are measured between the two calls it is - * possible to lose some metrics. To address this, this method supports this by combining them into a single - * call that allows you to specify whether you wish the first report delivered to be a cumulative report. - * - * @param monitorFilter The MonitorFilter containing the specific ServiceMonitors and types of Service Metrics desired - * @param reportRate The rate at which you wish metric delta reports - * @param includeCumulative Should the first report you receive be the cumulative data since the ServiceMonitors were created/reset? - * @param monitorListener The Listener to obtain the report when it arrives (or timed out) - * @return report rate - * @throws net.jxta.meter.MonitorException if a monitor error occurs - */ - public long addMonitorListener(MonitorFilter monitorFilter, long reportRate, boolean includeCumulative, MonitorListener monitorListener) throws MonitorException; - - /** - * Get MonitorReports at a specified rates of metrics accrued over time from the ServiceMonitors - * (specified in the MonitorFilter) about the specified remote Peer. For many applications it is required to obtain metrics from - * the beginning of time and then augment over time as more data arrives.

      - *

      - * There is a problem with the following approach: - *

        - *
      1. Call getCumulativeMonitorReport to get the cumulative totals
      2. - *
      3. Call addMonitorListener to get periodic changes
      4. - *
      5. Add the periodic data to the totals
      6. - *
      - *

      - * Because of a potential race condition related to metrics that are measured between the two calls it is - * possible to lose some metrics. To address this, this method supports this by combining them into a single - * call that allows you to specify whether you wish the first report delivered to be a cumulative report. - * - * @param peerID The PeerID of the Peer you wish information about - * @param monitorFilter The MonitorFilter containing the specific ServiceMonitors and types of Service Metrics desired - * @param reportRate The rate at which you wish metric delta reports - * @param includeCumulative Should the first report you receive be the cumulative data since the ServiceMonitors were created/reset? - * @param monitorListener The Listener to obtain the report when it arrives (or timed out) - * @param timeout The timeout for reporting that the information has not arrived. - * @param lease the lease - * @throws net.jxta.meter.MonitorException if a monitor error occurs - */ - public void addRemoteMonitorListener(PeerID peerID, MonitorFilter monitorFilter, long reportRate, boolean includeCumulative, MonitorListener monitorListener, long lease, long timeout) throws MonitorException; - - /** - * Stop the periodic reporting for all registered filters corresponding to this MonitorListener - * @param monitorListener the monitor listener - * @return true if successfully removed - * @throws net.jxta.meter.MonitorException if a monitor error occurs - */ - public boolean removeMonitorListener(MonitorListener monitorListener) throws MonitorException; - - /** - * Stop the periodic reporting for all registered filters to the specified Peer corresponding to this MonitorListener. - * - * @param peerID The Peer that you wish to deregister periodic reporting - * @param monitorListener The MonitorListener that was originally registered - * @param timeout The timeout for reporting that the remote listener was acknowledged as deregistered - * @throws net.jxta.meter.MonitorException if a monitor error occurs - */ - public void removeRemoteMonitorListener(PeerID peerID, MonitorListener monitorListener, long timeout) throws MonitorException; - - /** - * Stop the periodic reporting for all registered filters to the all remote Peers corresponding to this MonitorListener. - * - * @param monitorListener The MonitorListener that was originally registered - * @param timeout The timeout for reporting that the remote listener was acknowledged as deregistered - * @throws net.jxta.meter.MonitorException if a monitor error occurs - */ - public void removeRemoteMonitorListener(MonitorListener monitorListener, long timeout) throws MonitorException; -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/package.html deleted file mode 100644 index 0d36f16c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peer/package.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - Provides definition for the standard JXTA Peer Info Service. There - is no JXSE object directly associated with the peer. The state of the - current peer is expressed through the {@link net.jxta.peergroup.PeerGroup} - object. - - @see net.jxta.peergroup.PeerGroup - @see net.jxta.protocol.PeerAdvertisement - @see net.jxta.id.ID - - @see JXTA Protocols Specification : Peer Info Protocol - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/Configurator.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/Configurator.java deleted file mode 100644 index fa72befc..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/Configurator.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.peergroup; - - -import net.jxta.exception.ConfiguratorException; -import net.jxta.protocol.ConfigParams; - - -/** - * A configurator is responsible for the persistence and validation of - * configuration parameters. - * - * @deprecated This interface has been replaced with the {@link net.jxta.platform.NetworkConfigurator}. - **/ -@Deprecated -public interface Configurator { - - /** - * Retrieve the parameters associated with this configuration from the - * default location. If necessary the parameters will be created or an - * opportunity to adjust them will be provided. - * - * @return The configuration parameters. - * @throws ConfiguratorException If there was a failure in retrieving the - * parameters. This is normally a chained exception to the underlying - * cause. - **/ - public ConfigParams getConfigParams() throws ConfiguratorException; - - /** - * Sets the parameters associated with this configuration object to the - * provided values. - * - * @deprecated Configuration parameters should be set individually via - * whatever interfaces implementing configurator provides. This method - * over-writes all configuration settings in an unpredictable way. - * - * @param cp The parameters to be associated with this configuration. - **/ - @Deprecated - public void setConfigParams(ConfigParams cp); - - /** - * Retrieves the persisted parameters associated with this configuration - * from the standard location. - * - * @deprecated Loading of existing configuration is best accomplished by use - * of specific constructors of the implementing configurator. This method - * complicates the state management of configuration parameters and may have - * unpredictable results depending upon the constructor and configuration - * set methods used prior to it's execution. - * - * @return The configuration parameters. - * @throws ConfiguratorException If there was a failure in retrieving the - * persisted parameters. This is normally a chained exception to the - * underlying cause. - **/ - @Deprecated - public ConfigParams load() throws ConfiguratorException; - - /** - * Persist the parameters associated with this configuration to the - * standard location. - * - * @return true if the configuration was successfully saved - * otherwise false. If the parameters are not persisted then - * false/code> is returned. - * @throws ConfiguratorException If there was a failure in persisting the - * parameters. This is normally a chained exception to the underlying - * cause. - **/ - public boolean save() throws ConfiguratorException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/LightWeightPeerGroup.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/LightWeightPeerGroup.java deleted file mode 100644 index 67dff032..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/LightWeightPeerGroup.java +++ /dev/null @@ -1,584 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.peergroup; - - -import net.jxta.access.AccessService; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.Element; -import net.jxta.endpoint.EndpointService; -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.ProtocolNotSupportedException; -import net.jxta.exception.ServiceNotFoundException; -import net.jxta.id.ID; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peer.PeerInfoService; -import net.jxta.pipe.PipeService; -import net.jxta.platform.JxtaLoader; -import net.jxta.platform.Module; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.resolver.ResolverService; -import net.jxta.service.Service; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.IOException; -import java.net.URI; -import java.util.Collections; -import java.util.Iterator; - - -/** - * LightWeightPeerGroup is a class intended to help - * building PeerGroup that can inherit one or more - * services from a parent PeerGroup. - *

      - * An LightWeightPeerGroup implements PeerGroup and is to - * be used like a PeerGroup by applications. - *

      - * This class is intended to be extended/implemented. - *

      - * Note: unlike implementations of peer groups that existed until JXTA 2.2, - * LightweightPeergroup permits to implement groups that borrow all or - * part of their services to a parent group. One needs to remember - * that peers in various such subgroups of a given parent groups may - * implicitly all share the same services if that is what the PeerGroup - * implementing LightWeightPeerGroup is doing. Please refer to the documentation - * of PeerGroups extending LightWeigthPeerGroup do understand which - * services are shared, and which are not. - */ - -public class LightWeightPeerGroup implements PeerGroup { - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(LightWeightPeerGroup.class.getName()); - - private PeerGroup group = null; - private ID assignedID = null; - private ModuleImplAdvertisement implAdv = null; - private final PeerGroupAdvertisement adv; - - /** - * Constructor - *

      - * All classes that extend this class must invoke this - * constructor. - * - * @param adv PeerGroupAdvertisement of this LightWeightPeerGroup. - * Note that only the PeerGroupID is used. - */ - public LightWeightPeerGroup(PeerGroupAdvertisement adv) { - this.adv = adv; - } - - /*********************************************************** - ** Module API - ***********************************************************/ - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement implAdv) { - this.group = group; - this.assignedID = assignedID; - this.implAdv = (ModuleImplAdvertisement) implAdv; - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] args) { - if (null == group) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("No base peer group defined."); - } - return -1; - } - - return START_OK; - } - - /** - * {@inheritDoc} - */ - public void stopApp() {} - - /** - * {@inheritDoc} - */ - public Service getInterface() { - return this; - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return implAdv; - } - - /*********************************************************** - ** PeerGroup API - ***********************************************************/ - - /** - * {@inheritDoc} - */ - public ThreadGroup getHomeThreadGroup() { - if (group != null) { - return group.getHomeThreadGroup(); - } else { - return null; - } - } - - /*********************************************************** - ** PeerGroup API - ***********************************************************/ - - /** - * {@inheritDoc} - */ - public URI getStoreHome() { - if (group != null) { - return group.getStoreHome(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public JxtaLoader getLoader() { - if (group != null) { - return group.getLoader(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public PeerGroup getParentGroup() { - - try { - return group; - } catch (Exception ex) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("LightWeightPeerGroup is a base PeerGroup: no parent"); - } - throw new RuntimeException("LightWeightPeerGroup is a base PeerGroup: no parent"); - } - } - - /** - * {@inheritDoc} - */ - public boolean isRendezvous() { - - return group != null && group.isRendezvous(); - } - - /** - * {@inheritDoc} - */ - public PeerGroupAdvertisement getPeerGroupAdvertisement() { - - if (adv != null) { - return adv; - } else if (group != null) { - return group.getPeerGroupAdvertisement(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public PeerAdvertisement getPeerAdvertisement() { - - if (group != null) { - return group.getPeerAdvertisement(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public Service lookupService(ID name) throws ServiceNotFoundException { - - if (group != null) { - return group.lookupService(name); - } else { - throw new ServiceNotFoundException("Not implemented"); - } - } - - /** - * {@inheritDoc} - */ - public Service lookupService(ID name, int ignoredForNow) throws ServiceNotFoundException { - - if (group != null) { - return group.lookupService(name); - } else { - throw new ServiceNotFoundException("Not implemented"); - } - } - - /** - * {@inheritDoc} - */ - public Iterator getRoleMap(ID name) { - - if (group != null) { - return group.getRoleMap(name); - } else { - // No translation; use the given name in a singleton. - return Collections.singletonList(name).iterator(); - } - } - - /** - * {@inheritDoc} - */ - public boolean compatible(Element compat) { - - return group != null && group.compatible(compat); - } - - /** - * {@inheritDoc} - */ - public Module loadModule(ID assignedID, Advertisement impl) throws ProtocolNotSupportedException, PeerGroupException { - - if (group != null) { - return group.loadModule(assignedID, impl); - } else { - throw new ProtocolNotSupportedException("LightWeightPeerGroup does not implement this operation"); - } - } - - /** - * {@inheritDoc} - */ - public Module loadModule(ID assignedID, ModuleSpecID specID, int where) { - - if (group != null) { - return group.loadModule(assignedID, specID, where); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public void publishGroup(String name, String description) throws IOException { - - if (group != null) { - group.publishGroup(name, description); - } else { - throw new IOException("Not implemented"); - } - } - - /** - * {@inheritDoc} - */ - public PeerGroup newGroup(Advertisement pgAdv) throws PeerGroupException { - - if (group != null) { - return group.newGroup(pgAdv); - } else { - throw new PeerGroupException("Not implemented"); - } - } - - /** - * {@inheritDoc} - */ - public PeerGroup newGroup(PeerGroupID gid, Advertisement impl, String name, String description) throws PeerGroupException { - - if (group != null) { - return group.newGroup(gid, impl, name, description); - } else { - throw new PeerGroupException("Not implemented"); - } - } - - /** - * {@inheritDoc} - */ - public PeerGroup newGroup(PeerGroupID gid) throws PeerGroupException { - - if (group != null) { - return group.newGroup(gid); - } else { - throw new PeerGroupException("Not implemented"); - } - } - - /* - * shortcuts to the well-known services, in order to avoid calls to lookup. - */ - - /** - * {@inheritDoc} - */ - public RendezVousService getRendezVousService() { - - if (group != null) { - return group.getRendezVousService(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - - if (group != null) { - return group.getEndpointService(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public ResolverService getResolverService() { - if (group != null) { - return group.getResolverService(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public DiscoveryService getDiscoveryService() { - if (group != null) { - return group.getDiscoveryService(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public PeerInfoService getPeerInfoService() { - if (group != null) { - return group.getPeerInfoService(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public MembershipService getMembershipService() { - if (group != null) { - return group.getMembershipService(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public PipeService getPipeService() { - if (group != null) { - return group.getPipeService(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public AccessService getAccessService() { - if (group != null) { - return group.getAccessService(); - } else { - return null; - } - } - - /* - * A few convenience methods. This information is available from - * the peer and peergroup advertisement. - */ - - /** - * {@inheritDoc} - */ - public PeerGroupID getPeerGroupID() { - - if (adv != null) { - return (PeerGroupID) adv.getID(); - } else if (group != null) { - return group.getPeerGroupID(); - } else { - throw new RuntimeException("No PeerGroupID"); - } - } - - /** - * {@inheritDoc} - */ - public PeerID getPeerID() { - - if (group != null) { - return group.getPeerID(); - } else { - throw new RuntimeException("No PeerID"); - } - } - - /** - * {@inheritDoc} - */ - public String getPeerGroupName() { - - if (adv != null) { - return adv.getName(); - } else if (group != null) { - return group.getPeerGroupName(); - } else { - throw new RuntimeException("No name"); - } - } - - /** - * {@inheritDoc} - */ - public String getPeerName() { - - if (group != null) { - return group.getPeerName(); - } else { - throw new RuntimeException("No name"); - } - } - - /** - * {@inheritDoc} - */ - public ConfigParams getConfigAdvertisement() { - - if (group != null) { - return group.getConfigAdvertisement(); - } else { - throw new RuntimeException("No ConfigAdvertisement"); - } - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getAllPurposePeerGroupImplAdvertisement() throws Exception { - - if (group != null) { - return group.getAllPurposePeerGroupImplAdvertisement(); - } else { - throw new RuntimeException("Not implemented"); - } - } - - /** - * {@inheritDoc} - */ - public void unref() {} - - /** - * {@inheritDoc} - */ - public PeerGroup getWeakInterface() { - - /** - * A LightWeightPeerGroup is already a weak reference - * that is not shareable, therefore, return self as - * a weak reference. - **/ - - return this; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/NetPeerGroupFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/NetPeerGroupFactory.java deleted file mode 100644 index df66d6d6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/NetPeerGroupFactory.java +++ /dev/null @@ -1,581 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.peergroup; - - -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLElement; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; - -import net.jxta.impl.protocol.PeerGroupConfigAdv; -import net.jxta.impl.peergroup.GenericPeerGroup; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URI; -import java.util.MissingResourceException; -import java.util.PropertyResourceBundle; -import java.util.ResourceBundle; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * A factory for instantiating a Network Peer Group instances. The Network Peer - * Group is the base peer group for applications and services within the JXTA - * network. Most applications and services will instantiate their own peer - * groups using the Network Peer Group as a base. - *

      - * A non-default configuration of The Network Peer Group may be - * set-up by the administrator in charge of the network domain inside which the - * peer is starting. The Network Peer Group may be discovered via the - * JXTA Discovery protocol. Many such groups may be configured by an - * administrator. - * - * @since JXTA JSE 2.4 - * - * @see net.jxta.peergroup.PeerGroup - * @see net.jxta.peergroup.WorldPeerGroupFactory - */ -public final class NetPeerGroupFactory { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(NetPeerGroupFactory.class.getName()); - - /** - * Our strong reference to the net peer group. - */ - private final PeerGroup net; - - /** - * Instantiates the Net Peer Group using the ConfigParams found in the - * directory specified by the {@code JXTA_HOME} system property or the - * "{@code .jxta/}" directory if {@code JXTA_HOME} is not defined. - *

      - * This constructor is provided primarily for backwards compatibility. - * Though not deprecated this method should be considered as sample code - * only and the other constructors should be used whenever possible. - * - * @throws PeerGroupException Thrown for problems constructing the Net Peer - * Group. - */ - public NetPeerGroupFactory() throws PeerGroupException { - WorldPeerGroupFactory world = new WorldPeerGroupFactory(); - PeerGroup worldGroup = world.getInterface(); - NetGroupTunables tunables; - - try { - ConfigParams cp = worldGroup.getConfigAdvertisement(); - PeerGroupConfigAdv netGroupConfig = (PeerGroupConfigAdv) cp.getSvcConfigAdvertisement(PeerGroup.peerGroupClassID); - - if (null == netGroupConfig) { - tunables = new NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config"), new NetGroupTunables()); - // load overides from "${JXTA_HOME}config.properties". - URI storeHome = worldGroup.getStoreHome(); - - if (null != storeHome) { - try { - File configProperties = new File(new File(storeHome), "config.properties"); - ResourceBundle rsrcs = new PropertyResourceBundle(new FileInputStream(configProperties)); - - tunables = new NetGroupTunables(rsrcs, tunables); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Loaded defaults from " + rsrcs); - } - } catch (MissingResourceException ignored) { - // ingnored - } catch (IOException ignored) { - // ingnored - } - } - } else { - tunables = new NetGroupTunables(netGroupConfig.getPeerGroupID(), netGroupConfig.getName(), netGroupConfig.getDesc()); - } - - net = newNetPeerGroup(worldGroup, null, tunables.id, tunables.name, tunables.desc, null); - } finally { - worldGroup.unref(); - } - } - - /** - * Constructs a Net Peer Group using the specified parent peer group. This - * is the preferred constructor for constructing a Net Peer Group using the - * default configuration. The resulting Net Peer Group instance will use - * the default ID, Name and Description. - * - * @param parentGroup The Peer Group which will be the parent of the newly - * created net peer group. This should normally be the World Peer Group. - * @throws PeerGroupException Thrown for problems constructing the Net Peer - * Group. - */ - public NetPeerGroupFactory(PeerGroup parentGroup) throws PeerGroupException { - ConfigParams cp = parentGroup.getConfigAdvertisement(); - PeerGroupConfigAdv netGroupConfig = (PeerGroupConfigAdv) cp.getSvcConfigAdvertisement(PeerGroup.peerGroupClassID); - NetGroupTunables tunables; - - if (null == netGroupConfig) { - tunables = new NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config"), new NetGroupTunables()); - } else { - tunables = new NetGroupTunables(netGroupConfig.getPeerGroupID(), netGroupConfig.getName(), netGroupConfig.getDesc()); - } - - net = newNetPeerGroup(parentGroup, null, tunables.id, tunables.name, tunables.desc, null); - } - - /** - * Constructs a Net Peer Group and the World Peer Group using the - * configuration specified by the provided ConfigParams and using the - * specified storeHome location for persistence. The resulting Net Peer - * Group instance will use the default ID, Name and Description. - * - * @param config The configuration to use for the newly created World Peer - * Group and Net Peer Groups. - * @param storeHome The optional location that the World Peer Group, the - * Net Peer Group and its' services should use for storing persistent and - * transient information. May be {@code null} if the World Peer Group is - * not provided a persistent store (though this not currently supported). - * @throws PeerGroupException Thrown for problems constructing the Net Peer - * Group. - */ - public NetPeerGroupFactory(ConfigParams config, URI storeHome) throws PeerGroupException { - WorldPeerGroupFactory world = new WorldPeerGroupFactory(config, storeHome); - PeerGroup worldGroup = world.getInterface(); - - try { - PeerGroupConfigAdv netGroupConfig = (PeerGroupConfigAdv) config.getSvcConfigAdvertisement(PeerGroup.peerGroupClassID); - NetGroupTunables tunables; - - if (null == netGroupConfig) { - tunables = new NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config"), new NetGroupTunables()); - } else { - tunables = new NetGroupTunables(netGroupConfig.getPeerGroupID(), netGroupConfig.getName(), netGroupConfig.getDesc()); - } - - net = newNetPeerGroup(worldGroup, config, tunables.id, tunables.name, tunables.desc, null); - } finally { - worldGroup.unref(); - } - } - - /** - * Constructs a Net Peer Group and the World Peer Group using the - * configuration specified by the provided ConfigParams and using the - * specified storeHome location for persistence. The resulting Net Peer - * Group instance will use the group information provided in the - *

      - * This constructor is provided in anticipation of other improvements - * to the peer group instantiation process. Currently it has some - * unreasonable limitations which keep it from being very useful. In a - * future release it will be improved. - * - * @param config The configuration to use for the newly created World Peer - * Group and Net Peer Groups. - * @param storeHome The optional location that the World Peer Group, the - * Net Peer Group and its' services should use for storing persistent and - * transient information. May be {@code null} if the World Peer Group is - * not provided a persistent store (though this not currently supported). - * @throws PeerGroupException Thrown for problems constructing the Net Peer - * Group. - * @param parentGroup the parent peer group - */ - public NetPeerGroupFactory(PeerGroup parentGroup, ConfigParams config, URI storeHome) throws PeerGroupException { - - if (config != parentGroup.getConfigAdvertisement()) { - throw new IllegalArgumentException("This constructor cannot currently accept group parameters different than the parent group"); - } - - if (null == storeHome) { - if (null != parentGroup.getStoreHome()) { - throw new IllegalArgumentException("This constructor cannot currently accept a different store location than the parent group"); - } - } else { - if (!storeHome.equals(parentGroup.getStoreHome())) { - throw new IllegalArgumentException("This constructor cannot currently accept a different store location than the parent group"); - } - } - - ConfigParams cp = parentGroup.getConfigAdvertisement(); - PeerGroupConfigAdv netGroupConfig = (PeerGroupConfigAdv) cp.getSvcConfigAdvertisement(PeerGroup.peerGroupClassID); - NetGroupTunables tunables; - - if (null == netGroupConfig) { - tunables = new NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config"), new NetGroupTunables()); - } else { - tunables = new NetGroupTunables(netGroupConfig.getPeerGroupID(), netGroupConfig.getName(), netGroupConfig.getDesc()); - } - - net = newNetPeerGroup(parentGroup, config, tunables.id, tunables.name, tunables.desc, null); - } - - /** - * Constructs a Net Peer Group and the World Peer Group using the - * configuration specified by the provided ConfigParams and using the - * specified storeHome location for persistence. - * - * @deprecated With the addition of support for {@code PeerGroupConfigAdv} - * this constructor is being deprecated as the precedence of settings is - * ambiguous. - * - * @param config The configuration to use for the newly created World Peer - * Group and Net Peer Groups. - * @param storeHome The optional location that the World Peer Group, the - * Net Peer Group and its' services should use for storing persistent and - * transient information. May be {@code null} if the World Peer Group is - * not provided a persistent store (though this not currently supported). - * @param id The PeerGroupID which will be used for the new Net Peer Group - * instance. - * @param name The name which will be used for the new Net Peer Group - * instance. - * @param desc The description which will be used for the new Net Peer Group - * instance. You can construct an {@code XMLDocument} from a {@code String} - * via : - *

      -     *     XMLDocument asDoc = StructuredDocumentFactory.newStructuredDocument( MimeMediaType.XMLUTF8, "desc", asString );
      -     * 
      - * @throws PeerGroupException Thrown for problems constructing the Net Peer - * Group. - */ - @Deprecated - public NetPeerGroupFactory(ConfigParams config, URI storeHome, ID id, String name, XMLElement desc) throws PeerGroupException { - WorldPeerGroupFactory world = new WorldPeerGroupFactory(config, storeHome); - PeerGroup worldGroup = world.getInterface(); - - try { - net = newNetPeerGroup(worldGroup, config, id, name, desc, null); - } finally { - worldGroup.unref(); - } - } - - /** - * Constructs a Net Peer Group instance using the specified parent peer - * group (normally the World Peer Group). This is the preferred constructor - * for constructing a private Net Peer Group. - * - * @deprecated With the addition of support for {@code PeerGroupConfigAdv} - * this constructor is being deprecated as the precedence of settings is - * ambiguous. - * - * @param parentGroup The Peer Group which will be the parent of the - * newly created net peer group. This should normally be the World Peer - * Group. - * @param id The PeerGroupID which will be used for the new Net Peer Group - * instance. - * @param name The name which will be used for the new Net Peer Group - * instance. - * @param desc The description which will be used for the new Net Peer Group - * instance. You can construct an {@code XMLDocument} from a {@code String} - * via : - *

      -     *     XMLDocument asDoc = StructuredDocumentFactory.newStructuredDocument( MimeMediaType.XMLUTF8, "desc", asString );
      -     * 
      - * @throws PeerGroupException Thrown for problems constructing the Net Peer - * Group. - */ - @Deprecated - public NetPeerGroupFactory(PeerGroup parentGroup, ID id, String name, XMLElement desc) throws PeerGroupException { - net = newNetPeerGroup(parentGroup, null, id, name, desc, null); - } - - /** - * Constructs a Net Peer Group instance using the specified parent peer - * group (normally the World Peer Group). This is the preferred constructor - * for constructing a private Net Peer Group with a specific implementation. - * - * @deprecated With the addition of support for {@code PeerGroupConfigAdv} - * this constructor is being deprecated as the precedence of settings is - * ambiguous. - * - * @param parentGroup The Peer Group which will be the parent of the newly - * created net peer group. This should normally be the World Peer - * - * @param id The PeerGroupID which will be used for the new Net Peer Group - * instance. - * @param name The name which will be used for the new Net Peer Group - * instance. - * @param desc The description which will be used for the new Net Peer Group - * instance. You can construct an {@code XMLDocument} from a {@code String} - * via : - *

      -     *     XMLDocument asDoc = StructuredDocumentFactory.newStructuredDocument( MimeMediaType.XMLUTF8, "desc", asString );
      -     * 
      - * @param moduleImplAdv The Module Impl Advertisement for the new Net Peer - * Group instance. - * @throws PeerGroupException Thrown for problems constructing the Net Peer - * Group. - */ - @Deprecated - public NetPeerGroupFactory(PeerGroup parentGroup, ID id, String name, XMLElement desc, ModuleImplAdvertisement moduleImplAdv) throws PeerGroupException { - net = newNetPeerGroup(parentGroup, null, id, name, desc, moduleImplAdv); - } - - /** - * Constructs a Net Peer Group instance using the specified parent peer - * group (normally the World Peer Group). This is the preferred constructor - * for constructing a Net Peer Group with a specific implementation. - * - * @param parentGroup The Peer Group which will be the parent of the - * newly created net peer group. This should normally be the World Peer - * Group. - * @param config The configuration parameters for the newly created Net Peer - * Group instance. - * @param moduleImplAdv The Module Impl Advertisement for the new Net Peer - * Group instance. - * @throws PeerGroupException Thrown for problems constructing the Net Peer - * Group. - */ - public NetPeerGroupFactory(PeerGroup parentGroup, ConfigParams config, ModuleImplAdvertisement moduleImplAdv) throws PeerGroupException { - PeerGroupConfigAdv netGroupConfig = (PeerGroupConfigAdv) config.getSvcConfigAdvertisement(PeerGroup.peerGroupClassID); - NetGroupTunables tunables; - - if (null == netGroupConfig) { - tunables = new NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config"), new NetGroupTunables()); - } else { - tunables = new NetGroupTunables(netGroupConfig.getPeerGroupID(), netGroupConfig.getName(), netGroupConfig.getDesc()); - } - - net = newNetPeerGroup(parentGroup, config, tunables.id, tunables.name, tunables.desc, moduleImplAdv); - } - - /** - * Returns a strong (reference counted) interface object for the Net Peer - * Group instance. This reference should be explicitly unreferenced when it - * is no longer needed. - * - * @return A strong (reference counted) interface object for the Net Peer Group. - * @see PeerGroup#unref() - */ - public PeerGroup getInterface() { - return (PeerGroup) net.getInterface(); - } - - /** - * Returns a weak (non-reference counted) interface object for the Net Peer Group. - * - * @return A weak (non-reference counted) interface object for the Net Peer Group. - * @see PeerGroup#getWeakInterface() - */ - public PeerGroup getWeakInterface() { - return net.getWeakInterface(); - } - - /** - * Construct the new Net Peer Group instance. - * - * @param parentGroup The parent group of the newly created net peer group. - * @param config Configuration parameters for the newly created net peer group. - * @param id The name to use for the newly created Net Peer Group. - * @param name The name to use for the newly created Net Peer Group. - * @param desc The description to use for the newly created Net Peer Group. - * @param implAdv The Module Impl Advertisement for the new Net Peer Group - * instance or {@code null} to use the advertisement returned by - * {@ link PeerGroup.getAllPurposePeerGroupImplAdvertisement()}. - * @return the PeerGroup - * @throws PeerGroupException Thrown for errors instantiating the new Net - * Peer Group instance. - */ - private PeerGroup newNetPeerGroup(PeerGroup parentGroup, ConfigParams config, ID id, String name, XMLElement desc, ModuleImplAdvertisement implAdv) throws PeerGroupException { - synchronized (PeerGroup.globalRegistry) { - PeerGroup result = PeerGroup.globalRegistry.lookupInstance((PeerGroupID) id); - - if (null != result) { - result.unref(); - throw new PeerGroupException("Only a single instance of a Peer Group may be instantiated at a single time."); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info( "Instantiating net peer group : " + id + - "\n\tParent : " + parentGroup + - "\n\tID : " + id + - "\n\tName : " + name + - "\n\timpl : " + implAdv); - } - - try { - if (null == implAdv) { - // Use the default Peer Group Impl Advertisement - implAdv = parentGroup.getAllPurposePeerGroupImplAdvertisement(); - } - - // Build the group - GenericPeerGroup.setGroupConfigAdvertisement(id,config); - - result = (PeerGroup) parentGroup.loadModule(id, implAdv); - - // Set the name and description - // FIXME 20060217 bondolo How sad, we can't use our XML description. - if (null != desc) { - result.publishGroup(name, desc.getTextValue()); - } else { - result.publishGroup(name, null); - } - - return result; - } catch (PeerGroupException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "newNetPeerGroup failed", failed); - } - // rethrow - throw failed; - } catch (RuntimeException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "newNetPeerGroup failed", e); - } - // rethrow - throw e; - } catch (Exception e) { - // should be all other checked exceptions - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "newNetPeerGroup failed", e); - } - // Simplify exception scheme for caller: every sort of problem - // wrapped in a PeerGroupException. - throw new PeerGroupException("newNetPeerGroup failed", e); - } - } - } - - /** - * Holds the construction tunables for the Net Peer Group. This consists of - * the peer group id, the peer group name and the peer group description. - */ - static class NetGroupTunables { - - final ID id; - final String name; - final XMLElement desc; - - /** - * Constructor for loading the default Net Peer Group construction - * tunables. - */ - NetGroupTunables() { - id = PeerGroupID.defaultNetPeerGroupID; - name = "NetPeerGroup"; - desc = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", "default Net Peer Group"); - } - - /** - * Constructor for loading the default Net Peer Group construction - * tunables. - * - * @param pgid the PeerGroupID - * @param pgname the group name - * @param pgdesc the group description - */ - NetGroupTunables(ID pgid, String pgname, XMLElement pgdesc) { - id = pgid; - name = pgname; - desc = pgdesc; - } - - /** - * Constructor for loading the Net Peer Group construction - * tunables from the provided resource bundle. - * - * @param rsrcs The resource bundle from which resources will be loaded. - * @param defaults default values - */ - NetGroupTunables(ResourceBundle rsrcs, NetGroupTunables defaults) { - ID idTmp; - String nameTmp; - XMLElement descTmp; - - try { - String idTmpStr = rsrcs.getString("NetPeerGroupID").trim(); - - if (idTmpStr.startsWith(ID.URNNamespace + ":")) { - idTmpStr = idTmpStr.substring(5); - } - idTmp = IDFactory.fromURI(new URI(ID.URIEncodingName + ":" + ID.URNNamespace + ":" + idTmpStr)); - nameTmp = rsrcs.getString("NetPeerGroupName").trim(); - descTmp = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", - rsrcs.getString("NetPeerGroupDesc").trim()); - } catch (Exception failed) { - if (null != defaults) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "NetPeerGroup tunables not defined or could not be loaded. Using defaults.", failed); - } - - idTmp = defaults.id; - nameTmp = defaults.name; - descTmp = defaults.desc; - } else { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "NetPeerGroup tunables not defined or could not be loaded.", failed); - } - - throw new IllegalStateException("NetPeerGroup tunables not defined or could not be loaded."); - } - } - - id = idTmp; - name = nameTmp; - desc = descTmp; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/PeerGroup.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/PeerGroup.java deleted file mode 100644 index 7e900561..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/PeerGroup.java +++ /dev/null @@ -1,1003 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.peergroup; - - -import net.jxta.access.AccessService; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.Element; -import net.jxta.endpoint.EndpointService; -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.ProtocolNotSupportedException; -import net.jxta.exception.ServiceNotFoundException; -import net.jxta.id.ID; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peer.PeerInfoService; -import net.jxta.pipe.PipeService; -import net.jxta.platform.JxtaLoader; -import net.jxta.platform.Module; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.resolver.ResolverService; -import net.jxta.service.Service; - -import java.io.IOException; -import java.lang.ref.Reference; -import java.lang.ref.WeakReference; -import java.net.URI; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - - -/** - * Peer groups are formed as a collection of peers that have agreed upon a - * common set of services. Each peer group is assigned a unique peer group ID - * and a peer group advertisement. The peer group advertisement contains a - * ModuleSpecID which refers to a module specification for this peer group. - *

      - * The peer group specification mandates each of the group services (membership, - * discovery, resolver, etc). Implementations of that specification are - * described by ModuleImplAdvertisements which are identified by the group's - * ModuleSpecID. Implementations are responsible for providing the services mandated - * by the specification. - *

      - * The java reference implementation achieves this by loading additional Modules - * which ModuleSpecIDs are listed by the group implementation advertisement. - *

      - * In order to fully participate in a group, a peer may need to authenticate - * with the group using the peer group membership service. - * - * @see net.jxta.peergroup.PeerGroupID - * @see net.jxta.service.Service - * @see net.jxta.peergroup.PeerGroupFactory - * @see net.jxta.protocol.PeerGroupAdvertisement - * @see net.jxta.protocol.ModuleImplAdvertisement - * @see net.jxta.platform.ModuleSpecID - * @see net.jxta.platform.ModuleClassID - */ -public interface PeerGroup extends Service { - - /** - * Look for needed ModuleImplAdvertisement in this group. - */ - public final static int Here = 0; - - /** - * Look for needed ModuleImplAdvertisement in the parent group of this group. - */ - public final static int FromParent = 1; - - /** - * Look for needed ModuleImplAdvertisement in both this group and its parent. - */ - public final static int Both = 2; - - /** - * Default life time for group advertisements in the publisher's cache. - * (a year) - */ - // without casting to long we lose precision - public final static long DEFAULT_LIFETIME = (long) 1000 * (long) 3600 * (long) 24 * 365L; - - /** - * Default expiration time for discovered group advertisements. (2 weeks) - */ - // without casting to long we lose precision - public final static long DEFAULT_EXPIRATION = (long) 1000 * (long) 3600 * (long) 24 * 14L; - - /** - * Global registry of instantiated peer groups. We allow only a single - * PeerGroup instance for a specific PeerGroupID within the context of the - * classloader JXTA is loaded into. - */ - static class GlobalRegistry { - - private final Map> registry = new HashMap>(8); - - /** - * Registers a new instance. - * - * @param gid the ID of the group of which an instance is being registered. - * @param pg the group instance being registered. - * @return false if the instance could not be registered because there - * was already such an instance registered. - */ - public synchronized boolean registerInstance(PeerGroupID gid, PeerGroup pg) { - - Reference ref = registry.get(gid); - - if ((ref != null) && (ref.get() != null)) { - return false; - } - - // If the ref is a dead instance, we can also replace it. - registry.put(gid, new WeakReference(pg)); - return true; - } - - /** - * Unregisters a group instance (normally because the group is being - * stopped. - * - * @param gid the ID of the group of which an instance is unregistered. - * @param pg the group instance itself (serves as a credential). - * @return false if the group could not be unregistered because no such - * registration (exact ID, exact object) was not found. - */ - public synchronized boolean unRegisterInstance(PeerGroupID gid, PeerGroup pg) { - - Reference ref = registry.get(gid); - - if (ref == null) { - return false; - } - - PeerGroup found = ref.get(); - - if (found == null) { - // Dead instance. Remove from table. - registry.remove(gid); - return false; - } - - // Note the use of "!=", not "!equals()" - if (pg != found) { - return false; - } - - registry.remove(gid); - return true; - } - - /** - * Returns a running instance of the peergroup with given ID if any - * exists. The instance should be {@link PeerGroup#unref()}ed when it is - * no longer needed. - * - * @param gid the id of the group of which an instance is wanted. - * @return the group, or {@code null} if no instance exists. - */ - public synchronized PeerGroup lookupInstance(PeerGroupID gid) { - - Reference ref = registry.get(gid); - - if (ref == null) { - return null; - } - - PeerGroup pg = ref.get(); - - if (pg == null) { - // Dead instance. remove from table. - registry.remove(gid); - return null; - } - - // Returns an interface object. Therefore a module that got the - // peergroup through lookup cannot unregister it if the group - // protects itself by returning an interface object different from - // the group object. In general only the group itself can - // unregister when being torn down. Unregistration will also be - // automatic if the grp object is GC'ed (the references are weak - // references). - return (PeerGroup) pg.getInterface(); - } - - /** - * Returns a running instance of the peergroup with given ID if any - * exists. - * - * @param gid The id of the group of which an instance is wanted. - * @return The group, or {@code null} if no instance exists. - */ - synchronized PeerGroup getInstance(PeerGroupID gid) { - - Reference ref = registry.get(gid); - - if (ref == null) { - return null; - } - - PeerGroup pg = ref.get(); - - if (pg == null) { - // Dead instance. remove from table. - registry.remove(gid); - return null; - } - - return pg; - } - - /** - * Returns {@code true} if there is a registered peergroup of the - * specified ID. - * - * @param gid the id of the group of which an instance is wanted. - * @return {@code} true if the peergroup is currently registered - * otherwise false; - */ - public synchronized boolean registeredInstance(PeerGroupID gid) { - - Reference ref = registry.get(gid); - - if (ref == null) { - return false; - } - - PeerGroup pg = ref.get(); - - if (pg == null) { - // Dead instance. remove from table. - registry.remove(gid); - return false; - } - - return true; - } - } - - /** - * Well known classes for the basic services. - * - *

      FIXME: we should make a "well-known ID" encoding implementation that - * has its own little name space of human readable names...later. - * To keep their string representation shorter, we put our small spec - * or role pseudo unique ID at the front of the second UUID string. - * Base classes do not need an explicit second UUID string because it is - * all 0. - * - *

      The type is always the last two characters, no-matter the total length. - */ - - /** - * Prefix string for all of the Well Known IDs declared in this interface. - */ - static final String WK_ID_PREFIX = ID.URIEncodingName + ":" + ID.URNNamespace + ":uuid-DeadBeefDeafBabaFeedBabe"; - - /** - * Well known module class identifier: peer group - */ - public final static ModuleClassID peerGroupClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000105")); - - /** - * Well known module class identifier: resolver service - */ - public final static ModuleClassID resolverClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000205")); - - /** - * Well known module class identifier: discovery service - */ - public final static ModuleClassID discoveryClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000305")); - - /** - * Well known module class identifier: pipe service - */ - public final static ModuleClassID pipeClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000405")); - - /** - * Well known module class identifier: membership service - */ - public final static ModuleClassID membershipClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000505")); - - /** - * Well known module class identifier: rendezvous service - */ - public final static ModuleClassID rendezvousClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000605")); - - /** - * Well known module class identifier: peerinfo service - */ - public final static ModuleClassID peerinfoClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000705")); - - /** - * Well known module class identifier: endpoint service - */ - public final static ModuleClassID endpointClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000805")); - - // FIXME: EndpointProtocols should probably all be of the same class - // and of different specs and roles... But we'll take a shortcut for now. - - /** - * Well known module class identifier: tcp protocol - */ - public final static ModuleClassID tcpProtoClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000905")); - - /** - * Well known module class identifier: http protocol - */ - public final static ModuleClassID httpProtoClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000A05")); - - /** - * Well known module class identifier: router protocol - */ - public final static ModuleClassID routerProtoClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000B05")); - - /** - * Well known module class identifier: application - */ - public final static ModuleClassID applicationClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000C05")); - - /** - * Well known module class identifier: tlsProtocol - */ - public final static ModuleClassID tlsProtoClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000D05")); - - /** - * Well known module class identifier: ProxyService - */ - public final static ModuleClassID proxyClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000E05")); - - /** - * Well known module class identifier: RelayProtocol - */ - public final static ModuleClassID relayProtoClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000000F05")); - - /** - * Well known module class identifier: AccessService - */ - public final static ModuleClassID accessClassID = - ModuleClassID.create(URI.create(WK_ID_PREFIX + "0000001005")); - - /** - * Well known group specification identifier: the platform - */ - public final static ModuleSpecID refPlatformSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000010106")); - - /** - * Well known group specification identifier: the Network Peer Group - */ - public final static ModuleSpecID refNetPeerGroupSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000010206")); - - /** - * Well known service specification identifier: the standard resolver - */ - public final static ModuleSpecID refResolverSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000020106")); - - /** - * Well known service specification identifier: the standard discovery - */ - public final static ModuleSpecID refDiscoverySpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000030106")); - - /** - * Well known service specification identifier: the standard pipe service - */ - public final static ModuleSpecID refPipeSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000040106")); - - /** - * Well known service specification identifier: the standard membership - */ - public final static ModuleSpecID refMembershipSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000050106")); - - /** - * Well known service specification identifier: the standard rendezvous - */ - public final static ModuleSpecID refRendezvousSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000060106")); - - /** - * Well known service specification identifier: the standard peerinfo - */ - public final static ModuleSpecID refPeerinfoSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000070106")); - - /** - * Well known service specification identifier: the standard endpoint - */ - public final static ModuleSpecID refEndpointSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000080106")); - - /** - * Well known endpoint protocol specification identifier: the standard - * tcp endpoint protocol - */ - public final static ModuleSpecID refTcpProtoSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000090106")); - - /** - * Well known endpoint protocol specification identifier: the standard - * http endpoint protocol - */ - public final static ModuleSpecID refHttpProtoSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "0000000A0106")); - - /** - * Well known endpoint protocol specification identifier: the standard - * router - */ - public final static ModuleSpecID refRouterProtoSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "0000000B0106")); - - /** - * Well known endpoint protocol specification identifier: the standard - * tls endpoint protocol - */ - public final static ModuleSpecID refTlsProtoSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "0000000D0106")); - - /** - * Well known group specification identifier: an all purpose peer group - * specification. The java reference implementation implements it with - * the StdPeerGroup class and all the standard platform services and no - * endpoint protocols. - */ - public final static ModuleSpecID allPurposePeerGroupSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000010306")); - - /** - * Well known application: the shell - */ - public final static ModuleSpecID refShellSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "0000000C0206")); - - /** - * Well known application: the Proxy - */ - public final static ModuleSpecID refProxySpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "0000000E0106")); - - /** - * Well known endpoint protocol specification identifier: the standard - * relay endpoint protocol - */ - public final static ModuleSpecID refRelayProtoSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "0000000F0106")); - - /** - * Well known access specification identifier: the standard - * access service - */ - public final static ModuleSpecID refAccessSpecID = - ModuleSpecID.create(URI.create(WK_ID_PREFIX + "000000100106")); - - /** - * The global registry of Peer Group instances. Operations involving the - * instantiation or orderly shutdown of Peer Groups should synchronize upon - * this object. - */ - final static GlobalRegistry globalRegistry = new GlobalRegistry(); - - /** - * Returns the Thread Group in which threads for this peer group will live. - * This is currently used only for debugging purposes so that the source of - * a thread can be determined. - * - * @return ThreadGroup - */ - public ThreadGroup getHomeThreadGroup(); - - /** - * Returns the class loader for this group. - * - * @return JxtaLoader The JXTA Class loader used by this group. - */ - public JxtaLoader getLoader(); - - /** - * Returns the whether the group member is a Rendezvous peer for the group. - * - * @return boolean true if the peer is a rendezvous for the group. - */ - public boolean isRendezvous(); - - /** - * Return the PeerGroupAdvertisement for this group. - * - * @return PeerGroupAdvertisement this Group's advertisement. - */ - public PeerGroupAdvertisement getPeerGroupAdvertisement(); - - /** - * Return the PeerAdvertisement of the local Peer within this Peer Group. - * - * @return the PeerAdvertisement of the local Peer within this Peer Group. - */ - public PeerAdvertisement getPeerAdvertisement(); - - /** - * Lookup for a service by name. - * - * @param name the service identifier. - * @return Service, the Service registered by that name - * @throws ServiceNotFoundException could not find the service requested - */ - public Service lookupService(ID name) throws ServiceNotFoundException; - - /** - * Lookup for a service by class ID and index in a map. - *

      - * More than one service in a group may be of a given ModuleClass. - * However each of them has a unique assigned ID which serves as the - * index in the map of services. In most cases, there is only one - * service of each given Module Class, and the ID of that Module Class - * is the assigned ID. Otherwise, the group may have a list of existing - * assigned ID per base class. This routine may be used to retrieve - * services of the given Module Class and index in that list. - * In the absence of a mapping, index 0 is still valid and - * corresponds to the service which assigned ID is exactly the - * given ID. - * Group objects with a map are normally wrappers tailored - * specially by the loader of a module (often the group itself) in order - * to provide a map appropriate for that module. Modules that do not use - * more than one service of a given base class normally never need to call - * this method; lookupService(ID) is equivalent to lookupService(ID, 0) - * and will transparently remap index 0 to whatever the group's - * structure defines as the default for the invoking service. - *

      - * Note: traditionally, the given ID is expected to be a base Module - * Class ID, and the assigned ID of a Module is a Class ID of the - * same base class with a role suffix to make it unique. If the given - * ID already contains a role suffix, there may exist an entry for - * it in the map anyway, if not (which is the expected use pattern), - * then only index 0 exists and the given ID is used whole and - * untranslated. - * - * @param name the service identifier - * @param roleIndex the index in the list of assigned IDs that match - * that identifier. - * @return Service, the corresponding Service - * @throws ServiceNotFoundException Could not find the service requested. - * @since JXTA 2.3.1 - */ - public Service lookupService(ID name, int roleIndex) throws ServiceNotFoundException; - - /** - * Returns the map of the assigned IDs currently associated with the given - * ModuleClassID by this PeerGroup object. The IDs are returned in the order - * of their index in the map. So the first ID returned will be identical to - * what would be returned by the lookup method for the given ID and index 0. - * If there is no explicit such map, this method will return a singleton - * containing the given ID as this is the default mapping. There is no - * guarantee that any of the returned IDs correspond to an actually - * registered service. This method only maps IDs. - * - * @param name The ModuleClassID for which the map is desired. - * @return Iterator An iterator on a collection of the IDs to which the given ID maps. - * @since JXTA 2.3.1 - */ - public Iterator getRoleMap(ID name); - - /** - * Return true if the provided compatibility statement is compatible with this group. - * - * @param compat compatibility element - * @return boolean True if the statement is compatible. - */ - public boolean compatible(Element compat); - - /** - * Load a Module from a ModuleImplAdv. - *

      - * Compatibility is checked and load is attempted. If compatible and - * loaded successfully, the resulting Module is initialized and returned. - * In most cases the other loadModule() method should be preferred, since - * unlike this one, it will seek many compatible implementation - * advertisements and try them all until one works. The home group of the new - * module (its' parent group if the new Module is a group) will be this group. - * - * @param assignedID Id to be assigned to that module (usually its ClassID). - * @param impl An implementation advertisement for that module. - * @return Module the module loaded and initialized. - * @throws ProtocolNotSupportedException The implementation described by the - * advertisement is incompatible with this peer. The module cannot be loaded. - * @throws PeerGroupException The module could not be loaded or initialized - */ - public Module loadModule(ID assignedID, Advertisement impl) throws ProtocolNotSupportedException, PeerGroupException; - - /** - * Load a module from a ModuleSpecID - *

      - * Advertisement is sought, compatibility is checked on all candidates - * and load is attempted. The first one that is compatible and loads - * successfully is initialized and returned. - * - * @param assignedID Id to be assigned to that module (usually its ClassID). - * @param specID The specID of this module. - * @param where May be one of: {@code Here}, {@code FromParent}, or - * {@code Both}, meaning that the implementation advertisement will be - * searched in this group, its parent or both. As a general guideline, the - * implementation advertisements of a group should be searched in its - * prospective parent (that is {@code Here}), the implementation - * advertisements of a group standard service should be searched in the same - * group than where this group's advertisement was found (that is, - * {@code FromParent}), while applications may be sought more freely - * ({@code Both}). - * @return Module the new module, or null if no usable implementation was - * found. - */ - public Module loadModule(ID assignedID, ModuleSpecID specID, int where); - - /** - * Publish this group's Peer Group Advertisement. The Advertisement will be - * published using the parent peer group's Discovery service. - *

      - * Calling this method is only useful if the group is being created - * from scratch and the PeerGroup advertisement has not been - * created beforehand. In such a case, the group has never been named or - * described. Therefore this information has to be supplied here. - * - * @param name The name of this group. - * @param description The description of this group. - * @throws IOException The publication could not be accomplished - * because of a network or storage failure. - */ - public void publishGroup(String name, String description) throws IOException; - - /* - * Valuable application helpers: Various methods to instantiate - * groups. - */ - - /** - * Instantiate a peer group from the provided advertisement. This peer - * group will be the parent of the newly instantiated peer group. - *

      - * The pgAdv itself may be all new and unpublished. Therefore, the two - * typical uses of this routine are: - *

      - *

        - *
      • Creating an all new group with a new ID while using an existing - * and published implementation. (Possibly a new one published for - * that purpose). The information should first be gathered in a new - * PeerGroupAdvertisement which is then passed to this method.
      • - *

        - *

      • Instantiating a group which advertisement has already been - * discovered (therefore there is no need to find it by groupID - * again).
      • - *
      - * - * @param pgAdv The advertisement for the group to be instantiated. - * @return PeerGroup the initialized (but not started) peergroup. - * @throws PeerGroupException For problems instantiating the peer group. - */ - public PeerGroup newGroup(Advertisement pgAdv) throws PeerGroupException; - - /** - * Instantiates a peer group from its elementary pieces - * and publishes the corresponding PeerGroupAdvertisement. - * The pieces are: the groups implementation adv, the group id, - * the name and description. - *

      - * The typical use of this routine is creating a whole new group based - * on a newly created and possibly unpublished implementation adv. - *

      - * This is a convenience method equivalent to either: - *

      - *

      -     * newGrp = thisGroup.loadModule(gid, impl);
      -     * newGrp.publishGroup(name, description);
      -     * 
      - * or, but only if the implementation advertisement has been published: - *

      - *

      -     * newPGAdv = AdvertisementFactory.newAdvertisement(
      -     *                 PeerGroupAdvertisement.getAdvertisementType());
      -     * newPGAdv.setPeerGroupID(gid);
      -     * newPGAdv.setModuleSpecID(impl.getModuleSpecID());
      -     * newPGAdv.setName(name);
      -     * newPGAdv.setDescription(description);
      -     * newGrp = thisGroup.newGroup(newPGAdv);
      -     * 
      - * - * @param gid The ID of that group. If null then a new group ID - * will be chosen. - * @param impl The advertisement of the implementation to be used. - * @param name The name of the group. - * @param description A description of this group. - * @return PeerGroup the initialized (but not started) peergroup. - * @throws PeerGroupException Thrown if the group could not be instantiated. - */ - public PeerGroup newGroup(PeerGroupID gid, Advertisement impl, String name, String description) throws PeerGroupException; - - /** - * Instantiate a group from its Peer Group ID only. Use this when using a - * group that has already been published and discovered. - *

      - * The typical uses of this routine are therefore: - *

      - *

        - *
      • Instantiating a peer group which is assumed to exist and whose Peer - * Group ID is already known.
      • - *

        - *

      • Creating a new peer group instance using an already published - * Group advertisement, typically published for that purpose. All other - * referenced advertisements must also be available.
      • - *
      - *

      - * To create a group from a known implAdv, just use - * {@link #loadModule(ID,Advertisement)} or even:

      - *

      - * - * grp = new GroupSubClass(); - * grp.init(parentGroup, gid, impladv); - * - *

      - * then, REMEMBER TO PUBLISH THE GROUP IF IT IS ALL NEW. - * - * @param gid the groupID. - * @return PeerGroup the initialized (but not started) peergroup. - * @throws PeerGroupException Thrown if the group could not be instantiated. - */ - public PeerGroup newGroup(PeerGroupID gid) throws PeerGroupException; - - /* - * Shortcuts to the well-known services, in order to avoid calls to - * {@link #lookupService(ID)}. - */ - - /** - * Return the Rendezvous Service for this Peer Group. This service is - * optional and may not be present in all groups. - * - * @return The Rendezvous Service for this Peer Group or null - * if there is no Rendezvous Service in this Peer Group. - */ - public RendezVousService getRendezVousService(); - - /** - * Return the Endpoint Service for this Peer Group. This service is - * present in every Peer Group. - * - * @return EndpointService The Endpoint Service for this Peer Group. - */ - public EndpointService getEndpointService(); - - /** - * Return the Resolver Service for this Peer Group. This service is - * present in every Peer Group. - * - * @return ResolverService The Resolver Service for this Peer Group. - */ - public ResolverService getResolverService(); - - /** - * Return the Discovery Service for this Peer Group. - * - * @return The Discovery Service for this Peer Group or null - * if there is no PeerInfo Service in this Peer Group. - */ - public DiscoveryService getDiscoveryService(); - - /** - * Return the PeerInfo Service for this Peer Group. - * - * @return The PeerInfo Service for this Peer Group or null - * if there is no PeerInfo Service in this Peer Group. - */ - public PeerInfoService getPeerInfoService(); - - /** - * Return the Membership Service for this Peer Group. This service is - * present in every Peer Group. - * - * @return MembershipService The Membership Service for this Peer Group. - */ - public MembershipService getMembershipService(); - - /** - * Return the Pipe Service for this Peer Group. - * - * @return The Pipe Service for this Peer Group or null if - * there is no Pipe Service in this Peer Group. - */ - public PipeService getPipeService(); - - /** - * Return the Access Service for this Peer Group. This service is - * present in every Peer Group. - * - * @return AccessService The Access Service for this Peer Group. - * @since JXTA 2.1 - */ - public AccessService getAccessService(); - - // A few convenience methods. This information is available from the peer and peergroup advertisement. - - /** - * Return the Peer Group ID of this Peer Group. - * - * @return PeerGroupId The Peer Group ID of this Peer Group. - */ - public PeerGroupID getPeerGroupID(); - - /** - * Return the Peer ID by which this Peer is known within this Peer Group. - * - * @return the Peer ID by which this Peer is known within this Peer Group. - */ - public PeerID getPeerID(); - - /** - * Return the Name of this group. This name is not canonical, meaning that - * there may be other groups with the same name. - * - * @return String This groups's name or null if no name was - * specified. - */ - public String getPeerGroupName(); - - /** - * Return the name of the local peer within this group. This name is not - * canonical, meaning that there may be other peers with the same name. - * - * @return String This peer's name or null if no name was - * specified. - */ - public String getPeerName(); - - /** - * Returns the config advertisement for this peer in this group (if any). - * - * @return The advertisement or null if none is available. - */ - public ConfigParams getConfigAdvertisement(); - - /** - * Get an all purpose peerGroup ModuleImplAdvertisement that is compatible - * with this group. This impl adv can be used to create any group that - * relies only on the standard services. Or to derive other impl advs, using - * this impl advertisement as a basis. - *

      - * This defines a peergroup implementation that can be used for - * many purposes, and from which one may derive slightly different - * peergroup implementations. - *

      - * This definition is always the same and has a well known ModuleSpecID. - * It includes the basic service, no protocols and the shell for main - * application. - *

      - * The user must remember to change the specID if the set of services - * protocols or applications is altered before use. - * - * @return ModuleImplAdvertisement The new peergroup impl adv. - * @throws Exception if an error occurs while creating the implementation advertisement - */ - public ModuleImplAdvertisement getAllPurposePeerGroupImplAdvertisement() throws Exception; - - /** - * Explicitly notifies a group interface that it will no-longer be - * used (similar to dispose). Does nothing to a real group object, - * only has an effect on a group interface. - */ - public void unref(); - - /** - * Returns a weak interface object that represents this - * group. - *

      - * A weak interface object has no life-cycle privileges over - * the group that it represents and therefore its users have - * no accountability. A weak interface object is safe to - * give away but holds no promise of sustained validity. - *

      - * Whatever code gave away a weak interface object retains - * the power of terminating the group object from which it - * was obtained, thereby making the weak interface - * object invalid. - *

      - * A weak interface object is immutable; its unref and stopApp - * methods do nothing. Its validity is exactly that of the - * group or interface object from which it was obtained. - *

      - * A weak interface object can be obtained from an interface - * object, or from a real group object, or from a weak interface - * object. In the later case, the object returned may be - * the original weak interface object since such objects - * are immutable. - *

      - * Whatever code obtains a weak interface object from a group object - * or regular interface object, remains entirely liable for invoking unref - * on the initial object before discarding it. Giving away a weak interface - * object is not equivalent to transferring ownership of the original. - * - * @return PeerGroup A weak interface object that represents this - * PeerGroup object. - * @since JXTA 2.2 - */ - public PeerGroup getWeakInterface(); - - /** - * Returns the parent group of this group. Not all groups have parents and - * some implementations may not reveal their parents. - * - * @return PeerGroup the parent group or null if a parent group - * if not available. - * @since JXTA 2.3 - */ - public PeerGroup getParentGroup(); - - /** - * Returns the location of the parent of all items that this peer group is - * using for persistently storing its preferences, cache, persistent store, - * properties, etc. May be {@code null} if the peergroup has no defined - * location for storing persistent data. - * - * @return The location of the parent of all persistent items stored by - * this peer group. - * @since JXTA 2.3.7 - */ - public URI getStoreHome(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/PeerGroupFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/PeerGroupFactory.java deleted file mode 100644 index bc182e5a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/PeerGroupFactory.java +++ /dev/null @@ -1,577 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.peergroup; - - -import net.jxta.document.Advertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.exception.ConfiguratorException; -import net.jxta.exception.JxtaError; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.logging.Logging; -import net.jxta.protocol.ConfigParams; - -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.net.URLConnection; -import java.util.MissingResourceException; -import java.util.PropertyResourceBundle; -import java.util.ResourceBundle; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * A factory for instantiating the JXTA core peer groups. - *

      - * JXTA comes with two peergroup implementations: - *

      - *

      - *
      Platform
      - *
      Implements the world peer group. Every peer starts by instantiating this - * peer group and then other peer groups are instantiated as needed. The World - * Peer Group's ID is invariant. - *

      - * The world peer group provides the minimum core services needed to find - * and instantiate other groups on a peer. The Platform - * implementation will assign a new ID to the peer, if it does not already have - * one.

      - *

      - *

      StdPeergroup
      - *
      This is currently used to implement all other kinds of peer groups. - * The first such peer group that it is instantiated after starting is known as - * The Net Peer Group. When the Platform starts it may - * optionally search for The Net Peer Group on the local network and, - * if found, instantiate it. Otherwise a default built-in configuration of - * The Net Peer Group is instantiated. - *

      - * A non-default configuration of The Net Peer Group may be set-up - * by the administrator in charge of the network domain inside which the peer - * is starting. The Net Peer Group is discovered via the Discovery - * protocol. Many such groups may be configured by an administrator.
      - *

      - * StdPeergroup may also be used to implement User-defined - * peer groups--Users can create new peer groups which use their own set of - * customized services.

      - *
      - * - * @see net.jxta.peergroup.PeerGroup - * @deprecated This factory has been deprecated in favour of {@link WorldPeerGroupFactory} - * and {@link NetPeerGroupFactory}. See the deprecations for the individual - * methods for the specific replacements/alternatives provided by the new - * factory classes. - */ -@Deprecated -public final class PeerGroupFactory { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(PeerGroupFactory.class.getName()); - - /** - * Constant for specifying no configurator. This configurator provides no - * configuration actions but does ensure that a valid configuration exists - * at the specified location. - */ - public final static Class NULL_CONFIGURATOR = net.jxta.impl.peergroup.NullConfigurator.class; - - /** - * Constant for specifying the default configurator. Currently this is the - * familiar AWT-based dialogue but in future is likely to become the - * UI-less automatic configurator. - */ - public final static Class DEFAULT_CONFIGURATOR = net.jxta.impl.peergroup.DefaultConfigurator.class; - - /** - * The class which will be instantiated as the World Peer Group. - */ - private static Class worldGroupClass = null; - - /** - * The ID of the network peer group. - */ - private static PeerGroupID netPGID = null; - - /** - * The name of the network peer group. - */ - private static String netPGName = null; - - /** - * The description of the network peer group. - */ - private static String netPGDesc = null; - - /** - * The class which will be instantiated to configure the World Peer - * Group. - */ - private static Class configurator = DEFAULT_CONFIGURATOR; - - /** - * the location which will serve as the parent for all stored items used - * by JXTA. - */ - private static URI storeHome = null; - - /** - * Static Method to initialize the world peer group class. - * - * @param c The Class which will be instantiated for the World Peer Group - * @deprecated Consider converting to use {@link WorldPeerGroupFactory#WorldPeerGroupFactory(Class,ConfigParams,URI)}. - */ - @Deprecated - public static void setPlatformClass(Class c) { - worldGroupClass = c; - } - - /** - * Static Method to initialize the std peer group class. - * - * @param c The Class which will be instantiated for most peer groups. - * @deprecated This method previously had no effect and has been removed with no alternatives. - */ - @Deprecated - public static void setStdPeerGroupClass(Class c) { - throw new UnsupportedOperationException("This feature has been removed. (sorry)"); - } - - /** - * Sets the description which will be used for new net peer group instances. - * - * @param desc The description which will be used for new net peer group instances. - * @deprecated Consider converting to use {@link NetPeerGroupFactory#NetPeerGroupFactory(ConfigParams,URI,ID,String,XMLElement)} - * or {@link NetPeerGroupFactory#NetPeerGroupFactory(PeerGroup,ID,String,XMLElement)}. - */ - @Deprecated - public static void setNetPGDesc(String desc) { - netPGDesc = desc; - } - - /** - * Sets the name which will be used for new net peer group instances. - * - * @param name The name which will be used for new net peer group instances. - * @deprecated Consider converting to use {@link NetPeerGroupFactory#NetPeerGroupFactory(ConfigParams,URI,ID,String,XMLElement)} - * or {@link NetPeerGroupFactory#NetPeerGroupFactory(PeerGroup,ID,String,XMLElement)}. - */ - @Deprecated - public static void setNetPGName(String name) { - netPGName = name; - } - - /** - * Sets the ID which will be used for new net peer group instances. - * - * @param id The ID which will be used for new net peer group instances. - * @deprecated Consider converting to use {@link NetPeerGroupFactory#NetPeerGroupFactory(ConfigParams,URI,ID,String,XMLElement)} - * or {@link NetPeerGroupFactory#NetPeerGroupFactory(PeerGroup,ID,String,XMLElement)}. - */ - @Deprecated - public static void setNetPGID(PeerGroupID id) { - netPGID = id; - } - - /** - * Get the optional configurator class for the world peer group. - * - * @return Class configurator class - * @deprecated Consider converting to use {@link NetPeerGroupFactory}. - */ - @Deprecated - public static Class getConfiguratorClass() { - return configurator; - } - - /** - * Set the optional configurator class for the World Peer Group. If present - * an instance of this class will be used to generate/update the - * configuration parameters for the World Peer Group whenever - * {@code newPlatform()} is invoked. - *

      - * All configuration actions for the World Peer Group may be completely - * disabled by specify {@code null} as the configurator class. The default - * configuration class is always initialized to {@code DEFAULT_CONFIGURATOR}. - * - * @param c The {@code Class} to use as a configurator for the World Peer - * Group. - * @deprecated Consider converting to use {@link NetPeerGroupFactory} and/or {@link WorldPeerGroupFactory}. - */ - @Deprecated - public static void setConfiguratorClass(Class c) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Setting configurator class to : " + c); - } - - configurator = c; - } - - /** - * Returns the location which will serve as the parent for all stored items - * used by JXTA. This method is intended for use by PeerGroup implementations - * and is not intended for use by applications. Applications and services - * should use the PeerGroup method with the same name. - * - * @return The location which will serve as the parent for all stored - * items used by JXTA. - * @see PeerGroup#getStoreHome() - * @deprecated Consider converting to use {@link NetPeerGroupFactory} and/or {@link WorldPeerGroupFactory}. - */ - @Deprecated - public static URI getStoreHome() { - if (null == storeHome) { - // Establish the default store location via long established hackery. - String jxta_path = System.getProperty("JXTA_HOME", ".jxta/"); - - File jxta_home = new File(jxta_path); - - jxta_home.mkdirs(); - URI defaultHome = jxta_home.toURI(); - - return defaultHome; - } - - return storeHome; - } - - /** - * Set the location which will serve as the parent for all stored items used by JXTA. - * - * @param newHome The absolute URI location which will serve as the parent - * for all stored items used by JXTA. Currently this must be a non-opaque URI. - * May also be {@code null} to restore the default value. - * @deprecated Consider converting to use {@link NetPeerGroupFactory} and/or {@link WorldPeerGroupFactory}. - */ - @Deprecated - public static void setStoreHome(URI newHome) { - - if (null != newHome) { - // Fail if the URI is not absolute. - if (!newHome.isAbsolute()) { - throw new IllegalArgumentException("Only absolute URIs accepted for store home location."); - } - - // Fail if the URI is Opaque. - if (newHome.isOpaque()) { - throw new IllegalArgumentException("Only hierarchical URIs accepted for store home location."); - } - - // Add a trailing slash if necessary. - if (!newHome.toString().endsWith("/")) { - newHome = URI.create(newHome.toString() + "/"); - } - } - - storeHome = newHome; - } - - /** - * Static Method to create a new peer group instance. - *

      - * After being created the init() method needs to be called, and - * the startApp() method may be called, at the invoker's discretion. - * - * @return PeerGroup instance of a new PeerGroup - * @deprecated This method was previously unused and has been removed with no alternatives. (it wasn't useful) - */ - @Deprecated - public static PeerGroup newPeerGroup() { - throw new UnsupportedOperationException("This feature has been removed. (sorry)"); - } - - /** - * Instantiates the World (Platform) Peer Group and can also optionally - * (re)configure the world peer group before instantiation using the - * configurator specified via {@link #setConfiguratorClass(Class)}. - *

      - * Only one instance of the World Peer Group may be created within the - * context of the {@code PeerGroupFactory}'s class loader. Invoking this - * method amounts to creating an instance of JXTA. - *

      - * The {@link PeerGroup#init(PeerGroup,ID,Advertisement)} method is - * called automatically. The {@link PeerGroup#startApp(String[])} method - * is left for the invoker to call if appropriate. - * - * @return PeerGroup The World Peer Group instance. - * @throws JxtaError Thrown for all checked Exceptions which occur during - * construction of the World Peer Group. - * @deprecated Consider converting to use {@link WorldPeerGroupFactory#WorldPeerGroupFactory()}. - */ - @Deprecated - public static PeerGroup newPlatform() { - - Class c = PeerGroupFactory.getConfiguratorClass(); - - if (null == c) { - c = NULL_CONFIGURATOR; - } - - Configurator configurator; - - try { - Constructor config_constructor = c.getConstructor(URI.class); - - configurator = (Configurator) config_constructor.newInstance(getStoreHome()); - } catch (InvocationTargetException ie) { - LOG.log(Level.SEVERE, "Uninstantiatable configurator: " + c, ie); - - throw new JxtaError("Uninstantiatable configurator: " + c, ie); - } catch (NoSuchMethodException ie) { - LOG.log(Level.SEVERE, "Uninstantiatable configurator: " + c, ie); - - throw new JxtaError("Uninstantiatable configurator: " + c, ie); - } catch (InstantiationException ie) { - LOG.log(Level.SEVERE, "Uninstantiatable configurator: " + c, ie); - - throw new JxtaError("Uninstantiatable configurator: " + c, ie); - } catch (IllegalAccessException iae) { - LOG.log(Level.SEVERE, "can\'t instantiate configurator: " + c, iae); - - throw new JxtaError("Can't instantiate configurator: " + c, iae); - } catch (ClassCastException cce) { - LOG.log(Level.SEVERE, "Not a Configurator :" + c, cce); - - throw new JxtaError("Not a Configurator :" + c, cce); - } - - ConfigParams pc; - - try { - pc = configurator.getConfigParams(); - } catch (ConfiguratorException cce) { - LOG.log(Level.SEVERE, "Could not retrieve configuration", cce); - - throw new JxtaError("Could not retrieve configuration", cce); - } - - try { - WorldPeerGroupFactory wpgf; - - if (null == worldGroupClass) { - wpgf = new WorldPeerGroupFactory(pc, getStoreHome()); - } else { - wpgf = new WorldPeerGroupFactory(worldGroupClass, pc, getStoreHome()); - } - - configurator.setConfigParams(pc); - configurator.save(); - - // Forget about the configurator - configurator = null; - - return wpgf.getInterface(); - } catch (RuntimeException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "newPlatform failed", e); - } - // rethrow - throw e; - } catch (Exception e) { - // should be all other checked exceptions - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "newPlatform failed", e); - } - - // Simplify exception scheme for caller: any sort of problem wrapped - // in a PeerGroupException. - throw new JxtaError("newPlatform failed", e); - } catch (Error e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "newPlatform failed", e); - } - // rethrow - throw e; - } - } - - /** - * Instantiates the net peer group using the provided parent peer group. - * - * @param ppg The parent group. - * @return PeerGroup The default netPeerGroup - * @throws PeerGroupException For failures in constructing the Net Peer Group. - * @deprecated Consider converting to use {@link NetPeerGroupFactory#NetPeerGroupFactory(PeerGroup,ID,String,XMLElement)}. - */ - @Deprecated - public static PeerGroup newNetPeerGroup(PeerGroup ppg) throws PeerGroupException { - - try { - NetPeerGroupFactory npgf; - - NetPeerGroupFactory.NetGroupTunables tunables; - - if (null == netPGID) { - // Determine net peer group configuration parameters if they - // have not already been set. - tunables = new NetPeerGroupFactory.NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config") - , - new NetPeerGroupFactory.NetGroupTunables()); - - // load overides from "${JXTA_HOME}config.properties". - URI configPropertiesLocation = getStoreHome().resolve("config.properties"); - - try { - URLConnection configProperties = configPropertiesLocation.toURL().openConnection(); - - ResourceBundle rsrcs = new PropertyResourceBundle(configProperties.getInputStream()); - - tunables = new NetPeerGroupFactory.NetGroupTunables(rsrcs, tunables); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Loaded defaults from " + rsrcs); - } - } catch (MissingResourceException ignored) { - ; - } catch (IOException ignored) { - ; - } catch (Exception ignored) { - ; - } - } else { - tunables = new NetPeerGroupFactory.NetGroupTunables(netPGID, netPGName - , - (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", netPGDesc)); - } - - npgf = new NetPeerGroupFactory(ppg, tunables.id, tunables.name, tunables.desc); - - PeerGroup newPg = npgf.getInterface(); - - return newPg; - } catch (PeerGroupException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "newNetPeerGroup failed", failed); - } - // rethrow - throw failed; - } catch (RuntimeException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "newNetPeerGroup failed", e); - } - // rethrow - throw e; - } catch (Exception e) { - // should be all other checked exceptions - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "newNetPeerGroup failed", e); - } - // Simplify exception scheme for caller: any sort of problem wrapped - // in a PeerGroupException. - throw new PeerGroupException("newNetPeerGroup failed", e); - } catch (Error e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "newNetPeerGroup failed", e); - } - - // rethrow - throw e; - } - } - - /** - * Instantiates the World Peer Group and then instantiates the Net Peer - * Group. This simplifies the method by which applications can start JXTA. - * - * @return The newly instantiated Net Peer Group. - * @deprecated Consider converting to use {@link NetPeerGroupFactory#NetPeerGroupFactory()} - * or preferably one of the other {@code NetPeerGroupFactory} constructors. - */ - @Deprecated - public static PeerGroup newNetPeerGroup() throws PeerGroupException { - // get/create the World Peer Group. - PeerGroup wpg = getWorldPeerGroup(); - - try { - PeerGroup npg = newNetPeerGroup(wpg); - - return npg; - } finally { - wpg.unref(); - } - } - - /** - * Retrieves or constructs a new World Peer Group instance suitable for - * use as the parent for Net Peer Group instances. This implementation - * makes an important trade-off worth noting; it will use an existing - * world peer group instance if available and ignore any changes which have - * been made to the static configuration methods provided by this class. - * - * @return The World Peer Group. - * @throws PeerGroupException For failures in recovering the World Peer Group. - */ - private static PeerGroup getWorldPeerGroup() throws PeerGroupException { - synchronized (PeerGroup.globalRegistry) { - PeerGroup result = PeerGroup.globalRegistry.lookupInstance(PeerGroupID.worldPeerGroupID); - - if (null != result) { - return result; - } - - return newPlatform(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/PeerGroupID.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/PeerGroupID.java deleted file mode 100644 index 5835fff9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/PeerGroupID.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.peergroup; - - -import java.net.URI; - -import net.jxta.id.ID; -import net.jxta.id.IDFactory; - - -/** - * This class implements a PeerGroup ID. Each peer group is assigned a - * unique id. - * - * @see net.jxta.id.ID - * @see net.jxta.id.IDFactory - * @see net.jxta.peer.PeerID - * - * @since JXTA 1.0 - */ -public abstract class PeerGroupID extends ID { - - /** - * Creates an ID by parsing the given URI. - * - *

      This convenience factory method works as if by invoking the - * {@link net.jxta.id.IDFactory#fromURI(URI)} method; any - * {@link java.net.URISyntaxException} thrown is caught and wrapped in a - * new {@link IllegalArgumentException} object, which is then thrown. - * - *

      This method is provided for use in situations where it is known that - * the given string is a legal ID, for example for ID constants declared - * within in a program, and so it would be considered a programming error - * for the URI not to parse as such. The {@link net.jxta.id.IDFactory}, - * which throws {@link java.net.URISyntaxException} directly, should be used - * situations where a ID is being constructed from user input or from some - * other source that may be prone to errors. - * - * @param fromURI The URI to be parsed into an ID - * @return The new ID - * - * @throws NullPointerException If {@code fromURI} is {@code null}. - * @throws IllegalArgumentException If the given URI is not a valid ID. - */ - public static PeerGroupID create(URI fromURI) { - return (PeerGroupID) ID.create(fromURI); - } - - /** - * {@inheritDoc} - */ - public PeerGroupID intern() { - return (PeerGroupID) super.intern(); - } - - /** - * The well known Unique Identifier of the world peergroup. - * This is a singleton within the scope of a VM. - */ - public final static PeerGroupID worldPeerGroupID = (new WorldPeerGroupID()).intern(); - - /** - * The well known Unique Identifier of the net peergroup. - * This is a singleton within the scope of this VM. - */ - public final static PeerGroupID defaultNetPeerGroupID = (new NetPeerGroupID()).intern(); - - /** - * Returns the parent peer group id of this peer group id, if any. - * - * @return the id of the parent peergroup or null if this group has no - * parent group. - */ - public abstract PeerGroupID getParentPeerGroupID(); -} - - -final class WorldPeerGroupID extends PeerGroupID { - - /** - * The name associated with this ID Format. - */ - final static String JXTAFormat = "jxta"; - - private static final String UNIQUEVALUE = "WorldGroup"; - - /** - * WorldPeerGroupID is not intended to be constructed. You should use the - * {@link PeerGroupID.worldPeerGroupID} constant instead. - */ - WorldPeerGroupID() {} - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - return (this == target); // worldPeerGroupID is only itself. - } - - /** - * deserialization has to point back to the singleton in this VM - */ - private Object readResolve() { - return PeerGroupID.worldPeerGroupID; - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return JXTAFormat; - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + UNIQUEVALUE; - } - - /** - * {@inheritDoc} - */ - @Override - public PeerGroupID getParentPeerGroupID() { - return null; - } -} - - -final class NetPeerGroupID extends PeerGroupID { - - /** - * The name associated with this ID Format. - */ - final static String JXTAFormat = "jxta"; - - private static final String UNIQUEVALUE = "NetGroup"; - - /** - * NetPeerGroupID is not intended to be constructed. You should use the - * {@link PeerGroupID.defaultNetPeerGroupID} constant instead. - */ - NetPeerGroupID() {} - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - return (this == target); // netPeerGroupID is only itself. - } - - /** - * deserialization has to point back to the singleton in this VM - */ - private Object readResolve() { - return PeerGroupID.defaultNetPeerGroupID; - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return JXTAFormat; - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + UNIQUEVALUE; - } - - /** - * {@inheritDoc} - */ - @Override - public PeerGroupID getParentPeerGroupID() { - return PeerGroupID.worldPeerGroupID; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/WorldPeerGroupFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/WorldPeerGroupFactory.java deleted file mode 100644 index a8cac02d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/WorldPeerGroupFactory.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.peergroup; - - -import net.jxta.exception.ConfiguratorException; -import net.jxta.exception.PeerGroupException; -import net.jxta.logging.Logging; -import net.jxta.protocol.ConfigParams; - -import java.io.File; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.net.URI; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.jxta.platform.JxtaLoader; -import net.jxta.protocol.ModuleImplAdvertisement; - - -/** - * A factory for instantiating the World Peer Group. Every peer starts by - * instantiating the World Peer Group and then other Peer Groups are - * instantiated as needed. Most applications do not need to use - * {@code WorldPeerGroupFactory} but should instead prefer using - * {@code NetPeerGroupFactory} whenever possible. - *

      - * The World Peer Group provides the minimum core services needed to find - * and instantiate other Peer Groups on a peer. The World Peer Group is the - * primordial peer group upon which all other peer groups are instantiated. The - * World Peer Group is primarily responsible for management of physical network - * connections, physical network discovery (generally broadcast) and physical - * network topology management. - *

      - * Applications generally do not normally interact directly with the World Peer - * Group. The World Peer Group includes only limited endpoint, resolver, - * discovery and rendezvous services. - *

      - * When the World Peer Group starts it may optionally search - * for The Network Peer Group on the local network and, if found, - * instantiate it. Otherwise a default built-in configuration of The Net - * Peer Group is instantiated. - * - * @since JXTA JSE 2.4 - * - * @see net.jxta.peergroup.PeerGroup - * @see net.jxta.peergroup.NetPeerGroupFactory - */ -public final class WorldPeerGroupFactory { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(WorldPeerGroupFactory.class.getName()); - - /** - * Our strong reference to the World Peer Group. - */ - private final PeerGroup world; - - /** - * Provided for backwards compatibility, this constructor instantiates the - * World Peer Group using the PlatformConfig file found in the directory - * specified by the {@code JXTA_HOME} system property or the "{@code .jxta/}" - * directory if {@code JXTA_HOME} is not defined. - *

      - * Though not deprecated this method should be considered as sample - * code only and the other constructors should be used whenever possible. - * - * @throws PeerGroupException Thrown for problems construction the World - * Peer Group. - */ - public WorldPeerGroupFactory() throws PeerGroupException { - // Establish the default store location via long established hackery. - String jxta_home = System.getProperty("JXTA_HOME", ".jxta/"); - - // ensure that it ends in a seperator. - if (!jxta_home.endsWith(File.separator)) { - jxta_home += File.separator; - } - - File jxta_home_dir = new File(jxta_home); - - // Ensure the homedir exists. - if (!jxta_home_dir.exists()) { - jxta_home_dir.mkdirs(); - } - - URI storeHome = jxta_home_dir.toURI(); - - // Instantiate the default configurator. Do not do this in your own code! - try { - Configurator configurator = new net.jxta.impl.peergroup.DefaultConfigurator(storeHome); - // Get (and possibly generate) the platform configuration. - ConfigParams config = configurator.getConfigParams(); - - world = newWorldPeerGroup(getDefaultWorldPeerGroupClass(), config, storeHome); - - // persist any changes which were made to the platform config by - // service initialization. - configurator.setConfigParams(config); - configurator.save(); - } catch (ConfiguratorException configFailure) { - LOG.severe("Failure while managing World Peer Group configuration"); - - throw new PeerGroupException("Failure while managing World Peer Group configuration", configFailure); - } - } - - /** - * Constructs the World Peer Group using the specified configuration and - * using the specified storeHome location for persistence. - * - * @param config The configuration to use for the World Peer Group. - * @param storeHome The optional location that the World Peer Group and its' - * services should use for storing persistent and transient information. - * May be null if the World Peer Group is not provided a - * persistent store (though this not currently supported). - * @throws PeerGroupException Thrown for problems constructing the World - * Peer Group. - */ - public WorldPeerGroupFactory(ConfigParams config, URI storeHome) throws PeerGroupException { - - world = newWorldPeerGroup(getDefaultWorldPeerGroupClass(), config, storeHome); - } - - /** - * Constructs the World Peer Group using the specified configuration and - * using the specified storeHome location for persistence. - * - * @param worldPeerGroupClass The class which will be instantiated for the - * World Peer Group instance. - * @param config The configuration to use for the World Peer Group. - * @param storeHome The optional location that the World Peer Group and its' - * services should use for storing persistent and transient information. - * May be null if the World Peer Group is not provided a - * persistent store (though this not currently supported). - * @throws PeerGroupException Thrown for problems constructing the World - * Peer Group. - */ - public WorldPeerGroupFactory(Class worldPeerGroupClass, ConfigParams config, URI storeHome) throws PeerGroupException { - - world = newWorldPeerGroup(worldPeerGroupClass, config, storeHome); - } - - /** - * Returns a strong (reference counted) interface object for the World Peer - * Group. This reference should be explicitly unreferenced when it is no - * longer needed. - * - * @return A strong (reference counted) interface object for the World Peer - * Group. - * @see PeerGroup#unref() - */ - public PeerGroup getInterface() { - return (PeerGroup) world.getInterface(); - } - - /** - * Returns a weak (non-reference counted) interface object for the World - * Peer Group. - * - * @return A weak (non-reference counted) interface object for the World - * Peer Group. - * @see PeerGroup#getWeakInterface() - */ - public PeerGroup getWeakInterface() { - return world.getWeakInterface(); - } - - /** - * Determine the class to use for the World PeeerGroup. - * - * @return The Class which has been configured to be used for - * World Peer Group instances. - * @throws PeerGroupException Thrown for problems determining the class to - * be used for the World Peer Group. - */ - private static Class getDefaultWorldPeerGroupClass() throws PeerGroupException { - - try { - // XXX 20070713 bondolo Temporary hack to resolve class load order issue. StdPeerGroup is responsible for initializing standard modules. - String unused = net.jxta.impl.peergroup.StdPeerGroup.STD_COMPAT.toString(); - - JxtaLoader loader = net.jxta.impl.peergroup.GenericPeerGroup.getJxtaLoader(); - - ModuleImplAdvertisement worldGroupImplAdv = loader.findModuleImplAdvertisement(PeerGroup.refPlatformSpecID); - - if(null == worldGroupImplAdv) { - throw new PeerGroupException("Could not locate World PeerGroup Module Implementation."); - } - - return Class.forName(worldGroupImplAdv.getCode()); - } catch (RuntimeException failed) { - throw new PeerGroupException("Could not load World PeerGroup class.", failed); - } catch (ClassNotFoundException failed) { - throw new PeerGroupException("Could not load World PeerGroup class.", failed); - } - } - - /** - * Constructs the World Peer Group instance. - * - * @param worldPeerGroupClass The class which will be instantiated for the - * World Peer Group instance. - * @param config The configuration to use for the World Peer Group. - * @param storeHome The optional location the World Peer Group and its' - * services may use for storing persistent and transient information. - * May be {@code null} if the World Peer Group is not provided a - * persistent store (though this not currently supported). - * @throws PeerGroupException Thrown for problems constructing the World - * Peer Group. - * @return the WorldPeerGroup - */ - private PeerGroup newWorldPeerGroup(Class worldPeerGroupClass, ConfigParams config, URI storeHome) throws PeerGroupException { - if (!storeHome.isAbsolute()) { - LOG.severe("storeHome must be an absolute URI."); - throw new PeerGroupException("storeHome must be an absolute URI."); - } - - if (storeHome.isOpaque()) { - LOG.severe("Opaque storeHome is not currently supported."); - throw new PeerGroupException("Opaque storeHome is not currently supported."); - } - - synchronized (PeerGroup.globalRegistry) { - if (PeerGroup.globalRegistry.registeredInstance(PeerGroupID.worldPeerGroupID)) { - throw new PeerGroupException( "Only a single instance of the World Peer Group may be instantiated at a single time."); - } - - PeerGroup result = null; - - try { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Making a new World Peer Group instance using : " + worldPeerGroupClass.getName()); - } - - Constructor twoParams = (Constructor) worldPeerGroupClass.getConstructor(ConfigParams.class,URI.class); - - try { - result = twoParams.newInstance(config, storeHome); - } catch (InvocationTargetException failure) { - // unwrap the real exception. - Throwable cause = failure.getCause(); - - if (cause instanceof Exception) { - throw (Exception) cause; - } else if (cause instanceof Error) { - throw (Error) cause; - } else { - // just rethrow what we already had. sigh. - throw failure; - } - } - - result.init(null, PeerGroupID.worldPeerGroupID, null); - - return result; - } catch (RuntimeException e) { - // should be all other checked exceptions - LOG.log(Level.SEVERE, "World Peer Group could not be instantiated.", e); - - // cleanup broken instance - if (null != result) { - result.unref(); - } - - // just rethrow. - throw e; - } catch (Exception e) { - // should be all other checked exceptions - LOG.log(Level.SEVERE, "World Peer Group could not be instantiated.", e); - - // cleanup broken instance - if (null != result) { - result.unref(); - } - - // Simplify exception scheme for caller: any sort of problem wrapped - // in a PeerGroupException. - throw new PeerGroupException("World Peer Group could not be instantiated.", e); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/package.html deleted file mode 100644 index 155ccd1f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/peergroup/package.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - Peer groups are formed as a collection of peers that have agreed upon a - common set of services. The {@link net.jxta.peergroup.PeerGroup} interface presents the - API of those services and encapsulates the group's identity and the local - peer's identity in that group. - -

      A group is instantiated on a peer by instantiating the group class - specified by the group definition and initializing the resulting object - with the parameters specified by the group definition. - -

      A group may be, and often is, defined and instantiated within the - context of another group referred to as its parent group. In that case an - appropriate and initialized {@link net.jxta.peergroup.PeerGroup} object, - that represents that group may be obtained from the parent group by using - one of the parent's {@link net.jxta.peergroup.PeerGroup#newGroup newGroup} - methods. - -

      All peers start with instantiating one well known root group - (which has no parent) known as the World Peer Group. It is created - by calling {@link net.jxta.peergroup.PeerGroupFactory#newPlatform()}. - -

      The World Peer Group has a limited set of functionality. Most - peers chose to instantiate early on another well known group known as the - Net Peer Group and to use it as the root of the other groups they - create. - -

      An object representing the Net Peer Group may be obtained from - the {@link net.jxta.peergroup.PeerGroupFactory} by invoking the method - {@link net.jxta.peergroup.PeerGroupFactory#newNetPeerGroup()}. This method - invokes {@link net.jxta.peergroup.PeerGroupFactory#newPlatform()} - automatically, so if an application wants to use the Net Peer Group - as its root group, invoking - {@link net.jxta.peergroup.PeerGroupFactory#newNetPeerGroup()} is all that is - required. - -

      All other groups should be created or instantiated within the context of - already instantiated groups by using one of the - {@link net.jxta.peergroup.PeerGroup#newGroup newGroup} methods. - -

      It is possible to change the identity, name, and description of the - group that {@link net.jxta.peergroup.PeerGroupFactory#newNetPeerGroup()} - instantiates by setting the following properties in the file - config.properties (all three must be specified for the setting - to take effect): -

        -
      • NetPeerGroupID
      • -
      • NetPeerGroupName
      • -
      • NetPeerGroupDesc
      • -
      - The same result may be obtained by invoking the following - {@link net.jxta.peergroup.PeerGroupFactory} static methods: -
        -
      • {@link net.jxta.peergroup.PeerGroupFactory#setNetPGID}
      • -
      • {@link net.jxta.peergroup.PeerGroupFactory#setNetPGName}
      • -
      • {@link net.jxta.peergroup.PeerGroupFactory#setNetPGDesc}
      • -
      - -

      It is also possible to create arbitrary subgroups of the World Peer - Group programatically by first starting the World Peer Group - and applying one of the - {@link net.jxta.peergroup.PeerGroup#newGroup newGroup} methods of the - resulting PeerGroup object. An example of creating multiple - infrastructure peer groups. - {@link Dual Infrastructure Group Tutorial} - - - @see net.jxta.peergroup.PeerGroup - @see net.jxta.peergroup.PeerGroupFactory - @see net.jxta.protocol.PeerGroupAdvertisement - @see net.jxta.protocol.PeerAdvertisement - @see net.jxta.id.ID - @see JXTA Protocols Specification : Peer Groups - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/InputPipe.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/InputPipe.java deleted file mode 100644 index 2e20ff4c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/InputPipe.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.pipe; - - -import net.jxta.id.ID; -import net.jxta.endpoint.Message; -import net.jxta.protocol.PipeAdvertisement; - - -/** - * InputPipe defines the interface for receiving messages from a - * {@link net.jxta.pipe.PipeService}. - * - *

      An application that wants to receive messages from a Pipe will create - * an input pipe. - * - *

      An InputPipe is created and returned by the - * {@link net.jxta.pipe.PipeService} - * - * @see net.jxta.pipe.PipeService - * @see net.jxta.pipe.OutputPipe - * @see net.jxta.endpoint.Message - * @see net.jxta.endpoint.MessageElement - * @see net.jxta.protocol.PipeAdvertisement - */ -public interface InputPipe { - - /** - * Wait (block) for a message to be received. - * - * @return a message or null if the pipe has been closed. - * @exception InterruptedException If another thread interrupted while we - * were waiting for a message. - */ - public Message waitForMessage() throws InterruptedException; - - /** - * Poll for a message from the pipe. If there is no message immediately - * available then wait the specified amount of time for a message to arrive. - * - * @param timeout Maximum number of milliseconds to wait (block) for a - * message to be received. If zero then wait indefinitely for a message. - * @return Message received or null if the pipe has closed or the timeout - * expired without a message being received. - * @throws InterruptedException If another thread interrupted while we - * were waiting for a message. - */ - public Message poll(int timeout) throws InterruptedException; - - /** - * Close the pipe. No additional messages will be received on this pipe. - */ - public void close(); - - /** - * Gets the pipe type - * - * @return The type - */ - public String getType(); - - /** - * Gets the pipe id - * - * @return The type - */ - public ID getPipeID(); - - /** - * Gets the pipe name - * - * @return The name - */ - public String getName(); - - /** - * Gets the pipe advertisement - * - * @return The advertisement - */ - public PipeAdvertisement getAdvertisement(); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/OutputPipe.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/OutputPipe.java deleted file mode 100644 index 6a8b25f5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/OutputPipe.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.pipe; - - -import java.io.IOException; - -import net.jxta.endpoint.Message; -import net.jxta.id.ID; -import net.jxta.protocol.PipeAdvertisement; - - -/** - * OuputPipe defines the interface for sending messages from a - * {@link net.jxta.pipe.PipeService}. - * - *

      Application that want to send messages onto a Pipe must fist get - * an {@link net.jxta.pipe.OutputPipe} from the {@link net.jxta.pipe.PipeService}. - * - * @see net.jxta.pipe.PipeService - * @see net.jxta.pipe.InputPipe - * @see net.jxta.endpoint.Message - * @see net.jxta.protocol.PipeAdvertisement - */ - -public interface OutputPipe { - - /** - * Send a message through the pipe - * - *

      WARNING: The message object used when sending a pipe message - * should not be reused or modified after the {@link #send(Message)} call is - * made. Concurrent modification of messages will produce unexpected result. - * - * @param msg is the PipeMessage to be sent. - * @return boolean true if the message has been sent otherwise - * false. false. is commonly returned for - * non-error related congestion, meaning that you should be able to send - * the message after waiting some amount of time. - * @exception IOException output pipe error - * - */ - public boolean send(Message msg) throws IOException; - - /** - * close the pipe - * - */ - public void close(); - - /** - * Returns true if this pipe is closed and no longer - * accepting messages to be sent. The pipe should be discarded. - * - * @return true if this pipe is closed, otherwise - * false. - */ - boolean isClosed(); - - /** - * Gets the pipe type - * - * @return The type - */ - public String getType(); - - /** - * Gets the pipe id - * - * @return The type - */ - public ID getPipeID(); - - /** - * Gets the pipe name - * - * @return The name - */ - public String getName(); - - /** - * Gets the pipe advertisement - * - * @return The advertisement - */ - public PipeAdvertisement getAdvertisement(); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/OutputPipeEvent.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/OutputPipeEvent.java deleted file mode 100644 index 7c5c1cd0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/OutputPipeEvent.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2001-2006 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.pipe; - - -import java.util.EventObject; - - -/** - * Container for OutputPipeEvent events. - */ -public class OutputPipeEvent extends EventObject { - - private OutputPipe outputpipe; - - private String pipeID; - - private int queryID; - - /** - * Creates a new event - * - * @param source The PipeService which created this event. - * @param outputpipe the outputpipe object - * @param pipeID URI containing the Pipe unique identifier. - * @param queryID The query id associated with the response returned in this event - */ - public OutputPipeEvent(Object source, OutputPipe outputpipe, String pipeID, int queryID) { - - super(source); - - this.outputpipe = outputpipe; - this.pipeID = pipeID; - this.queryID = queryID; - } - - /** - * Returns the output associated with the event - * - * @return OutPutPipe - */ - public OutputPipe getOutputPipe() { - return outputpipe; - } - - /** - * Returns The pipe id associated with this output pipe event - * - * @return pipe id associated with this output pipe event - */ - public String getPipeID() { - return pipeID; - } - - /** - * Returns The query id associated with the response returned in this event - * - * @return query id associated with the response - */ - public int getQueryID() { - return queryID; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/OutputPipeListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/OutputPipeListener.java deleted file mode 100644 index a5705c1c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/OutputPipeListener.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.pipe; - - -import java.util.EventListener; - - -/** - * The listener interface for receiving {@link net.jxta.pipe.OutputPipe} - * resolution events. - * - * The following example illustrates how to implement a - * {@link net.jxta.pipe.OutputPipeListener}: - * - *

      - *     public class MyService implements OutputPipeListener {
      - *        ..
      - *        ..
      - *        pipe.createOutputPipe(pipeAdv, this);
      - *        ..
      - *        ..
      - *        public void outputPipeEvent(OutputPipeEvent event) {
      - *
      - *        OutputPipe op = event.getOutputPipe();
      - *        }
      - *    }
      - * 
      - */ -public interface OutputPipeListener extends EventListener { - - /** - * Called when a input pipe has been located for a previously registered - * pipe. The event contains an {@link net.jxta.pipe.OutputPipe} which can - * be used to communicate with the remote peer. - * - * @param event the event - */ - void outputPipeEvent(OutputPipeEvent event); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeID.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeID.java deleted file mode 100644 index 579249f0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeID.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.pipe; - - -import java.net.URI; -import net.jxta.id.ID; - - -/** - * This class implements a Pipe ID. Each pipe is assigned a unique id. - * - * @see net.jxta.id.ID - * @see net.jxta.id.IDFactory - * @see net.jxta.peergroup.PeerGroupID - * @see net.jxta.pipe.PipeService - * @see net.jxta.protocol.PipeAdvertisement - */ -public abstract class PipeID extends ID { - - /** - * Creates an ID by parsing the given URI. - * - *

      This convenience factory method works as if by invoking the - * {@link net.jxta.id.IDFactory#fromURI(URI)} method; any - * {@link java.net.URISyntaxException} thrown is caught and wrapped in a - * new {@link IllegalArgumentException} object, which is then thrown. - * - *

      This method is provided for use in situations where it is known that - * the given string is a legal ID, for example for ID constants declared - * within in a program, and so it would be considered a programming error - * for the URI not to parse as such. The {@link net.jxta.id.IDFactory}, - * which throws {@link java.net.URISyntaxException} directly, should be used - * situations where a ID is being constructed from user input or from some - * other source that may be prone to errors. - * - * @param fromURI The URI to be parsed into an ID - * @return The new ID - * - * @throws NullPointerException If {@code fromURI} is {@code null}. - * @throws IllegalArgumentException If the given URI is not a valid ID. - */ - public static PipeID create(URI fromURI) { - return (PipeID) ID.create(fromURI); - } - - /** - * {@inheritDoc} - */ - public PipeID intern() { - return (PipeID) super.intern(); - } - - /** - * Returns PeerGroupID of the Peer Group to which this Pipe ID belongs. - * - * @return The PeerGroupID of the Peer Group to which this Pipe ID belongs. - */ - public abstract ID getPeerGroupID(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeMsgEvent.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeMsgEvent.java deleted file mode 100644 index 67eba550..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeMsgEvent.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.pipe; - - -import java.util.EventObject; -import net.jxta.endpoint.Message; - - -/** - * Container for Pipe Message events. - */ -public class PipeMsgEvent extends EventObject { - - /** - * The received Message - */ - private final Message message; - - /** - * Pipe ID of the pipe on which the message was received. - */ - private final PipeID pipeID; - - /** - * Creates a new event - * - * @param source The PipeObject on which the message was received. - * @param message the message object - * @param pipeID the pipe id of the pipe on which the message was received. - */ - public PipeMsgEvent(Object source, Message message, PipeID pipeID) { - super(source); - - this.message = message; - - this.pipeID = pipeID; - } - - /** - * Returns the message associated with the event - * - * @return message - */ - public Message getMessage() { - return message; - } - - /** - * Returns the pipeID associated with the event - * - * @return pipeID - */ - public PipeID getPipeID() { - return pipeID; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeMsgListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeMsgListener.java deleted file mode 100644 index 90b157e8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeMsgListener.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.pipe; - - -import java.util.EventListener; - - -/** - * The listener interface for receiving {@link net.jxta.pipe.PipeMsgEvent} - * events. - * - * The following example illustrates how to implement a {@link net.jxta.pipe.PipeMsgListener}: - *

      
      - * PipeMsgListener myListener = new PipeMsgListener() {
      - *
      - *   public void pipeMsgEvent(PipeMsgEvent event) {
      - *     Message msg=null;
      - *     try {
      - *       msg = event.getMessage();
      - *     } catch (Exception e) {
      - *       e.printStackTrace();
      - *       return;
      - *     }
      - *   }
      - * }
      - *
      - * InputPipe pipeIn = pipe.createInputPipe(pipeAdv, myListener);
      - * *
      - */ -public interface PipeMsgListener extends EventListener { - - /** - * Called for each pipe message event that occurs. - * - * @param event The event being received. - */ - void pipeMsgEvent(PipeMsgEvent event); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeService.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeService.java deleted file mode 100644 index e4e1518c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/PipeService.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (c) 2001-2006 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.pipe; - - -import java.io.IOException; -import java.util.Set; - -import net.jxta.id.ID; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.service.Service; - - -/** - * Pipes are the core mechanism for exchanging messages between JXTA - * applications or services. - * - *

      Pipes are uniquely identified by a - * {@link net.jxta.protocol.PipeAdvertisement} which is associated with each - * pipe. - * - *

      Several types of Pipe can currently be used: - * - *

        - *
      • JxtaUnicast - unicast, unreliable and unsecured pipe - *
      • JxtaUnicastSecure - unicast and secure pipe - *
      • JxtaPropagate - propagated, unreliable and unsecured pipe - *
      - * - *

      The type of a Pipe is defined when creating its - * {@link net.jxta.protocol.PipeAdvertisement}. - * - * @see net.jxta.protocol.PipeAdvertisement - * @see net.jxta.pipe.InputPipe - * @see net.jxta.pipe.OutputPipe - * @see net.jxta.endpoint.Message - * @see JXTA Protocols Specification : Pipes - * @see JXTA Protocols Specification : Pipe Binding Protocol - */ -public interface PipeService extends Service { - - /** - * Unicast, unreliable and unsecured type of Pipe - */ - public final static String UnicastType = "JxtaUnicast"; - - /** - * Propagated, unsecured and unreliable type of Pipe - */ - public final static String PropagateType = "JxtaPropagate"; - - /** - * End-to-end secured unicast pipe of Pipe - */ - public final static String UnicastSecureType = "JxtaUnicastSecure"; - - /** - * Create an InputPipe from a pipe Advertisement - * - * @param adv The advertisement of the Pipe. - * @return The InputPipe created. - * @throws IOException error creating input pipe - */ - public InputPipe createInputPipe(PipeAdvertisement adv) throws IOException; - - /** - * Create an InputPipe from a pipe Advertisement - * - * @param adv is the advertisement of the Pipe. - * @param listener PipeMsgListener to receive msgs. - * @return InputPipe The InputPipe created. - * @throws IOException Error creating input pipe - */ - public InputPipe createInputPipe(PipeAdvertisement adv, PipeMsgListener listener) throws IOException; - - /** - * Attempt to create an OutputPipe using the specified Pipe Advertisement. - * The pipe will be be resolved within the provided timeout. - * - * @param pipeAdv The advertisement of the pipe being resolved. - * @param timeout Time duration in milliseconds to wait for a successful - * pipe resolution. 0 will wait indefinitely. - * @return OutputPipe the successfully resolved OutputPipe. - * @throws IOException If the pipe cannot be created or failed to resolve - * within the specified time. - */ - public OutputPipe createOutputPipe(PipeAdvertisement pipeAdv, long timeout) throws IOException; - - /** - * Attempt to create an OutputPipe using the specified Pipe Advertisement. - * The pipe will be be resolved to one of the peers in the set of peer ids - * provided within the provided timeout. - * - * @param pipeAdv The advertisement of the pipe being resolved. - * @param resolvablePeers The peers on which the pipe may be resolved. - * If the Set is empty then the pipe may be resolved to any - * destination peer. - * @param timeout Time duration in milliseconds to wait for a successful - * pipe resolution. 0 will wait indefinitely. - * @return The successfully resolved OutputPipe. - * @throws IOException If the pipe cannot be created or failed to resolve - * within the specified time. - */ - public OutputPipe createOutputPipe(PipeAdvertisement pipeAdv, Set resolvablePeers, long timeout) throws IOException; - - /** - * Attempt to create an OutputPipe using the specified Pipe Advertisement. - * The pipe may be resolved to any destination peer. When the pipe is - * resolved the listener will be called. - * - * @param pipeAdv The advertisement of the pipe being resolved. - * @param listener The listener to be called when the pipe is resolved. - * @throws IOException If the pipe cannot be created. - */ - public void createOutputPipe(PipeAdvertisement pipeAdv, OutputPipeListener listener) throws IOException; - - /** - * Attempt to create an OutputPipe using the specified Pipe Advertisement. - * When the pipe is resolved to one of the peers in the set of peer ids - * provided the listener will be called. - * - * @param pipeAdv The advertisement of the pipe being resolved. - * @param resolvablePeers The set of peers on which the pipe may be resolved. - * If the Set is empty then the pipe may be resolved to any - * destination peer. - * @param listener the listener to be called when the pipe is resolved. - * @throws IOException If the pipe cannot be created. - */ - public void createOutputPipe(PipeAdvertisement pipeAdv, Set resolvablePeers, OutputPipeListener listener) throws IOException; - - /** - * Remove an OutputPipeListener previously registered with - * createOuputputPipe. - * - * @deprecated This method is being replaced by {@link #removeOutputPipeListener(ID,OutputPipeListener)}. - * - * @param pipeID The pipe who's listener is to be removed. - * @param listener The listener to remove. - * @return The listener which was removed or null if the key did not have a mapping. - */ - @Deprecated - public OutputPipeListener removeOutputPipeListener(String pipeID, OutputPipeListener listener); - - /** - * Remove an OutputPipeListener previously registered with - * createOuputputPipe. - * - * @param pipeID The pipe who's listener is to be removed. - * @param listener The listener to remove. - * @return The listener which was removed or null if the key did not have a mapping. - */ - public OutputPipeListener removeOutputPipeListener(ID pipeID, OutputPipeListener listener); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/package.html deleted file mode 100644 index 6c508fb4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/pipe/package.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - Pipes are the core mechanism for exchanging messages between JXTA - applications or services. - - @see net.jxta.protocol.PipeAdvertisement - @see net.jxta.pipe.PipeService - @see JXTA Protocols Specification : Pipes - @see JXTA Protocols Specification : Pipe Binding Protocol - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/Application.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/Application.java deleted file mode 100644 index 17d3ae2c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/Application.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.platform; - - -/** - * This interface defines a JXTA peer group application. - * That is a class of Module suitable for loading as the main application - * of a group, or which may be loaded by a group while not being a service. - * - * For now, it is a plain Module. - */ - -public interface Application extends Module {} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/JxtaLoader.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/JxtaLoader.java deleted file mode 100644 index 5d037956..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/JxtaLoader.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.platform; - - -import java.net.URL; -import java.net.URLClassLoader; - -import net.jxta.protocol.ModuleImplAdvertisement; - - -/** - * A ClassLoader which provides additional JXTA functionality. You can load - * classes by ModuleSpecID. Classes are defined with ModuleImplAdvertisements - * and class loading will determine suitability using the provided - * compatibility statements. - */ -public abstract class JxtaLoader extends URLClassLoader { - - /** - * Construct a new loader with the specified parent loader and - * - * @param parent the parent class loader for delegation. - */ - public JxtaLoader(ClassLoader parent) { - this(new URL[0], parent); - } - - /** - * Construct a new loader for the specified URLS with the specified parent - * loader. - * - * @param urls the URLs from which to load classes and resources. - * @param parent the parent class loader for delegation. - */ - public JxtaLoader(URL[] urls, ClassLoader parent) { - super(urls, parent); - } - - /** - * {@inheritDoc} - */ - @Override - public void addURL(URL url) { - super.addURL(url); - } - - /** - * Finds and loads the class with the specified spec ID from the URL search - * path. Any URLs referring to JAR files are loaded and opened as needed - * until the class is found. - * - * @param spec the specid of the class to load. - * @throws ClassNotFoundException if the class could not be found. - * @return the resulting class. - */ - public abstract Class findClass(ModuleSpecID spec) throws ClassNotFoundException; - - /** - * Loads the class with the specified spec ID from the URL search - * path. - * - * @param spec the specid of the class to load. - * @throws ClassNotFoundException if the class could not be found. - * @return the resulting class. - */ - public abstract Class loadClass(ModuleSpecID spec) throws ClassNotFoundException; - - /** - * Defines a new class from a Module Impl Advertisement. - * - * @param impl The moduleImplAdvertisement containing the class - * specification - * @return The Class object that was created from the specified class data. - */ - public abstract Class defineClass(ModuleImplAdvertisement impl); - - /** - * Finds the ModuleImplAdvertisement for the associated class in the - * context of this ClassLoader. - * - * @param clazz The class who's ModuleImplAdvertisement is desired. - * @return The matching {@code ModuleImplAdvertisement} otherwise - * {@code null} if there is no known association. - */ - public abstract ModuleImplAdvertisement findModuleImplAdvertisement(Class clazz); - - /** - * Finds the ModuleImplAdvertisement for the associated class in the - * context of this ClassLoader. - * - * @param msid The module spec id who's ModuleImplAdvertisement is desired. - * @return The matching {@code ModuleImplAdvertisement} otherwise - * {@code null} if there is no known association. - */ - public abstract ModuleImplAdvertisement findModuleImplAdvertisement(ModuleSpecID msid); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/Module.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/Module.java deleted file mode 100644 index 67ffaaff..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/Module.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.platform; - - -import net.jxta.peergroup.PeerGroup; -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.exception.PeerGroupException; - - -/** - * Defines the interface for modules loaded by PeerGroups. Message transports, - * services and applications need to implement this interface if they are - * to be loaded and started by a PeerGroup. Service and Application extend - * Module, PeerGroup implements Service and ShellApp implements Application, as - * a result both implement Module. - * - *

      Jxta Modules are given their initialization parameters via the init() - * method rather than a non-default constructor. - * - *

      Modules are passed the peer group within which they are created. - * From the peergroup object, Modules can access all the peer group - * services. The PeerGroup within which a PeerGroup runs is known as its - * parent. - * - *

      The initial root peer group is known as the World Peer Group and is - * implemented by an object of class Platform, a subclass of PeerGroup. - * The "parent" PeerGroup of the World Peer Group is null. - * - * @see net.jxta.protocol.ModuleImplAdvertisement - * @see net.jxta.platform.ModuleClassID - * @see net.jxta.peergroup.PeerGroup - * @see net.jxta.document.Advertisement - * @see net.jxta.id.ID - * @see net.jxta.platform.Application - * @see net.jxta.service.Service - **/ -public interface Module { - - /** - * startApp() completed successfully. This module claims to now - * be fully functional and no further invocation of startApp is required. - **/ - public static final int START_OK = 0; - - /** - * This is to be used mostly by co-dependent services when started as - * a set (such as {@link PeerGroup} services) so that their - * startApp() method may be invoked multiple times. - * - *

      This value indicates that startApp must be retried later in order for - * this module to become fully functional. However, some progress in - * functionality was accomplished. - * - *

      This is a strong indication that some other modules may be able - * to advance or complete their initialization if their - * startApp() method is invoked again. - * - *

      The distinction between START_AGAIN_STALLED and START_AGAIN_PROGRESS - * is only a hint. Each module makes an arbitrary judgment in this - * respect. It is up to the invoker of startApp to ensure that the - * starting of a set of modules eventually succeeds or fails. - **/ - public static final int START_AGAIN_PROGRESS = 1; - - /** - * This is to be used mostly by co-dependent services when started as - * a set (such as {@link PeerGroup} services) so that their startApp - * method may be invoked multiple times. - * - *

      This value indicates that startApp must be retried later in order for - * this module to become fully functional. However, some progress in - * functionality was accomplished. - * - *

      If all modules in a set return this value, it is a strong indication - * that the modules co-dependency is such that it prevents them - * collectively from starting. - * - *

      The distinction between START_AGAIN_STALLED and START_AGAIN_PROGRESS - * is only a hint. Each module makes an arbitrary judgment in this - * respect. It is up to the invoker of startApp to ensure that the - * starting of a set of modules eventually succeeds or fails. - **/ - public static final int START_AGAIN_STALLED = 2; - - /** - * This return result is used to indicate that the module refuses to start - * because it has been configured to be disabled or otherwise cannot run - * (missing hardware, missing system resources, etc.) The module will not be - * functional and should be discarded but the failure to load may be ignored - * by the loader at it's discretion. - */ - public static final int START_DISABLED = Integer.MIN_VALUE + 100; - - /** - * Initialize the module, passing it its peer group and advertisement. - * - *

      Note: when subclassing one of the existing PeerGroup implementations - * (which implement Module), it may not be recommended to overload the init - * method. See the documentation of the PeerGroup class being subclassed. - * - * @param group The PeerGroup from which this Module can obtain services. - * If this module is a Service, this is also the PeerGroup of which this - * module is a service. - * - * @param assignedID Identity of Module within group. - * modules can use it as a the root of their namespace to create - * names that are unique within the group but predictable by the - * same module on another peer. This is normally the ModuleClassID - * which is also the name under which the module is known by other - * modules. For a group it is the PeerGroupID itself. - * The parameters of a service, in the Peer configuration, are indexed - * by the assignedID of that service, and a Service must publish its - * run-time parameters in the Peer Advertisement under its assigned ID. - * - * @param implAdv The implementation advertisement for this - * Module. It is permissible to pass null if no implementation - * advertisement is available. This may happen if the - * implementation was selected by explicit class name rather than - * by following an implementation advertisement. Modules are not - * required to support that style of loading, but if they do, then - * their documentation should mention it. - * - * @exception PeerGroupException This module failed to initialize. - **/ - public void init(PeerGroup group, ID assignedID, Advertisement implAdv) throws PeerGroupException; - - /** - * Complete any remaining initialization of the module. The module should - * be fully functional after startApp() is completed. That is - * also the opportunity to supply arbitrary arguments (mostly to - * applications). - * - *

      If this module is a {@link PeerGroup} service, it may be invoked - * several times depending on its return value. - * - * @param args An array of Strings forming the parameters for this - * Module. - * - * @return int A status indication which may be one of - * {@link #START_OK}, {@link #START_AGAIN_PROGRESS}, - * {@link #START_AGAIN_STALLED}, which indicates partial or complete - * success, or any other value (negative values are - * recommended for future compatibility), which indicates failure. - **/ - public int startApp(String[] args); - - /** - * Stop a module. This may be called any time after init() - * completes and should not assume that startApp() has been - * called or completed. - * - *

      The Module cannot be forced to comply, but in the future - * we might be able to deny it access to anything after some timeout. - **/ - public void stopApp(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/ModuleClassID.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/ModuleClassID.java deleted file mode 100644 index 97d3503d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/ModuleClassID.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.platform; - - -import java.net.URI; -import net.jxta.id.ID; - - -/** - * A ModuleClassID uniquely identifies a particular local behaviour, that is, - * a specific API for each execution environment for which an implementation - * exists. - * - *

      A ModuleClassID has two components: A base class identifier, and a role identifier. - * The role identifier may be zero. By convention the API uses the ModuleClassID with - * a zero role identifier to designate the base class in contexts where only the base class - * is significant. Nonetheless, a ModuleClassID with a zero role identifier is a valid - * ModulesClassID wherever a full ModuleClassID is expected. In many cases, only one role - * in a given class is ever used. Using role zero in such cases is an optimization because - * it may make the string representation of the ModuleClassID shorter. - * - *

      Each service of a group, that is, the role it plays in the group, is uniquely identified - * per the group definition. - * This identifier may be used by other modules in the group to designate this one, or by the service - * itself to identify its parameters in a PeerAdvertisement. In addition, by combining its - * PeerGroupID with its own ModuleClassID, a service may create a predictible identifier unique - * on their peer, suitable for registering listeners with the EndpointService or other services - * with similar listener interfaces. - * - *

      The standard PeerGroup implementation of the java reference implementation - * assigns to each service its ModuleClassID as its unique service identifier. Most of the - * times this ModuleClassID is a base classID, but groups that use the same Module Class - * for more than one service (same behaviour but playing a different role in the group, such - * as, for example, a data base engine with a different data base), may define multiple roles - * identified by the same base class identifier but different role identifiers. The standard - * PeerGroup implementation of the java reference implementation has the notion of main - * application: a default application which may be started automatically upon instantiating - * the group. This application implements Module and, therefore, is assigned a ModuleClassID. - * However applications are not expected to play any specific role in the group. As a result, they - * are assigned a role identifier allocated at run-time as need to garantee local unicity. As - * a result main applications cannot expect a predictible ClassID. - * - *

      A ModuleClassID is optionaly described by a published ModuleClassAdvertisement. - * - *

      There may be any number of embodiements of a module class. These are module - * specifications. A module specification represent the network behaviour of a - * module while its class represents its local behaviour. Different groups - * may use a common subset of classes, for example, the basic set defined by the platform - * should always be part of it. Each group may use different and network-incompatible - * specifications for common classes, optimized for various purposes. The local API of a - * given class on a given JXTA implementation will be invariant per the spec being used. - * Therefore, the difference will be transparent to applications which do not depend - * on the possibly different quality of service. - * - *

      A ModuleSpecID embeds a base class identifier, which permits to verify that - * a given Module specification is suitable for its intended use. - * - * @see net.jxta.peergroup.PeerGroup - * @see net.jxta.platform.Module - * @see net.jxta.platform.ModuleClassID - * @see net.jxta.protocol.PeerAdvertisement - * @see net.jxta.protocol.ModuleSpecAdvertisement - * @see net.jxta.protocol.ModuleClassAdvertisement - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.id.ID - * - */ -public abstract class ModuleClassID extends ID { - - /** - * Creates an ID by parsing the given URI. - * - *

      This convenience factory method works as if by invoking the - * {@link net.jxta.id.IDFactory#fromURI(URI)} method; any - * {@link java.net.URISyntaxException} thrown is caught and wrapped in a - * new {@link IllegalArgumentException} object, which is then thrown. - * - *

      This method is provided for use in situations where it is known that - * the given string is a legal ID, for example for ID constants declared - * within in a program, and so it would be considered a programming error - * for the URI not to parse as such. The {@link net.jxta.id.IDFactory}, - * which throws {@link java.net.URISyntaxException} directly, should be used - * situations where a ID is being constructed from user input or from some - * other source that may be prone to errors. - * - * @param fromURI The URI to be parsed into an ID - * @return The new ID - * - * @throws NullPointerException If {@code fromURI} is {@code null}. - * @throws IllegalArgumentException If the given URI is not a valid ID. - */ - public static ModuleClassID create(URI fromURI) { - return (ModuleClassID) ID.create(fromURI); - } - - /** - * {@inheritDoc} - */ - public ModuleClassID intern() { - return (ModuleClassID) super.intern(); - } - - /** - * Returns true if this ModuleClassID is of the same base class than the - * given class. - * Note: This method is NOT named "isOfClass" because a ModuleClassID - * may have two UUID; one that denotes a "base" class proper, - * and an optional second one that denotes a "Role", or subclass. - * Compatibility between ClassIDs is based on the "base" portion, hence the - * "isOfSame" naming. This routine can be used for comparison with a base class - * since a base class is just a class which role portion happens to be zero. - * - * @param id Module class id to compare with - * @return boolean true if equals - */ - - public abstract boolean isOfSameBaseClass(ModuleClassID id); - - /** - * Returns true if this ModuleClassID is of the same class than the - * the given ModuleSpecID. - * - * @param id Module spec id to compare with - * @return boolean true if equals - */ - - public abstract boolean isOfSameBaseClass(ModuleSpecID id); - - /** - * Return a ModuleClassID of the same base class but with the role portion - * set to zero. aka "the base class". - * - * @return ModuleClassID the base class. - */ - public abstract ModuleClassID getBaseClass(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/ModuleSpecID.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/ModuleSpecID.java deleted file mode 100644 index bfca6558..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/ModuleSpecID.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.platform; - - -import java.net.URI; -import net.jxta.id.ID; - - -/** - * A ModuleSpecID uniquely identifies a particular network behaviour - * (wire protocol and choregraphy) that may be embodied by a Jxta Module. - * There may be any number of implementations of a given SpecID. All - * such implementations are assumed to be network compatible. - * - *

      - * The Specification that corresponds to a given ModuleSpecID may be published - * in a ModuleSpecAdvertisement. This advertisement is uniquely identified by - * the ModuleSpecID that it describes. - * - *

      - * The various implementations of a given SpecID may be published in - * ModuleImplAdvertisements. These advertisements are identified by the - * ModuleSpecID that they implement and a compatibility statement. - * ModuleImplAdvertisements baring the same SpecID and compatibility statement - * are theorethicaly interchangeable. However they may be subsequently discriminated - * by a Description element. - * - *

      - * A ModuleSpecID embeds a ModuleClassID which uniquely identifies a base Module - * class. A base module class defines a local behaviour and one API per compatible - * JXTA implementation. - * - *

      - * A ModuleSpecID therefore uniquely identifies an abstract module, of which an - * implementation compatible with the local JXTA implementation may be located and - * instantiated. - * - *

      - * In the standard PeerGroup implementation of the java reference implementation - * the various services are specified as a list of ModuleSpecID, for each of which - * the group locates and loads an implementation as part of the group's - * initialization. - * - * @see net.jxta.peergroup.PeerGroup - * @see net.jxta.platform.Module - * @see net.jxta.platform.ModuleClassID - * @see net.jxta.protocol.ModuleSpecAdvertisement - * @see net.jxta.protocol.ModuleImplAdvertisement - * @see net.jxta.id.ID - * @see net.jxta.document.Advertisement - * - */ - -public abstract class ModuleSpecID extends ID { - - /** - * Creates an ID by parsing the given URI. - * - *

      This convenience factory method works as if by invoking the - * {@link net.jxta.id.IDFactory#fromURI(URI)} method; any - * {@link java.net.URISyntaxException} thrown is caught and wrapped in a - * new {@link IllegalArgumentException} object, which is then thrown. - * - *

      This method is provided for use in situations where it is known that - * the given string is a legal ID, for example for ID constants declared - * within in a program, and so it would be considered a programming error - * for the URI not to parse as such. The {@link net.jxta.id.IDFactory}, - * which throws {@link java.net.URISyntaxException} directly, should be used - * situations where a ID is being constructed from user input or from some - * other source that may be prone to errors. - * - * @param fromURI The URI to be parsed into an ID - * @return The new ID - * - * @throws NullPointerException If {@code fromURI} is {@code null}. - * @throws IllegalArgumentException If the given URI is not a valid ID. - */ - public static ModuleSpecID create(URI fromURI) { - return (ModuleSpecID) ID.create(fromURI); - } - - /** - * {@inheritDoc} - */ - public ModuleSpecID intern() { - return (ModuleSpecID) super.intern(); - } - - /** - * Returns true if this ModuleSpecID is of the same base class than the - * given class. - * Note: This method is NOT named "isOfClass" because a ModuleClassID - * may have two portions; one that denotes a class proper, - * and an optional second one that denotes a "Role". For convenience, we refer - * the class stripped of its role portion as "the base class" although this is not - * a totally accurate term. - * A ModuleSpecID, is of a base class but is not related to any kind - * of role. So using "isOfClass" could be misleading. - * Base classes are represented by a class with the role ID set to zero, which - * happens to be a valid class. This routine may be used for comparison with - * such a class, of course. - * - * @param id Module class id to compare with - * @return boolean true if equals - * - */ - - public abstract boolean isOfSameBaseClass(ModuleClassID id); - - /** - * Returns true if this ModuleSpecID is of the same base class than the - * the given ModuleSpecID. - * - * @param id Module spec id to compare with - * @return boolean true if equals - * - */ - - public abstract boolean isOfSameBaseClass(ModuleSpecID id); - - /** - * Return a ModuleClassID of the same base class but with the role portion - * set to zero. aka "the base class". - * - * @return ModuleClassID the base class. - * - */ - - public abstract ModuleClassID getBaseClass(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/NetworkConfigurator.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/NetworkConfigurator.java deleted file mode 100644 index 3dc18b5c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/NetworkConfigurator.java +++ /dev/null @@ -1,1947 +0,0 @@ -/* - * Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.platform; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.membership.pse.PSEUtils; -import net.jxta.impl.membership.pse.PSEUtils.IssuerInfo; -import net.jxta.impl.protocol.HTTPAdv; -import net.jxta.impl.protocol.PSEConfigAdv; -import net.jxta.impl.protocol.PeerGroupConfigAdv; -import net.jxta.impl.protocol.PlatformConfig; -import net.jxta.impl.protocol.RdvConfigAdv; -import net.jxta.impl.protocol.RdvConfigAdv.RendezVousConfiguration; -import net.jxta.impl.protocol.RelayConfigAdv; -import net.jxta.impl.protocol.TCPAdv; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.TransportAdvertisement; - -import javax.security.cert.CertificateException; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.security.PrivateKey; -import java.security.cert.X509Certificate; -import java.util.Enumeration; -import java.util.List; -import java.util.MissingResourceException; -import java.util.NoSuchElementException; -import java.util.PropertyResourceBundle; -import java.util.ResourceBundle; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * NetworkConfigurator provides a simple programmatic interface for JXTA configuration. - *

      - * By default, it defines an edge configuration with TCP in auto mode w/port - * range 9701-9799, multicast enabled on group "224.0.1.85", and port 1234, - * HTTP transport with only outgoing enabled. - *

      - * By default a new PeerID is always generated. This can be overridden via - * {@link NetworkConfigurator#setPeerID} method or loading a PlatformConfig via - * {@link NetworkConfigurator#load}. - *

      - * A facility is provided to initialize a configuration by loading from an - * existing configuration. This provides limited platform configuration lifecycle - * management as well as configuration change management. - *

      - * Also by default, this class sets the default platform configurator to - * {@link net.jxta.impl.peergroup.NullConfigurator}. NullConfigurator - * is a no operation configurator intended to prevent any other configurators from - * being invoked, including the AWT ConfigDialog. - *

      - * NetworkConfigurator makes use of classes from the {@code net.jxta.impl.*} - * packages. Applications are very strongly encouraged to avoid importing these - * classes as their interfaces may change without notice in future JXTA releases. - * The NetworkConfigurator API abstracts the configuration implementation details - * and will provide continuity and stability i.e. the NetworkConfigurator API - * won't change and it will automatically accommodate changes to service - * configuration. - *

      - * Configuration example : - *

      - *     NetworkConfigurator config = new NetworkConfigurator();
      - *     if (!config.exists()) {
      - *         // Create a new configuration with a new name, principal, and pass
      - *         config.setName("New Name");
      - *         config.setPrincipal("username");
      - *         config.setPassword("password");
      - *         try {
      - *             //persist it
      - *             config.save();
      - *         } catch (IOException io) {
      - *             // deal with the io error
      - *         }
      - *      } else {
      - *        // Load the pre-existing configuration
      - *        File pc = new File(config.getHome(), "PlatformConfig");
      - *        try {
      - *            config.load(pc.toURI());
      - *            // make changes if so desired
      - *             ..
      - *             ..
      - *            // store the PlatformConfig under the default home
      - *            config.save();
      - *        } catch (CertificateException ce) {
      - *            // In case the root cert is invalid, this creates a new one
      - *            try {
      - *                  //principal
      - *                  config.setPrincipal("principal");
      - *                  //password to encrypt private key with
      - *                  config.setPassword("password");
      - *                  config.save();
      - *              } catch (Exception e) {
      - *                  e.printStackTrace();
      - *              }
      - *        }
      - * 

      - *

      - * - * @since JXTA JSE 2.4 - */ -public class NetworkConfigurator { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(NetworkConfigurator.class.getName()); - - // begin configuration modes - - /** - * Relay off Mode - */ - public final static int RELAY_OFF = 1 << 2; - - /** - * Relay client Mode - */ - public final static int RELAY_CLIENT = 1 << 3; - - /** - * Relay Server Mode - */ - public final static int RELAY_SERVER = 1 << 4; - - /** - * Proxy Server Mode - */ - public final static int PROXY_SERVER = 1 << 5; - - /** - * TCP transport client Mode - */ - public final static int TCP_CLIENT = 1 << 6; - - /** - * TCP transport Server Mode - */ - public final static int TCP_SERVER = 1 << 7; - - /** - * HTTP transport client Mode - */ - public final static int HTTP_CLIENT = 1 << 8; - - /** - * HTTP transport server Mode - */ - public final static int HTTP_SERVER = 1 << 9; - - /** - * IP multicast transport Mode - */ - public final static int IP_MULTICAST = 1 << 10; - - /** - * RendezVousService Mode - */ - public final static int RDV_SERVER = 1 << 11; - - /** - * RendezVousService Client - */ - public final static int RDV_CLIENT = 1 << 12; - - /** - * RendezVousService Ad-Hoc mode - */ - public final static int RDV_AD_HOC = 1 << 13; - - /** - * Default AD-HOC configuration - */ - public final static int ADHOC_NODE = TCP_CLIENT | TCP_SERVER | IP_MULTICAST | RDV_AD_HOC | RELAY_OFF; - - /** - * Default Edge configuration - */ - public final static int EDGE_NODE = TCP_CLIENT | TCP_SERVER | HTTP_CLIENT | IP_MULTICAST | RDV_CLIENT | RELAY_CLIENT; - - /** - * Default Rendezvous configuration - */ - public final static int RDV_NODE = RDV_SERVER | TCP_CLIENT | TCP_SERVER | HTTP_SERVER; - - /** - * Default Relay configuration - */ - public final static int RELAY_NODE = RELAY_SERVER | TCP_CLIENT | TCP_SERVER | HTTP_SERVER; - - /** - * Default Proxy configuration - */ - public final static int PROXY_NODE = PROXY_SERVER | RELAY_NODE; - - /** - * Default Rendezvous/Relay/Proxy configuration - */ - public final static int RDV_RELAY_PROXY_NODE = RDV_NODE | PROXY_NODE; - - - // end configuration modes - - /** - * Default mode - */ - protected transient int mode = EDGE_NODE; - - /** - * Default PlatformConfig Peer Description - */ - protected transient String description = "Platform Config Advertisement created by : " + NetworkConfigurator.class.getName(); - - /** - * The location which will serve as the parent for all stored items used - * by JXTA. - */ - private transient URI storeHome = null; - - /** - * Default peer name - */ - protected transient String name = "unknown"; - - /** - * Password value used to generate root Certificate and to protect the - * Certificate's PrivateKey. - */ - protected transient String password = null; - - /** - * Default PeerID - */ - protected transient PeerID peerid = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID); - - /** - * Principal value used to generate root certificate - */ - protected transient String principal = null; - - /** - * Public Certificate chain - */ - protected transient X509Certificate[] cert = null; - - /** - * Subject private key - */ - protected transient PrivateKey subjectPkey = null; - - /** - * Freestanding keystore location - */ - protected transient URI keyStoreLocation = null; - - /** - * Proxy Service Document - */ - protected transient XMLElement proxyConfig; - - /** - * Personal Security Environment Config Advertisement - * - * @see net.jxta.impl.membership.pse.PSEConfig - */ - protected transient PSEConfigAdv pseConf; - - /** - * Rendezvous Config Advertisement - */ - protected transient RdvConfigAdv rdvConfig; - - /** - * Default Rendezvous Seeding URI - */ - protected URI rdvSeedingURI = null; - - /** - * Relay Config Advertisement - */ - protected transient RelayConfigAdv relayConfig; - - /** - * Default Relay Seeding URI - */ - protected transient URI relaySeedingURI = null; - - /** - * TCP Config Advertisement - */ - protected transient TCPAdv tcpConfig; - - /** - * Default TCP transport state - */ - protected transient boolean tcpEnabled = true; - - /** - * HTTP Config Advertisement - */ - protected transient HTTPAdv httpConfig; - - /** - * Default HTTP transport state - */ - protected transient boolean httpEnabled = true; - - /** - * Infrastructure Peer Group Configuration - */ - protected transient PeerGroupConfigAdv infraPeerGroupConfig; - - /** - * Creates NetworkConfigurator instance with default AD-HOC configuration - * - * @param storeHome the URI to persistent store - * @return NetworkConfigurator instance with default AD-HOC configuration - */ - public static NetworkConfigurator newAdHocConfiguration(URI storeHome) { - return new NetworkConfigurator(ADHOC_NODE, storeHome); - } - - /** - * Creates NetworkConfigurator instance with default Edge configuration - * - * @param storeHome the URI to persistent store - * @return NetworkConfigurator instance with default AD-HOC configuration - */ - public static NetworkConfigurator newEdgeConfiguration(URI storeHome) { - return new NetworkConfigurator(EDGE_NODE, storeHome); - } - - /** - * Creates NetworkConfigurator instance with default Rendezvous configuration - * - * @param storeHome the URI to persistent store - * @return NetworkConfigurator instance with default Rendezvous configuration - */ - public static NetworkConfigurator newRdvConfiguration(URI storeHome) { - return new NetworkConfigurator(RDV_NODE, storeHome); - } - - /** - * Creates NetworkConfigurator instance with default Relay configuration - * - * @param storeHome the URI to persistent store - * @return NetworkConfigurator instance with default Relay configuration - */ - public static NetworkConfigurator newRelayConfiguration(URI storeHome) { - return new NetworkConfigurator(RELAY_NODE, storeHome); - } - - /** - * Creates NetworkConfigurator instance with default Rendezvous configuration - * - * @param storeHome the URI to persistent store - * @return NetworkConfigurator instance with default Rendezvous configuration - */ - public static NetworkConfigurator newRdvRelayConfiguration(URI storeHome) { - return new NetworkConfigurator(RDV_NODE | RELAY_SERVER, storeHome); - } - - /** - * Creates NetworkConfigurator instance with default Proxy configuration - * - * @param storeHome the URI to persistent store - * @return NetworkConfigurator instance with defaultProxy configuration - */ - public static NetworkConfigurator newProxyConfiguration(URI storeHome) { - return new NetworkConfigurator(PROXY_NODE, storeHome); - } - - /** - * Creates NetworkConfigurator instance with default Rendezvous, Relay, Proxy configuration - * - * @param storeHome the URI to persistent store - * @return NetworkConfigurator instance with default Rendezvous, Relay, Proxy configuration - */ - public static NetworkConfigurator newRdvRelayProxyConfiguration(URI storeHome) { - return new NetworkConfigurator(RDV_RELAY_PROXY_NODE, storeHome); - } - - /** - * Creates the default NetworkConfigurator. The configuration is stored with a default configuration mode of EDGE_NODE - */ - public NetworkConfigurator() { - this(EDGE_NODE, new File(".jxta").toURI()); - } - - /** - * Creates a NetworkConfigurator with the default configuration of the - * specified mode.

      Valid modes include ADHOC_NODE, EDGE_NODE, RDV_NODE - * PROXY_NODE, RELAY_NODE, RDV_RELAY_PROXY_NODE, or any combination of - * specific configuration.

      e.g. RDV_NODE | HTTP_CLIENT - * - * @param mode the new configuration mode - * @param storeHome the URI to persistent store - * @see #setMode - */ - public NetworkConfigurator(int mode, URI storeHome) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Creating a default configuration"); - } - - setStoreHome(storeHome); - - httpConfig = createHttpAdv(); - rdvConfig = createRdvConfigAdv(); - relayConfig = createRelayConfigAdv(); - proxyConfig = createProxyAdv(); - tcpConfig = createTcpAdv(); - infraPeerGroupConfig = createInfraConfigAdv(); - - setMode(mode); - } - - /** - * Sets PlaformConfig Peer Description element - * - * @param description the peer description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * Set the current directory for configuration and cache persistent store - *

      (default is $CWD/.jxta) - *

      - *

      Simple example :
      - *
      -     *  
      -     *   //Create an application home
      -     *   File appHome = new File(System.getProperty("JXTA_HOME", ".cache"));
      -     *   //Create an instance home under the application home
      -     *   File instanceHome = new File(appHome, instanceName);
      -     *   jxtaConfig.setHome(instanceHome);
      -     *   
      -     * 
      - * - * @param home the new home value - * @see #getHome - */ - public void setHome(File home) { - this.storeHome = home.toURI(); - } - - /** - * Returns the current directory for configuration and cache persistent - * store. This is the same location as returned by {@link #getStoreHome()} - * which is more general than this method. - * - * @return Returns the current home directory - * @see #setHome - */ - public File getHome() { - if( "file".equalsIgnoreCase(storeHome.getScheme())) { - return new File(storeHome); - } else { - throw new UnsupportedOperationException("Home location is not a file:// URI : " + storeHome ); - } - } - - /** - * Returns the location which will serve as the parent for all stored items - * used by JXTA. - * - * @return The location which will serve as the parent for all stored - * items used by JXTA. - * @see net.jxta.peergroup.PeerGroup#getStoreHome() - */ - public URI getStoreHome() { - return storeHome; - } - - - /** - * Sets the location which will serve as the parent for all stored items - * used by JXTA. - * - * @see net.jxta.peergroup.PeerGroup#getStoreHome() - */ - public void setStoreHome(URI newHome) { - // Fail if the URI is not absolute. - if (!newHome.isAbsolute()) { - throw new IllegalArgumentException("Only absolute URIs accepted for store home location."); - } - - // Fail if the URI is Opaque. - if (newHome.isOpaque()) { - throw new IllegalArgumentException("Only hierarchical URIs accepted for store home location."); - } - - // FIXME this should be removed when 1488 is committed - if (!"file".equalsIgnoreCase(newHome.getScheme())) { - throw new IllegalArgumentException("Only file based URI currently supported"); - } - - // Adds a terminating / - if (!newHome.toString().endsWith("/")) { - newHome = URI.create(newHome.toString() + "/"); - } - - storeHome = newHome; - } - - /** - * Toggles HTTP transport state - * - * @param enabled if true, enables HTTP transport - */ - public void setHttpEnabled(boolean enabled) { - this.httpEnabled = enabled; - if (!httpEnabled) { - httpConfig.setClientEnabled(false); - httpConfig.setServerEnabled(false); - } - } - - /** - * Toggles the HTTP transport server (incoming) mode - * - * @param incoming toggles HTTP transport server mode - */ - public void setHttpIncoming(boolean incoming) { - httpConfig.setServerEnabled(incoming); - } - - /** - * Toggles the HTTP transport client (outgoing) mode - * - * @param outgoing toggles HTTP transport client mode - */ - public void setHttpOutgoing(boolean outgoing) { - httpConfig.setClientEnabled(outgoing); - } - - /** - * Sets the HTTP listening port (default 9901) - * - * @param port the new HTTP port value - */ - public void setHttpPort(int port) { - httpConfig.setPort(port); - } - - /** - * Sets the HTTP interface Address to bind the HTTP transport to - *

      e.g. "192.168.1.1" - * - * @param address the new address value - */ - public void setHttpInterfaceAddress(String address) { - httpConfig.setInterfaceAddress(address); - } - - /** - * Sets the HTTP JXTA Public Address - * e.g. "192.168.1.1:9700" - * - * @param address the HTTP transport public address - * @param exclusive determines whether an address is advertised exclusively - */ - public void setHttpPublicAddress(String address, boolean exclusive) { - httpConfig.setServer(address); - httpConfig.setPublicAddressOnly(exclusive); - } - - /** - * Sets the ID which will be used for new net peer group instances. - *

      - *

      By Setting an alternate infrastructure PeerGroup ID (aka NetPeerGroup), - * it prevents heterogeneous infrastructure PeerGroups from intersecting. - *

      This is highly recommended practice for application deployment - * - * @param id the new infrastructure PeerGroupID as a string - * @see net.jxta.peergroup.PeerGroupFactory#setNetPGID - */ - public void setInfrastructureID(ID id) { - if (id == null || id.equals(ID.nullID)) { - throw new IllegalArgumentException("PeerGroupID can not be null"); - } - infraPeerGroupConfig.setPeerGroupID(id); - } - - /** - * Sets the ID which will be used for new net peer group instances. - *

      - *

      By Setting an alternate infrastructure PeerGroup ID (aka NetPeerGroup), - * it prevents heterogeneous infrastructure PeerGroups from intersecting. - *

      This is highly recommended practice for application deployment - * - * @param idStr the new infrastructure PeerGroupID as a string - * @see net.jxta.peergroup.PeerGroupFactory#setNetPGID - */ - public void setInfrastructureID(String idStr) { - if (idStr == null || idStr.length() == 0) { - throw new IllegalArgumentException("PeerGroupID string can not be empty or null"); - } - - PeerGroupID pgid = (PeerGroupID) ID.create(URI.create(idStr)); - setInfrastructureID(pgid); - } - - /** - * Gets the ID which will be used for new net peer group instances. - *

      - * - * @return the infrastructure PeerGroupID as a string - */ - public String getInfrastructureIDStr() { - return infraPeerGroupConfig.getPeerGroupID().toString(); - } - - /** - * Sets the infrastructure PeerGroup name meta-data - * - * @param name the Infrastructure PeerGroup name - * @see net.jxta.peergroup.PeerGroupFactory#setNetPGName - */ - public void setInfrastructureName(String name) { - infraPeerGroupConfig.setName(name); - } - - /** - * Gets the infrastructure PeerGroup name meta-data - * - * @return the Infrastructure PeerGroup name - */ - public String getInfrastructureName() { - return infraPeerGroupConfig.getName(); - } - - /** - * Sets the infrastructure PeerGroup description meta-data - * - * @param description the infrastructure PeerGroup description - * @see net.jxta.peergroup.PeerGroupFactory#setNetPGDesc - */ - public void setInfrastructureDescriptionStr(String description) { - infraPeerGroupConfig.setDescription(description); - } - - /** - * Returns the infrastructure PeerGroup description meta-data - * - * @return the infrastructure PeerGroup description meta-data - */ - public String getInfrastructureDescriptionStr() { - return infraPeerGroupConfig.getDescription(); - } - - /** - * Sets the infrastructure PeerGroup description meta-data - * - * @param description the infrastructure PeerGroup description - * @see net.jxta.peergroup.PeerGroupFactory#setNetPGDesc - */ - public void setInfrastructureDesc(XMLElement description) { - infraPeerGroupConfig.setDesc(description); - } - - /** - * Sets the current node configuration mode. - *

      The default mode is EDGE, unless modified at construction time. - * A node configuration mode defined a preset configuration - * parameters based on a operating mode. i.e. an EDGE mode, enable - * client/server side tcp, multicast, client side http, RelayService - * client mode. - *

      Valid modes include EDGE, RDV_SERVER, - * RELAY_OFF, RELAY_CLIENT, RELAY_SERVER, PROXY_SERVER, or any combination - * of which.

      e.g. RDV_SERVER + RELAY_SERVER - * - * @param mode the new configuration mode - * @see #getMode - */ - public void setMode(int mode) { - this.mode = mode; - if ((mode & PROXY_SERVER) == PROXY_SERVER && ((mode & RELAY_SERVER) != RELAY_SERVER)) { - mode = mode | RELAY_SERVER; - } - - // RELAY config - relayConfig.setClientEnabled((mode & RELAY_CLIENT) == RELAY_CLIENT); - relayConfig.setServerEnabled((mode & RELAY_SERVER) == RELAY_SERVER); - - // RDV_SERVER - if ((mode & RDV_SERVER) == RDV_SERVER) { - rdvConfig.setConfiguration(RendezVousConfiguration.RENDEZVOUS); - } else if ((mode & RDV_CLIENT) == RDV_CLIENT) { - rdvConfig.setConfiguration(RendezVousConfiguration.EDGE); - } else if ((mode & RDV_AD_HOC) == RDV_AD_HOC) { - rdvConfig.setConfiguration(RendezVousConfiguration.AD_HOC); - } - - // TCP - tcpConfig.setClientEnabled((mode & TCP_CLIENT) == TCP_CLIENT); - tcpConfig.setServerEnabled((mode & TCP_SERVER) == TCP_SERVER); - - // HTTP - httpConfig.setClientEnabled((mode & HTTP_CLIENT) == HTTP_CLIENT); - httpConfig.setServerEnabled((mode & HTTP_SERVER) == HTTP_SERVER); - - // Multicast - tcpConfig.setMulticastState((mode & IP_MULTICAST) == IP_MULTICAST); - - // EDGE - if (mode == EDGE_NODE) { - rdvConfig.setConfiguration(RendezVousConfiguration.EDGE); - } - } - - /** - * Returns the current configuration mode - *

      The default mode is EDGE, unless modified at construction time or through - * Method {@link NetworkConfigurator#setMode}. A node configuration mode defined a preset configuration - * parameters based on a operating mode. i.e. an EDGE mode, enable - * client/server side tcp, multicast, client side http, RelayService - * client mode. - * - * @return mode the current mode value - * @see #setMode - */ - public int getMode() { - return mode; - } - - /** - * Sets the IP group multicast packet size - * - * @param size the new multicast packet - */ - public void setMulticastSize(int size) { - tcpConfig.setMulticastSize(size); - } - - /** - * Gets the IP group multicast packet size - * - * @return the multicast packet - */ - public int getMulticastSize() { - return tcpConfig.getMulticastSize(); - } - - /** - * Sets the IP group multicast address (default 224.0.1.85) - * - * @param mcastAddress the new multicast group address - * @see #setMulticastPort - */ - public void setMulticastAddress(String mcastAddress) { - tcpConfig.setMulticastAddr(mcastAddress); - } - - /** - * Sets the IP group multicast port (default 1234) - * - * @param port the new IP group multicast port - * @see #setMulticastAddress - */ - public void setMulticastPort(int port) { - tcpConfig.setMulticastPort(port); - } - - /** - * Sets the node name - * - * @param name node name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Gets the node name - * - * @return node name - */ - public String getName() { - return this.name; - } - - /** - * Sets the Principal for the peer root certificate - * - * @param principal the new principal value - * @see #setPassword - * @see #getPrincipal - * @see #setPrincipal - */ - public void setPrincipal(String principal) { - this.principal = principal; - } - - /** - * Gets the Principal for the peer root certificate - * - * @return principal if a principal is set, null otherwise - * @see #setPassword - * @see #getPrincipal - * @see #setPrincipal - */ - public String getPrincipal() { - return principal; - } - - /** - * Sets the public Certificate for this configuration. - * - * @param cert the new cert value - */ - public void setCertificate(X509Certificate cert) { - this.cert = new X509Certificate[] { cert }; - } - - /** - * Returns the public Certificate for this configuration. - * - * @return X509Certificate - */ - public X509Certificate getCertificate() { - return (cert == null || cert.length == 0 ? null : cert[0]); - } - - /** - * Sets the public Certificate chain for this configuration. - * - * @param certificateChain the new Certificate chain value - */ - public void setCertificateChain(X509Certificate[] certificateChain) { - this.cert = certificateChain; - } - - /** - * Gets the public Certificate chain for this configuration. - * - * @return X509Certificate chain - */ - public X509Certificate[] getCertificateChain() { - return cert; - } - - /** - * Sets the Subject private key - * - * @param subjectPkey the subject private key - */ - public void setPrivateKey(PrivateKey subjectPkey) { - this.subjectPkey = subjectPkey; - } - - /** - * Gets the Subject private key - * - * @return the subject private key - */ - public PrivateKey getPrivateKey() { - return this.subjectPkey; - } - - /** - * Sets freestanding keystore location - * - * @param keyStoreLocation the absolute location of the freestanding keystore - */ - public void setKeyStoreLocation(URI keyStoreLocation) { - this.keyStoreLocation = keyStoreLocation; - } - - /** - * Gets the freestanding keystore location - * - * @return the location of the freestanding keystore - */ - public URI getKeyStoreLocation() { - return keyStoreLocation; - } - - /** - * Sets the password used to sign the private key of the root certificate - * - * @param password the new password value - * @see #setPassword - * @see #getPrincipal - * @see #setPrincipal - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * Gets the password used to sign the private key of the root certificate - * - * @return password if a password is set, null otherwise - * @see #setPassword - * @see #getPrincipal - * @see #setPrincipal - */ - public String getPassword() { - return password; - } - - /** - * Sets the PeerID (by default, a new PeerID is generated). - *

      Note: Persist the PeerID generated, or use load() - * to avoid overridding a node's PeerID between restarts. - * - * @param peerid the new net.jxta.peer.PeerID - */ - public void setPeerID(PeerID peerid) { - this.peerid = peerid; - } - - /** - * Gets the PeerID - * - * @return peerid the net.jxta.peer.PeerID value - */ - public PeerID getPeerID() { - return this.peerid; - } - - /** - * Sets Rendezvous Seeding URI - *

      e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvous.cgi?3 - * - * @param seedURI Rendezvous service seeding URI - */ - public void addRdvSeedingURI(URI seedURI) { - rdvConfig.addSeedingURI(seedURI); - } - - /** - * Sets Rendezvous Access Control URI - *

      e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvousACL.cgi?3 - * - * @param aclURI Rendezvous Access Control URI - */ - public void setRdvACLURI(URI aclURI) { - rdvConfig.setAclUri(aclURI); - } - - /** - * Gets Rendezvous Access Control URI if set - *

      e.g. http://rdv.jxtahosts.net/cgi-bin/rendezvousACL.cgi?3 - * - * @return aclURI Rendezvous Access Control URI - */ - public URI getRdvACLURI() { - return rdvConfig.getAclUri(); - } - - /** - * Sets Relay Access Control URI - *

      e.g. http://rdv.jxtahosts.net/cgi-bin/relayACL.cgi?3 - * - * @param aclURI Relay Access Control URI - */ - public void setRelayACLURI(URI aclURI) { - relayConfig.setAclUri(aclURI); - } - - /** - * Gets Relay Access Control URI if set - *

      e.g. http://rdv.jxtahosts.net/cgi-bin/relayACL.cgi?3 - * - * @return aclURI Relay Access Control URI - */ - public URI getRelayACLURI() { - return relayConfig.getAclUri(); - } - - /** - * Sets the RelayService maximum number of simultaneous relay clients - * - * @param relayMaxClients the new relayMaxClients value - */ - public void setRelayMaxClients(int relayMaxClients) { - if ((relayMaxClients != -1) && (relayMaxClients <= 0)) { - throw new IllegalArgumentException("Relay Max Clients : " + relayMaxClients + " must be > 0"); - } - relayConfig.setMaxClients(relayMaxClients); - } - - /** - * Sets the RelayService Seeding URI - *

      e.g. http://rdv.jxtahosts.net/cgi-bin/relays.cgi?3 - *

      A seeding URI (when read) is expected to provide a list of - * physical endpoint addresse(s) to relay peers - * - * @param seedURI RelayService seeding URI - */ - public void addRelaySeedingURI(URI seedURI) { - relayConfig.addSeedingURI(seedURI); - } - - /** - * Sets the RendezVousService maximum number of simultaneous rendezvous clients - * - * @param rdvMaxClients the new rendezvousMaxClients value - */ - public void setRendezvousMaxClients(int rdvMaxClients) { - if ((rdvMaxClients != -1) && (rdvMaxClients <= 0)) { - throw new IllegalArgumentException("Rendezvous Max Clients : " + rdvMaxClients + " must be > 0"); - } - rdvConfig.setMaxClients(rdvMaxClients); - } - - /** - * Toggles TCP transport state - * - * @param enabled if true, enables TCP transport - */ - public void setTcpEnabled(boolean enabled) { - this.tcpEnabled = enabled; - if (!tcpEnabled) { - tcpConfig.setClientEnabled(false); - tcpConfig.setServerEnabled(false); - } - } - - /** - * Sets the TCP transport listening port (default 9701) - * - * @param port the new tcpPort value - */ - public void setTcpPort(int port) { - tcpConfig.setPort(port); - } - - /** - * Sets the lowest port on which the TCP Transport will listen if configured - * to do so. Valid values are -1, 0 and - * 1-65535. The -1 value is used to signify that - * the port range feature should be disabled. The 0 specifies - * that the Socket API dynamic port allocation should be used. For values - * 1-65535 the value must be equal to or less than the value - * used for end port. - * - * @param start the lowest port on which to listen. - */ - public void setTcpStartPort(int start) { - tcpConfig.setStartPort(start); - } - - /** - * Returns the highest port on which the TCP Transport will listen if - * configured to do so. Valid values are -1, 0 and - * 1-65535. The -1 value is used to signify that - * the port range feature should be disabled. The 0 specifies - * that the Socket API dynamic port allocation should be used. For values - * 1-65535 the value must be equal to or greater than the value - * used for start port. - * - * @param end the new TCP end port - */ - public void setTcpEndPort(int end) { - tcpConfig.setEndPort(end); - } - - /** - * Toggles TCP transport server (incoming) mode (default is on) - * - * @param incoming the new TCP server mode - */ - public void setTcpIncoming(boolean incoming) { - tcpConfig.setServerEnabled(incoming); - } - - /** - * Toggles TCP transport client (outgoing) mode (default is true) - * - * @param outgoing the new tcpOutgoing value - */ - public void setTcpOutgoing(boolean outgoing) { - tcpConfig.setClientEnabled(outgoing); - } - - /** - * Sets the TCP transport interface address - *

      e.g. "192.168.1.1" - * - * @param address the TCP transport interface address - */ - public void setTcpInterfaceAddress(String address) { - tcpConfig.setInterfaceAddress(address); - } - - /** - * Sets the node public address - *

      e.g. "192.168.1.1:9701" - *

      This address is the physical address defined in a node's - * AccessPointAdvertisement. This often required for NAT'd/FW nodes - * - * @param address the TCP transport public address - * @param exclusive public address advertised exclusively - */ - public void setTcpPublicAddress(String address, boolean exclusive) { - tcpConfig.setServer(address); - tcpConfig.setPublicAddressOnly(exclusive); - } - - /** - * Toggles whether to use IP group multicast (default is true) - * - * @param multicastOn the new useMulticast value - */ - public void setUseMulticast(boolean multicastOn) { - tcpConfig.setMulticastState(multicastOn); - } - - /** - * Determines whether to restrict RelayService leases to those defined in - * the seed list - * - * @param useOnlyRelaySeeds restrict RelayService lease to seed list - */ - public void setUseOnlyRelaySeeds(boolean useOnlyRelaySeeds) { - relayConfig.setUseOnlySeeds(useOnlyRelaySeeds); - } - - /** - * Determines whether to restrict RendezvousService leases to those defined in - * the seed list - * - * @param useOnlyRendezvouSeeds restrict RendezvousService lease to seed list - */ - public void setUseOnlyRendezvousSeeds(boolean useOnlyRendezvouSeeds) { - rdvConfig.setUseOnlySeeds(useOnlyRendezvouSeeds); - } - - /** - * Adds RelayService peer seed address - *

      A RelayService seed is defined as a physical endpoint address - *

      e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701 - * - * @param seedURI the relay seed URI - */ - public void addSeedRelay(URI seedURI) { - relayConfig.addSeedRelay(seedURI.toString()); - } - - /** - * Adds Rendezvous peer seed, physical endpoint address - *

      A RendezVousService seed is defined as a physical endpoint address - *

      e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701 - * - * @param seedURI the rendezvous seed URI - */ - public void addSeedRendezvous(URI seedURI) { - rdvConfig.addSeedRendezvous(seedURI); - } - - /** - * Returns true if a PlatformConfig file exist under store home - * - * @return true if a PlatformConfig file exist under store home - */ - public boolean exists() { - - URI platformConfig = storeHome.resolve("PlatformConfig"); - try { - return null != read(platformConfig); - } catch( IOException failed ) { - return false; - } - } - - /** - * Sets the PeerID for this Configuration - * - * @param peerIdStr the new PeerID as a string - */ - public void setPeerId(String peerIdStr) { - this.peerid = (PeerID) ID.create(URI.create(peerIdStr)); - } - - /** - * Sets the new RendezvousService seeding URI as a string. - *

      A seeding URI (when read) is expected to provide a list of - * physical endpoint address to rendezvous peers - * - * @param seedURIStr the new rendezvous seed URI as a string - */ - public void addRdvSeedingURI(String seedURIStr) { - rdvConfig.addSeedingURI(URI.create(seedURIStr)); - } - - /** - * Sets the new RelayService seeding URI as a string. - *

      A seeding URI (when read) is expected to provide a list of - * physical endpoint address to relay peers - * - * @param seedURIStr the new RelayService seed URI as a string - */ - public void addRelaySeedingURI(String seedURIStr) { - relayConfig.addSeedingURI(URI.create(seedURIStr)); - } - - /** - * Sets the List relaySeeds represented as Strings - *

      A RelayService seed is defined as a physical endpoint address - *

      e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701 - * - * @param seeds the Set RelayService seed URIs as a string - */ - public void setRelaySeedURIs(List seeds) { - relayConfig.clearSeedRelays(); - for (String seedStr : seeds) { - relayConfig.addSeedRelay(new EndpointAddress(seedStr)); - } - } - - /** - * Sets the relaySeeds represented as Strings - *

      A seeding URI (when read) is expected to provide a list of - * physical endpoint address to relay peers - * - * @param seedURIs the List relaySeeds represented as Strings - */ - public void setRelaySeedingURIs(Set seedURIs) { - relayConfig.clearSeedingURIs(); - for (String seedStr : seedURIs) { - relayConfig.addSeedingURI(URI.create(seedStr)); - } - } - - /** - * Clears the List of RelayService seeds - */ - public void clearRelaySeeds() { - relayConfig.clearSeedRelays(); - } - - /** - * Clears the List of RelayService seeding URIs - */ - public void clearRelaySeedingURIs() { - relayConfig.clearSeedingURIs(); - } - - /** - * Sets the List of RendezVousService seeds represented as Strings - *

      A RendezvousService seed is defined as a physical endpoint address - *

      e.g. http://192.168.1.1:9700, or tcp://192.168.1.1:9701 - * - * @param seeds the Set of rendezvousSeeds represented as Strings - */ - public void setRendezvousSeeds(Set seeds) { - rdvConfig.clearSeedRendezvous(); - for (String seedStr : seeds) { - rdvConfig.addSeedRendezvous(URI.create(seedStr)); - } - } - - /** - * Sets the List of RendezVousService seeding URIs represented as Strings. - * A seeding URI (when read) is expected to provide a list of - * physical endpoint address to rendezvous peers. - * - * @deprecated The name of this method is inconsistent with it's function! - * It sets the seeding URIs and not the seed URIs. Use - * {@link #setRendezvousSeedingURIs()} instead. - * - * @param seedURIs the List rendezvousSeeds represented as Strings - */ - @Deprecated - public void setRendezvousSeedURIs(List seedingURIs) { - setRendezvousSeedingURIs(seedingURIs); - } - - /** - * Sets the List of RendezVousService seeding URIs represented as Strings. - * A seeding URI (when read) is expected to provide a list of - * physical endpoint address to rendezvous peers. - * - * @param seedURIs the List rendezvousSeeds represented as Strings. - */ - public void setRendezvousSeedingURIs(List seedingURIs) { - rdvConfig.clearSeedingURIs(); - for (String seedStr : seedingURIs) { - rdvConfig.addSeedingURI(URI.create(seedStr)); - } - } - - /** - * Clears the list of RendezVousService seeds - */ - public void clearRendezvousSeeds() { - rdvConfig.clearSeedRendezvous(); - } - - /** - * Clears the list of RendezVousService seeding URIs - * - * @deprecated The name of this method is inconsistent with it's function! - * It clears the seeding URIs and not the seed URIs. Use - * {@link #clearRendezvousSeedingURIs()} instead. - * - */ - @Deprecated - public void clearRendezvousSeedURIs() { - rdvConfig.clearSeedingURIs(); - } - - /** - * Clears the list of RendezVousService seeding URIs - */ - public void clearRendezvousSeedingURIs() { - rdvConfig.clearSeedingURIs(); - } - - /** - * Load a configuration from the specified store home uri - *

      - * e.g. file:/export/dist/EdgeConfig.xml, e.g. http://configserver.net/configservice?Edge - * - * @return The loaded configuration. - * @throws IOException if an i/o error occurs - * @throws CertificateException if the MembershipService is invalid - */ - public ConfigParams load() throws IOException, CertificateException { - return load(storeHome.resolve("PlatformConfig")); - } - - /** - * Loads a configuration from a specified uri - *

      - * e.g. file:/export/dist/EdgeConfig.xml, e.g. http://configserver.net/configservice?Edge - * - * @param uri the URI to PlatformConfig - * @return The loaded configuration. - * @throws IOException if an i/o error occurs - * @throws CertificateException if the MemebershipService is invalid - */ - public ConfigParams load(URI uri) throws IOException, CertificateException { - if (uri == null) { - throw new IllegalArgumentException("URI can not be null"); - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Loading configuration : " + uri); - } - - PlatformConfig platformConfig = read(uri); - - name = platformConfig.getName(); - peerid = platformConfig.getPeerID(); - description = platformConfig.getDescription(); - - // TCP - XMLElement param = (XMLElement) platformConfig.getServiceParam(PeerGroup.tcpProtoClassID); - tcpEnabled = platformConfig.isSvcEnabled(PeerGroup.tcpProtoClassID); - Enumeration tcpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType()); - - // get the TransportAdv from either TransportAdv or tcpConfig - if (tcpChilds.hasMoreElements()) { - param = (XMLElement) tcpChilds.nextElement(); - } else { - throw new IllegalStateException("Missing TCP Advertisment"); - } - tcpConfig = (TCPAdv) AdvertisementFactory.newAdvertisement(param); - - // HTTP - try { - param = (XMLElement) platformConfig.getServiceParam(PeerGroup.httpProtoClassID); - httpEnabled = platformConfig.isSvcEnabled(PeerGroup.httpProtoClassID); - - Enumeration httpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType()); - - // get the TransportAdv from either TransportAdv - if (httpChilds.hasMoreElements()) { - param = (XMLElement) httpChilds.nextElement(); - } else { - throw new IllegalStateException("Missing HTTP Advertisment"); - } - // Read-in the adv as it is now. - httpConfig = (HTTPAdv) AdvertisementFactory.newAdvertisement(param); - } catch (Exception failure) { - IOException ioe = new IOException("error processing the HTTP config advertisement"); - ioe.initCause(failure); - throw ioe; - } - - // ProxyService - try { - param = (XMLElement) platformConfig.getServiceParam(PeerGroup.proxyClassID); - if (param != null && !platformConfig.isSvcEnabled(PeerGroup.proxyClassID)) { - mode = mode | PROXY_SERVER; - } - } catch (Exception failure) { - IOException ioe = new IOException("error processing the pse config advertisement"); - ioe.initCause(failure); - throw ioe; - } - - // Rendezvous - try { - param = (XMLElement) platformConfig.getServiceParam(PeerGroup.rendezvousClassID); - // backwards compatibility - param.addAttribute("type", RdvConfigAdv.getAdvertisementType()); - rdvConfig = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(param); - if (rdvConfig.getConfiguration() == RendezVousConfiguration.AD_HOC) { - mode = mode | RDV_AD_HOC; - } else if (rdvConfig.getConfiguration() == RendezVousConfiguration.EDGE) { - mode = mode | RDV_CLIENT; - } else if (rdvConfig.getConfiguration() == RendezVousConfiguration.RENDEZVOUS) { - mode = mode | RDV_SERVER; - } - } catch (Exception failure) { - IOException ioe = new IOException("error processing the rendezvous config advertisement"); - ioe.initCause(failure); - throw ioe; - } - - // Relay - try { - param = (XMLElement) platformConfig.getServiceParam(PeerGroup.relayProtoClassID); - if (param != null && !platformConfig.isSvcEnabled(PeerGroup.relayProtoClassID)) { - mode = mode | RELAY_OFF; - } - // backwards compatibility - param.addAttribute("type", RelayConfigAdv.getAdvertisementType()); - relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(param); - } catch (Exception failure) { - IOException ioe = new IOException("error processing the relay config advertisement"); - ioe.initCause(failure); - throw ioe; - } - - // PSE - param = (XMLElement) platformConfig.getServiceParam(PeerGroup.membershipClassID); - if (param != null) { - - Advertisement adv = null; - try { - adv = AdvertisementFactory.newAdvertisement(param); - } catch (NoSuchElementException notAnAdv) { - CertificateException cnfe = new CertificateException("No membership advertisement found"); - cnfe.initCause(notAnAdv); - } catch (IllegalArgumentException invalidAdv) { - CertificateException cnfe = new CertificateException("Invalid membership advertisement"); - cnfe.initCause(invalidAdv); - } - - if (adv instanceof PSEConfigAdv) { - pseConf = (PSEConfigAdv) adv; - cert = pseConf.getCertificateChain(); - } else { - throw new CertificateException("Error processing the Membership config advertisement. Unexpected membership advertisement " - + adv.getAdvertisementType()); - } - } - - // Infra Group - infraPeerGroupConfig = (PeerGroupConfigAdv) platformConfig.getSvcConfigAdvertisement(PeerGroup.peerGroupClassID); - if (null == infraPeerGroupConfig) { - infraPeerGroupConfig = createInfraConfigAdv(); - try { - URI configPropsURI = storeHome.resolve("config.properties"); - InputStream configPropsIS = configPropsURI.toURL().openStream(); - ResourceBundle rsrcs = new PropertyResourceBundle(configPropsIS); - configPropsIS.close(); - - NetGroupTunables tunables = new NetGroupTunables(rsrcs, new NetGroupTunables()); - - infraPeerGroupConfig.setPeerGroupID(tunables.id); - infraPeerGroupConfig.setName(tunables.name); - infraPeerGroupConfig.setDesc(tunables.desc); - } catch (IOException ignored) { - //ignored - } catch (MissingResourceException ignored) { - //ignored - } - } - return platformConfig; - } - - /** - * Persists a PlatformConfig advertisement under getStoreHome()+"/PlaformConfig" - *

      - * Home may be overridden by a call to setHome() - * - * @see #load - * @throws IOException If there is a failure saving the PlatformConfig. - */ - public void save() throws IOException { - httpEnabled = (httpConfig.isClientEnabled() || httpConfig.isServerEnabled()); - tcpEnabled = (tcpConfig.isClientEnabled() || tcpConfig.isServerEnabled()); - ConfigParams advertisement = getPlatformConfig(); - OutputStream out = null; - - try { - if ("file".equalsIgnoreCase(storeHome.getScheme())) { - File saveDir = new File(storeHome); - saveDir.mkdirs(); - - // Sadly we can't use URL.openConnection() to create the - // OutputStream for file:// URLs. bogus. - out = new FileOutputStream(new File(saveDir, "PlatformConfig")); - } else { - out = storeHome.resolve("PlatformConfig").toURL().openConnection().getOutputStream(); - } - - XMLDocument aDoc = (XMLDocument) advertisement.getDocument(MimeMediaType.XMLUTF8); - OutputStreamWriter os = new OutputStreamWriter(out, "UTF-8"); - aDoc.sendToWriter(os); - os.flush(); - } finally { - if (null != out) { - out.close(); - } - } - } - - /** - * Returns a XMLDocument representation of an Advertisement - * - * @param enabled whether the param doc is enabled, adds a "isOff" - * element if disabled - * @param adv the Advertisement to retrieve the param doc from - * @return the parmDoc value - */ - protected XMLDocument getParmDoc(boolean enabled, Advertisement adv) { - XMLDocument parmDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - XMLDocument doc = (XMLDocument) adv.getDocument(MimeMediaType.XMLUTF8); - - StructuredDocumentUtils.copyElements(parmDoc, parmDoc, doc); - if (!enabled) { - parmDoc.appendChild(parmDoc.createElement("isOff")); - } - return parmDoc; - } - - /** - * Creates an HTTP transport advertisement - * - * @return an HTTP transport advertisement - */ - protected HTTPAdv createHttpAdv() { - httpConfig = (HTTPAdv) AdvertisementFactory.newAdvertisement(HTTPAdv.getAdvertisementType()); - httpConfig.setProtocol("http"); - httpConfig.setPort(9700); - httpConfig.setClientEnabled((mode & HTTP_CLIENT) == HTTP_CLIENT); - httpConfig.setServerEnabled((mode & HTTP_SERVER) == HTTP_SERVER); - return httpConfig; - } - - /** - * Creates Personal Security Environment Config Advertisement - *

      The configuration advertisement can include an optional seed certificate - * chain and encrypted private key. If this seed information is present the PSE - * Membership Service will require an initial authentication to unlock the - * encrypted private key before creating the PSE keystore. The newly created - * PSE keystore will be "seeded" with the certificate chain and the private key. - * - * @param principal principal - * @param password the password used to sign the private key of the root certificate - * @return PSEConfigAdv an PSE config advertisement - * @see net.jxta.impl.protocol.PSEConfigAdv - */ - protected PSEConfigAdv createPSEAdv(String principal, String password) { - pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType()); - if (principal != null && password != null) { - IssuerInfo info = PSEUtils.genCert(principal, null); - - pseConf.setCertificate(info.cert); - pseConf.setPrivateKey(info.subjectPkey, password.toCharArray()); - } - return pseConf; - } - - /** - * Creates Personal Security Environment Config Advertisement - *

      The configuration advertisement can include an optional seed certificate - * chain and encrypted private key. If this seed information is present the PSE - * Membership Service will require an initial authentication to unlock the - * encrypted private key before creating the PSE keystore. The newly created - * PSE keystore will be "seeded" with the certificate chain and the private key. - * - * @param cert X509Certificate - * @return PSEConfigAdv an PSE config advertisement - * @see net.jxta.impl.protocol.PSEConfigAdv - */ - protected PSEConfigAdv createPSEAdv(X509Certificate cert) { - pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType()); - if (subjectPkey != null && password != null) { - pseConf.setCertificate(cert); - pseConf.setPrivateKey(subjectPkey, password.toCharArray()); - } - return pseConf; - } - - /** - * Creates Personal Security Environment Config Advertisement - *

      The configuration advertisement can include an optional seed certificate - * chain and encrypted private key. If this seed information is present the PSE - * Membership Service will require an initial authentication to unlock the - * encrypted private key before creating the PSE keystore. The newly created - * PSE keystore will be "seeded" with the certificate chain and the private key. - * - * @param certificateChain X509Certificate[] - * @return PSEConfigAdv an PSE config advertisement - * @see net.jxta.impl.protocol.PSEConfigAdv - */ - protected PSEConfigAdv createPSEAdv(X509Certificate[] certificateChain) { - pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType()); - if (subjectPkey != null && password != null) { - pseConf.setCertificateChain(certificateChain); - pseConf.setPrivateKey(subjectPkey, password.toCharArray()); - } - return pseConf; - } - - /** - * Creates a ProxyService configuration advertisement - * - * @return ProxyService configuration advertisement - */ - protected XMLDocument createProxyAdv() { - return (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - } - - /** - * Creates a RendezVousService configuration advertisement with default values (EDGE) - * - * @return a RdvConfigAdv - */ - protected RdvConfigAdv createRdvConfigAdv() { - rdvConfig = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType()); - if (mode == RDV_AD_HOC) { - rdvConfig.setConfiguration(RendezVousConfiguration.AD_HOC); - } else if ((mode & RDV_CLIENT) == RDV_CLIENT) { - rdvConfig.setConfiguration(RendezVousConfiguration.EDGE); - } else if ((mode & RDV_SERVER) == RDV_SERVER) { - rdvConfig.setConfiguration(RendezVousConfiguration.RENDEZVOUS); - } - // A better alternative is to reference rdv service defaults (currently private) - // rdvConfig.setMaxClients(200); - return rdvConfig; - } - - /** - * Creates a RelayService configuration advertisement with default values (EDGE) - * - * @return a RelayConfigAdv - */ - protected RelayConfigAdv createRelayConfigAdv() { - relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(RelayConfigAdv.getAdvertisementType()); - relayConfig.setUseOnlySeeds(false); - relayConfig.setClientEnabled((mode & RELAY_CLIENT) == RELAY_CLIENT || mode == EDGE_NODE); - relayConfig.setServerEnabled((mode & RELAY_SERVER) == RELAY_SERVER); - return relayConfig; - } - - /** - * Creates an TCP transport advertisement with the platform default values. - * multicast on, 224.0.1.85:1234, with a max packet size of 16K - * - * @return a TCP transport advertisement - */ - protected TCPAdv createTcpAdv() { - tcpConfig = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType()); - tcpConfig.setProtocol("tcp"); - tcpConfig.setInterfaceAddress(null); - tcpConfig.setPort(9701); - tcpConfig.setStartPort(9701); - tcpConfig.setEndPort(9799); - tcpConfig.setMulticastAddr("224.0.1.85"); - tcpConfig.setMulticastPort(1234); - tcpConfig.setMulticastSize(16384); - tcpConfig.setMulticastState((mode & IP_MULTICAST) == IP_MULTICAST); - tcpConfig.setServer(null); - tcpConfig.setClientEnabled((mode & TCP_CLIENT) == TCP_CLIENT); - tcpConfig.setServerEnabled((mode & TCP_SERVER) == TCP_SERVER); - return tcpConfig; - } - - protected PeerGroupConfigAdv createInfraConfigAdv() { - infraPeerGroupConfig = (PeerGroupConfigAdv) AdvertisementFactory.newAdvertisement( - PeerGroupConfigAdv.getAdvertisementType()); - - NetGroupTunables tunables = new NetGroupTunables(ResourceBundle.getBundle("net.jxta.impl.config"), new NetGroupTunables()); - - infraPeerGroupConfig.setPeerGroupID(tunables.id); - infraPeerGroupConfig.setName(tunables.name); - infraPeerGroupConfig.setDesc(tunables.desc); - - return infraPeerGroupConfig; - } - - /** - * Returns a PlatformConfig which represents a platform configuration. - *

      Fine tuning is achieved through accessing each configured advertisement - * and achieved through accessing each configured advertisement and modifying - * each object directly. - * - * @return the PeerPlatformConfig Advertisement - */ - public ConfigParams getPlatformConfig() { - PlatformConfig advertisement = (PlatformConfig) AdvertisementFactory.newAdvertisement( - PlatformConfig.getAdvertisementType()); - - advertisement.setName(name); - advertisement.setDescription(description); - if (peerid != null) { - advertisement.setPeerID(peerid); - } - - if (tcpConfig != null) { - boolean enabled = tcpEnabled && (tcpConfig.isServerEnabled() || tcpConfig.isClientEnabled()); - advertisement.putServiceParam(PeerGroup.tcpProtoClassID, getParmDoc(enabled, tcpConfig)); - } - - if (httpConfig != null) { - boolean enabled = httpEnabled && (httpConfig.isServerEnabled() || httpConfig.isClientEnabled()); - advertisement.putServiceParam(PeerGroup.httpProtoClassID, getParmDoc(enabled, httpConfig)); - } - - if (relayConfig != null) { - boolean isOff = ((mode & RELAY_OFF) == RELAY_OFF) || (relayConfig.isServerEnabled() && relayConfig.isClientEnabled()); - XMLDocument relayDoc = (XMLDocument) relayConfig.getDocument(MimeMediaType.XMLUTF8); - - if (isOff) { - relayDoc.appendChild(relayDoc.createElement("isOff")); - } - advertisement.putServiceParam(PeerGroup.relayProtoClassID, relayDoc); - } - - if (rdvConfig != null) { - XMLDocument rdvDoc = (XMLDocument) rdvConfig.getDocument(MimeMediaType.XMLUTF8); - advertisement.putServiceParam(PeerGroup.rendezvousClassID, rdvDoc); - } - - if (cert != null) { - pseConf = createPSEAdv(cert); - } else { - pseConf = createPSEAdv(principal, password); - } - - if (pseConf != null) { - if (keyStoreLocation != null) { - if (keyStoreLocation.isAbsolute()) { - pseConf.setKeyStoreLocation(keyStoreLocation); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Keystore location set, but is not absolute: " + keyStoreLocation); - } - } - } - XMLDocument pseDoc = (XMLDocument) pseConf.getDocument(MimeMediaType.XMLUTF8); - advertisement.putServiceParam(PeerGroup.membershipClassID, pseDoc); - } - - if (proxyConfig != null && ((mode & PROXY_SERVER) == PROXY_SERVER)) { - advertisement.putServiceParam(PeerGroup.proxyClassID, proxyConfig); - } - - if ((null != infraPeerGroupConfig) && (null != infraPeerGroupConfig.getPeerGroupID()) - && (ID.nullID != infraPeerGroupConfig.getPeerGroupID()) - && (PeerGroupID.defaultNetPeerGroupID != infraPeerGroupConfig.getPeerGroupID())) { - advertisement.setSvcConfigAdvertisement(PeerGroup.peerGroupClassID, infraPeerGroupConfig); - } - return advertisement; - } - - /** - * @param location The location of the platform config. - * @return The platformConfig - * @throws IOException Thrown for failures reading the PlatformConfig. - */ - private PlatformConfig read(URI location) throws IOException { - URL url; - - try { - url = location.toURL(); - } catch (MalformedURLException mue) { - IllegalArgumentException failure = new IllegalArgumentException("Failed to convert URI to URL"); - failure.initCause(mue); - throw failure; - } - - InputStream input = url.openStream(); - try { - XMLDocument document = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, input); - PlatformConfig platformConfig = (PlatformConfig) AdvertisementFactory.newAdvertisement(document); - return platformConfig; - } finally { - input.close(); - } - } - - /** - * Holds the construction tunables for the Net Peer Group. This consists of - * the peer group id, the peer group name and the peer group description. - */ - static class NetGroupTunables { - - final ID id; - final String name; - final XMLElement desc; - - /** - * Constructor for loading the default Net Peer Group construction - * tunables. - */ - NetGroupTunables() { - id = PeerGroupID.defaultNetPeerGroupID; - name = "NetPeerGroup"; - desc = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", "default Net Peer Group"); - } - - /** - * Constructor for loading the default Net Peer Group construction - * tunables. - * - * @param pgid the PeerGroupID - * @param pgname the group name - * @param pgdesc the group description - */ - NetGroupTunables(ID pgid, String pgname, XMLElement pgdesc) { - id = pgid; - name = pgname; - desc = pgdesc; - } - - /** - * Constructor for loading the Net Peer Group construction - * tunables from the provided resource bundle. - * - * @param rsrcs The resource bundle from which resources will be loaded. - * @param defaults default values - */ - NetGroupTunables(ResourceBundle rsrcs, NetGroupTunables defaults) { - ID idTmp; - String nameTmp; - XMLElement descTmp; - - try { - String idTmpStr = rsrcs.getString("NetPeerGroupID").trim(); - - if (idTmpStr.startsWith(ID.URNNamespace + ":")) { - idTmpStr = idTmpStr.substring(5); - } - idTmp = IDFactory.fromURI(new URI(ID.URIEncodingName + ":" + ID.URNNamespace + ":" + idTmpStr)); - nameTmp = rsrcs.getString("NetPeerGroupName").trim(); - descTmp = (XMLElement) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "desc", rsrcs.getString("NetPeerGroupDesc").trim()); - } catch (Exception failed) { - if (null != defaults) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "NetPeerGroup tunables not defined or could not be loaded. Using defaults.", failed); - } - - idTmp = defaults.id; - nameTmp = defaults.name; - descTmp = defaults.desc; - } else { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "NetPeerGroup tunables not defined or could not be loaded.", failed); - } - - throw new IllegalStateException("NetPeerGroup tunables not defined or could not be loaded."); - } - } - - id = idTmp; - name = nameTmp; - desc = descTmp; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/NetworkManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/NetworkManager.java deleted file mode 100644 index b11b9e0f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/NetworkManager.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.platform; - - -import javax.security.cert.CertificateException; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.logging.Level; -import java.util.logging.Logger; - -import net.jxta.credential.AuthenticationCredential; -import net.jxta.credential.Credential; -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.ProtocolNotSupportedException; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; -import net.jxta.membership.InteractiveAuthenticator; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.NetPeerGroupFactory; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.rendezvous.RendezvousEvent; -import net.jxta.rendezvous.RendezvousListener; - -import net.jxta.impl.membership.pse.StringAuthenticator; - - -/** - * NetworkManager provides a simplified JXTA platform configuration abstraction, and provides a JXTA platform life-cycle - * management. The node configuration is created during construction of this object and can be obtained for fine tuning - * or alteration. Note that all alterations must be done prior to calling #startNetwork(), otherwise the default - * configuration is used. Configuration persistence is on by default and maybe overridden by call to #setEnableConfigPersistence - *

      - * NetworkManager defines six abstractions of a node configurations as follows : - * ADHOC : A node which typically deployed in an ad-hoc network - * EDGE : In addition to supporting ADHOC function, an Edge node can attach to a infrastructure (a Rendezvous, Relay, or both) - * RENDEZVOUS: provides network bootstrapping services, such as discovery, pipe resolution, etc. - * RELAY: provides message relaying services, enabling cross firewall traversal - * PROXY: provide JXME JXTA for J2ME proxying services - * SUPER: provide the functionality of a Rendezvous, Relay, Proxy node. - */ -public class NetworkManager implements RendezvousListener { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(NetworkManager.class.getName()); - - protected final transient URI publicSeedingRdvURI = URI.create("http://rdv.jxtahosts.net/cgi-bin/rendezvous.cgi?3"); - protected final transient URI publicSeedingRelayURI = URI.create("http://rdv.jxtahosts.net/cgi-bin/relays.cgi?3"); - - /** - * Define node standard node operating modes - */ - public enum ConfigMode { - - /** - * A AD-HOC node - */ - ADHOC, - /** - * A Edge node - */ - EDGE, - /** - * A Rendezvous node - */ - RENDEZVOUS, - /** - * A Relay node - */ - RELAY, - /** - * Rendezvous and a Relay - */ - RENDEZVOUS_RELAY, - /** - * JXME Proxy node - */ - PROXY, - /** - * A Rendezvous, Relay, and JXME Proxy node - */ - SUPER - } - - private final Object networkConnectLock = new String("rendezvous connection lock"); - private PeerGroup netPeerGroup = null; - private volatile boolean started = false; - private volatile boolean connected = false; - private volatile boolean stopped = false; - private RendezVousService rendezvous; - private String instanceName = "NA"; - private ShutdownHook shutdownHook; - private ConfigMode mode; - private URI instanceHome; - private PeerGroupID infrastructureID = PeerGroupID.defaultNetPeerGroupID; - private PeerID peerID = IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID); - private NetworkConfigurator config; - private boolean configPersistent = true; - private boolean useDefaultSeeds; - - /** - * Creates NetworkManger instance with default instance home set to "$CWD"/.jxta" - * At this point, alternate Infrastructure PeerGroupID maybe specified, as well as a PeerID. if neither are - * specified, the default NetPeerGroupID will be used, and a new PeerID will be generated. Also note the default - * seeding URIs are the to development. Alternate values must be specified, if desired, prior to a call to {@link #startNetwork} - * - * @param mode Operating mode the node operating {@link ConfigMode} - * @param instanceName Node name - * @throws IOException if an io error occurs - */ - public NetworkManager(ConfigMode mode, String instanceName) throws IOException { - this(mode, instanceName, new File(".jxta/").toURI()); - } - - /** - * Creates NetworkManger instance. - * At this point, alternate Infrastructure PeerGroupID maybe specified, as well as a PeerID. if neither are - * specified, the default NetPeerGroupID will be used, and a new PeerID will be generated. Also note the default - * seeding URIs are the to development. Alternate values must be specified, if desired, prior to a call to {@link #startNetwork} - * - * @param mode Operating mode the node operating {@link ConfigMode} - * @param instanceName Node name - * @param instanceHome instance home is a uri to the instance persistent store (aka Cache Manager store home) - * @throws IOException if an io error occurs - */ - public NetworkManager(ConfigMode mode, String instanceName, URI instanceHome) throws IOException { - this.instanceName = instanceName; - this.mode = mode; - this.instanceHome = instanceHome; - } - - /** - * Returns the {@link NetworkConfigurator} for additional tuning - * - * @return the {@link NetworkConfigurator} for additional tuning - * @throws java.io.IOException if an io error occurs - */ - public synchronized NetworkConfigurator getConfigurator() throws IOException { - if (config == null) { - configure(mode); - } - return config; - } - - /** - * Getter for property 'infrastructureID'. - * - * @return Value for property 'infrastructureID'. - */ - public PeerGroupID getInfrastructureID() { - return infrastructureID; - } - - /** - * Setter for property 'infrastructureID'. - * - * @param infrastructureID Value to set for property 'infrastructureID'. - */ - public void setInfrastructureID(PeerGroupID infrastructureID) { - this.infrastructureID = infrastructureID; - if (config != null) { - config.setInfrastructureID(infrastructureID); - } - } - - /** - * Getter for property 'instanceName'. - * - * @return Value for property 'instanceName'. - */ - public String getInstanceName() { - return instanceName; - } - - /** - * Setter for property 'instanceName'. - * - * @param instanceName Value to set for property 'instanceName'. - */ - public void setInstanceName(String instanceName) { - this.instanceName = instanceName; - } - - /** - * Getter for property 'instanceHome'. - * - * @return Value for property 'instanceHome'. - */ - public URI getInstanceHome() { - return instanceHome; - } - - /** - * Setter for property 'instanceHome'. - * - * @param instanceHome Value to set for property 'instanceHome'. - */ - public void setInstanceHome(URI instanceHome) { - this.instanceHome = instanceHome; - } - - /** - * Getter for property node operating 'mode'. - * - * @return Value for property 'mode'. - */ - public ConfigMode getMode() { - return mode; - } - - /** - * Setter for property 'mode'. - * - * @param mode Value to set for property 'mode'. - * @throws IOException if an io error occurs - */ - public void setMode(ConfigMode mode) throws IOException { - this.mode = mode; - configure(mode); - } - - /** - * Getter for property 'peerID'. - * - * @return Value for property 'peerID'. - */ - public PeerID getPeerID() { - return peerID; - } - - /** - * Setter for property 'peerID'. - * - * @param peerID Value to set for property 'peerID'. - */ - public void setPeerID(PeerID peerID) { - this.peerID = peerID; - } - - /** - * Getter for property 'configPersistent'. - * - * @return Value for property 'configPersistent'. - */ - public boolean isConfigPersistent() { - return configPersistent; - } - - /** - * Setter for property 'configPersistent'. if disabled a PlatformConfig is not persisted. It assumed that - * the PeerID is will be set, or a new PeerID will always be generated. - * - * @param persisted Value to set for property 'configPersistent'. - */ - public void setConfigPersistent(boolean persisted) { - this.configPersistent = persisted; - } - - private void configure(ConfigMode mode) throws IOException { - switch (mode) { - case ADHOC: - config = NetworkConfigurator.newAdHocConfiguration(instanceHome); - break; - - case EDGE: - config = NetworkConfigurator.newEdgeConfiguration(instanceHome); - break; - - case RENDEZVOUS: - config = NetworkConfigurator.newRdvConfiguration(instanceHome); - break; - - case RELAY: - config = NetworkConfigurator.newRelayConfiguration(instanceHome); - break; - - case RENDEZVOUS_RELAY: - config = NetworkConfigurator.newRdvRelayConfiguration(instanceHome); - break; - - case PROXY: - config = NetworkConfigurator.newProxyConfiguration(instanceHome); - break; - - case SUPER: - config = NetworkConfigurator.newRdvRelayProxyConfiguration(instanceHome); - break; - - default: - config = NetworkConfigurator.newAdHocConfiguration(instanceHome); - } - if (!config.exists()) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "Created new configuration. mode = " + mode.toString()); - } - - config.setDescription("Created by NetworkManager"); - config.setPeerID(peerID); - config.setInfrastructureID(infrastructureID); - config.setName(instanceName); - if (useDefaultSeeds) { - config.addRdvSeedingURI(publicSeedingRdvURI); - config.addRelaySeedingURI(publicSeedingRelayURI); - } - } else { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "Loading existing configuration. mode = " + mode.toString()); - } - - File pc = new File(config.getHome(), "PlatformConfig"); - - try { - config.load(pc.toURI()); - } catch (CertificateException pseFailed) { - IOException failure = new IOException("Failure reading membership service certificates."); - - failure.initCause(pseFailed); - throw failure; - } - - // XXX 20070524 bondolo Aren't we completely ignoring the mode? What if it changed? - // 20070614 hamada Good question, this feature is postponed due to the difficulty of comparing a stored/requested modes. - } - } - - /** - * Creates and starts the JXTA infrastructure peer group (aka NetPeerGroup) based on the specified mode - * template. This class also registers a listener for rendezvous events. - * - * @return The Net Peer Group - * @throws net.jxta.exception.PeerGroupException - * if the group fails to initialize - * @throws java.io.IOException if an io error occurs - */ - public synchronized PeerGroup startNetwork() throws PeerGroupException, IOException { - - if (started) { - return netPeerGroup; - } - - if (config == null) { - configure(mode); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "Starting JXTA Network! MODE = " + mode.toString() + ", HOME = " + instanceHome); - } - - // create, and Start the default jxta NetPeerGroup - NetPeerGroupFactory factory = new NetPeerGroupFactory(config.getPlatformConfig(), instanceHome); - - netPeerGroup = factory.getInterface(); - - if (configPersistent) { - config.save(); - } - - rendezvous = netPeerGroup.getRendezVousService(); - rendezvous.addListener(this); - started = true; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "Started JXTA Network!"); - } - - return netPeerGroup; - } - - /** - * Establishes group credential. This is a required step when planning to - * to utilize TLS messengers or secure pipes - * - * @param group peer group to establish credentials in - * @param keystore_password The passphrase for the keystore. This is a - * char[] rather than a String so that it can be blanked after use. - * @param principal_password The passphrase for the identity. This is a - * char[] rather than a String so that it can be blanked after use. - * @throws net.jxta.exception.PeerGroupException - * if group credentials were rejected - * @throws net.jxta.exception.ProtocolNotSupportedException - * if authenticator rejected the credential - */ - public static void login(PeerGroup group, char[] keystore_password, char[] principal_password) throws PeerGroupException, ProtocolNotSupportedException { - StringAuthenticator auth; - MembershipService membership = group.getMembershipService(); - Credential cred = membership.getDefaultCredential(); - - if (cred == null) { - AuthenticationCredential authCred = new AuthenticationCredential(group, "StringAuthentication", null); - - auth = (StringAuthenticator) membership.apply(authCred); - if (auth != null) { - auth.setAuth1_KeyStorePassword(keystore_password); - auth.setAuth2Identity(group.getPeerID()); - auth.setAuth3_IdentityPassword(principal_password); - if (auth.isReadyForJoin()) { - membership.join(auth); - } - } - } - - cred = membership.getDefaultCredential(); - if (null == cred) { - AuthenticationCredential authCred = new AuthenticationCredential(group, "InteractiveAuthentication", null); - InteractiveAuthenticator iAuth = (InteractiveAuthenticator) membership.apply(authCred); - - if (iAuth.interact() && iAuth.isReadyForJoin()) { - membership.join(iAuth); - } - } - } - - /** - * Stops and unreferences the NetPeerGroup - */ - public synchronized void stopNetwork() { - if (stopped || !started) { - return; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "Stopping JXTA Network!"); - } - - stopped = true; - synchronized(networkConnectLock) { - connected = false; - networkConnectLock.notifyAll(); - } - - rendezvous.removeListener(this); - netPeerGroup.stopApp(); - netPeerGroup.unref(); - netPeerGroup = null; - // permit restart. - started = false; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "Stopped JXTA Network!"); - } - } - - /** - * Gets the netPeerGroup object - * - * @return The netPeerGroup value - */ - public PeerGroup getNetPeerGroup() { - return netPeerGroup; - } - - /** - * Blocks only, if not connected to a rendezvous, or until a connection to rendezvous node occurs. - * - * @param timeout timeout in milliseconds, a zero timeout of waits forever - * @return true if connected to a rendezvous, false otherwise - */ - public boolean waitForRendezvousConnection(long timeout) { - if (0 == timeout) { - timeout = Long.MAX_VALUE; - } - - long timeoutAt = System.currentTimeMillis() + timeout; - - if (timeoutAt <= 0) { - // handle overflow. - timeoutAt = Long.MAX_VALUE; - } - - while (started && !stopped && !rendezvous.isConnectedToRendezVous() && !rendezvous.isRendezVous()) { - try { - long waitFor = timeoutAt - System.currentTimeMillis(); - - if (waitFor > 0) { - synchronized (networkConnectLock) { - networkConnectLock.wait(timeout); - } - } else { - // all done with waiting. - break; - } - } catch (InterruptedException e) { - Thread.interrupted(); - break; - } - } - - return rendezvous.isConnectedToRendezVous() || rendezvous.isRendezVous(); - } - - /** - * rendezvousEvent the rendezvous event - * - * @param event rendezvousEvent - */ - public void rendezvousEvent(RendezvousEvent event) { - if (event.getType() == RendezvousEvent.RDVCONNECT || event.getType() == RendezvousEvent.RDVRECONNECT - || event.getType() == RendezvousEvent.BECAMERDV) { - synchronized (networkConnectLock) { - connected = true; - networkConnectLock.notifyAll(); - } - } - } - - /** - * if true uses the public rendezvous seeding service - * - * @param useDefaultSeeds if true uses the default development seeding service - */ - public void setUseDefaultSeeds(boolean useDefaultSeeds) { - this.useDefaultSeeds = useDefaultSeeds; - } - - /** - * Returns true if useDefaultSeeds is set to true - * - * @return true if useDefaultSeeds is set to true - */ - public boolean getUseDefaultSeeds() { - return useDefaultSeeds; - } - - /** - * Registers a Runtime shutdown hook to cleanly shutdown the JXTA platform - */ - public synchronized void registerShutdownHook() { - if (shutdownHook != null) { - return; - } - shutdownHook = new NetworkManager.ShutdownHook(); - Runtime.getRuntime().addShutdownHook(shutdownHook); - } - - /** - * Unregisters a Runtime shutdown hook to cleanly shutdown the JXTA platform - */ - public synchronized void unregisterShutdownHook() { - - if (shutdownHook == null) { - return; - } - Runtime.getRuntime().removeShutdownHook(shutdownHook); - shutdownHook = null; - } - - private class ShutdownHook extends Thread { - - /** - * {@inheritDoc} - */ - @Override - public void run() { - stopNetwork(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/package.html deleted file mode 100644 index c839dfd0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/platform/package.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Classes for defining code modules within JXTA. Modules are used for services - and applications within JXTA. Also provides utilities for configuring and - managing JXTA start-up and shutdown. - - @see net.jxta.id.ID - @see JXTA Protocols Specification : IDs - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/AccessPointAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/AccessPointAdvertisement.java deleted file mode 100644 index 6964fafb..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/AccessPointAdvertisement.java +++ /dev/null @@ -1,387 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import java.util.Collection; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.peer.PeerID; - -import java.util.Enumeration; -import java.util.List; -import java.util.Vector; - - -/** - * Provides a simple association of a {@code PeerID} to an ordered list of - * {@code EndpointAddress} entries. Each {@code EndpointAddress} defines one - * Message Transport address by which the peer may be reached. The addresses - * are sorted in the preferred order (which may refer to performance, cost, - * efficiency, etc.) which they should be used. - *

      - * The Access Point Advertisement is most commonly used as part of other - * Advertisements such as {@code RouteAdvertisement}. - * - * @see net.jxta.protocol.PeerAdvertisement - * @see net.jxta.protocol.RouteAdvertisement - */ -public abstract class AccessPointAdvertisement extends ExtendableAdvertisement implements Cloneable { - - /** - * The peer id of the peer with these endpoints. May be {@code null} - * if the APA is used as a sub-element of a structure in which the context - * peerid is already known. - */ - private PeerID pid = null; - - /** - * The EndpointAddresses associated with the specified peer in preferred - * order. - *

      - *

        - *
      • Values are, sadly, {@link java.lang.String} of - * {@link net.jxta.endpoint.EndpointAddress}.
      • - *
      - */ - private Vector endpointAddresses = new Vector(); - - /** - * {@inheritDoc} - *

      - *

      Make a deep copy. - */ - @Override - public AccessPointAdvertisement clone() { - try { - AccessPointAdvertisement a = (AccessPointAdvertisement) super.clone(); - - a.setPeerID(getPeerID()); - a.addEndpointAddresses(endpointAddresses); - - return a; - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - } - - /** - * {@inheritDoc} - *

      - * Equals means the same PID and the same endpoint addresses. - */ - @Override - public boolean equals(Object target) { - - if (this == target) { - return true; - } - - if (!(target instanceof AccessPointAdvertisement)) { - return false; - } - - AccessPointAdvertisement ap = (AccessPointAdvertisement) target; - - if ((null == getPeerID()) && (null != ap.getPeerID())) { - return false; - } - - if ((null != getPeerID())) { - if (!getPeerID().equals(ap.getPeerID())) { - return false; - } - } - if (endpointAddresses.size() != ap.endpointAddresses.size()) { - return false; - } - - // XXX 20061127 bondolo This eventually should be an ordered comparison. - - for (String anEA : endpointAddresses) { - if (!ap.endpointAddresses.contains(anEA)) { - return false; - } - } - - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - if (null != pid) { - return pid.hashCode(); - } else { - // force all incomplete advertisements to hash to the same place. - return 1; - } - } - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:APA"; - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * Gets the PeerID for this access point. - * - * @return PeerID The peer id associated with the endpoint addresses or - * {@code null} if no peer has been directly associated. - */ - public PeerID getPeerID() { - return pid; - } - - /** - * Sets the PeerID for this access point. - * - * @param pid The peer id associated with the endpoint addresses or - * {@code null} if no peer is directly associated. - */ - public void setPeerID(PeerID pid) { - this.pid = pid; - } - - /** - * Add all of the provided EndpointAddresses. - * - * @param addrs Add all of the specified endpoint addresses. - */ - public void addEndpointAddresses(List addrs) { - for (EndpointAddress addr : addrs) { - addEndpointAddress(addr); - } - } - - /** - * Clears all EndpointAddresses. - */ - public void clearEndpointAddresses() { - endpointAddresses.clear(); - } - - /** - * Remove the specified EndpointAddress. - * - * @param addr EndpointAddress to remove. - */ - public void removeEndpointAddress(EndpointAddress addr) { - endpointAddresses.remove(addr.toString()); - } - - /** - * Remove the specified EndpointAddresses. - * - * @param addrs EndpointAddresses to remove. - */ - public void removeEndpointAddresses(Collection addrs) { - for (EndpointAddress addr : addrs) { - endpointAddresses.remove(addr.toString()); - } - } - - /** - * Returns the endpoint addresses associated with this access point. - * - * @return The endpoint addresses associated with this access point - * represented as {@link java.lang.String}. - */ - public Enumeration getEndpointAddresses() { - return endpointAddresses.elements(); - } - - /** - * Returns the vector of endpoint addresses associated with this access - * point. The result is a vector of endpoint addresses represented as - * {@code String}. The Vector contains the "live" data of this - * advertisement. It should be modified only with great care. - * - * @return The endpoint addresses associated with this access point - * represented as {@link java.lang.String}. - * @deprecated Returning the Vector is dangerous and unwise. This feature - * will be removed. - */ - @Deprecated - public Vector getVectorEndpointAddresses() { - return endpointAddresses; - } - - /** - * Sets the list of endpoint addresses associated with this access point. - * - * @param addresses Vector of EndpointAddresses represented as - * {@link java.lang.String}. The Vector is not copied! - * @deprecated This method causes the AccessPointAdvertisement to reference - * the provided array. This means that subsequent changes to the array will - * alter the endpoint addresses which are part of the - * {@code AcccessPointAdvertisement}. - */ - @Deprecated - public void setEndpointAddresses(Vector addresses) { - endpointAddresses = addresses; - } - - /** - * Add a new list of EndpointAddresses to the access point. - * - * @param addresses List of EndpointAddresses represented as - * {@link java.lang.String}. - * - * @deprecated Use {@link #addEndpointAddresses(List)} instead. - */ - @Deprecated - public void addEndpointAddresses(Vector addresses) { - for (String toAdd : addresses) { - addEndpointAddress(toAdd); - } - } - - /** - * Add a new EndpointAddresses to the access point - * - * @param address An EndpointAddress - */ - public void addEndpointAddress(EndpointAddress address) { - String toAdd = address.toString(); - - if (!endpointAddresses.contains(toAdd)) { - endpointAddresses.add(toAdd); - } - } - - /** - * add a new EndpointAddresses to the access point - * - * @param address EndpointAddress represented as {@link java.lang.String}. - */ - public void addEndpointAddress(String address) { - if (!endpointAddresses.contains(address)) { - endpointAddresses.add(address); - } - } - - /** - * remove a list of EndpointAddresses from the access point - * - * @param addresses List of EndpointAddresses represented as - * {@link java.lang.String}. - */ - public void removeEndpointAddresses(List addresses) { - endpointAddresses.removeAll(addresses); - } - - /** - * return number of endpoint addresses - * - * @return size number of endpointAddress in the hop - */ - public int size() { - return endpointAddresses.size(); - } - - /** - * Check if the EndpointAddress is already associated with this access point - * - * @param addr endpoint address to check - * @return true if the EndpointAddress is already associated with this access point - */ - public boolean contains(EndpointAddress addr) { - return endpointAddresses.contains(addr.toString()); - } - - /** - * Generate a string that displays an access point - * information for logging or debugging purpose - * - * @return String return a string containing the access point advertisement - */ - public String display() { - StringBuilder routeBuf = new StringBuilder(); - - routeBuf.append("PID="); - - PeerID peerId = getPeerID(); - - if (peerId == null) { - routeBuf.append(""); - } else { - routeBuf.append(peerId.toString()); - } - - Enumeration e = getEndpointAddresses(); - - while (e.hasMoreElements()) { - routeBuf.append("\n Addr=").append(e.nextElement()); - } - return routeBuf.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ConfigParams.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ConfigParams.java deleted file mode 100644 index 05cea09c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ConfigParams.java +++ /dev/null @@ -1,587 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.*; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; - - -/** - * A container for collections of configuration parameters. Configuration - * parameters are stored in a Map which is keyed by {@code JXTA ID}s and whose - * values are {@code Advertisement}s. - */ -public abstract class ConfigParams extends ExtendableAdvertisement implements Cloneable { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(ConfigParams.class.getName()); - - private static final String SVC_TAG = "Svc"; - private static final String MCID_TAG = "MCID"; - private static final String PARAM_TAG = "Parm"; - - /** - * A table of structured documents to be interpreted by each service. - * For safe operation these elements should be immutable, but we're helpless - * if they are not. - */ - private final Map params = new HashMap(); - - /** - * A map of advertisements to be interpreted by each service. - * For safe operation we clone the advertisements when they are added to the - * map and only ever return clones of the advertisements. - */ - private final Map ads = new HashMap(); - - /** - * The ids of the advertisements and/or params which have been explicitly - * marked as disabled. - */ - private final Set disabled = new HashSet(); - - /** - * Counts the changes made to this object. The API increments it every time - * some change is not proven to be idempotent. We rely on implementations to - * increment modCount every time something is changed without going through - * the API. - */ - protected final transient AtomicInteger modCount = new AtomicInteger(0); - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:CP"; - } - - /** - * Default Constructor. We want all ConfigParams derived advertisements to - * pretty print. - */ - protected ConfigParams() { - super(true); - } - - /** - * {@inheritDoc} - */ - @Override - public ConfigParams clone() { - - try { - ConfigParams result = (ConfigParams) super.clone(); - - for (Map.Entry anEntry : params.entrySet()) { - result.params.put(anEntry.getKey(), StructuredDocumentUtils.copyAsDocument(anEntry.getValue())); - } - - for (Map.Entry anEntry : ads.entrySet()) { - result.ads.put(anEntry.getKey(), anEntry.getValue().clone()); - } - - result.disabled.addAll(disabled); - - return result; - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object other) { - if(this == other) { - return true; - } - - if(other instanceof ConfigParams) { - ConfigParams likeMe = (ConfigParams) other; - - boolean ep = params.equals(likeMe.params); - boolean ea = ads.equals(likeMe.ads); - boolean ed = disabled.equals(likeMe.disabled); - - return ep && ea && ed; - } - - return false; - } - - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (SVC_TAG.equals(elem.getName())) { - Attribute disabledAttr = elem.getAttribute("disabled"); - boolean isDisabled = (null != disabledAttr) && Boolean.parseBoolean(disabledAttr.getValue()); - - Enumeration elems = elem.getChildren(); - - ID key = null; - XMLElement param = null; - - while (elems.hasMoreElements()) { - XMLElement e = elems.nextElement(); - - if (MCID_TAG.equals(e.getName())) { - try { - URI mcid = new URI(e.getTextValue()); - - key = IDFactory.fromURI(mcid); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad ID in advertisement: " + e.getTextValue()); - } - } else if (PARAM_TAG.equals(e.getName())) { - param = e; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unrecognized tag : " + e.getName()); - } - } - } - - if (key != null && param != null) { - if(!isDisabled) { - // Backwards compatibility support. - Enumeration isOff = param.getChildren("isOff"); - - isDisabled = isOff.hasMoreElements(); - } - - putServiceParam(key, param); - if(isDisabled) { - disabled.add(key); - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Incomplete Service Param : id=" + key + " param=" + param); - } - - return false; - } - return true; - } - return false; - } - - /** - * Return the advertisement as a document. - * - * @param adv the document to add elements to. - * @return true if elements were added otherwise false. - */ - public boolean addDocumentElements(StructuredDocument adv) { - - for (Map.Entry anEntry : params.entrySet()) { - ID anID = anEntry.getKey(); - StructuredDocument aDoc = anEntry.getValue(); - - Element s = adv.createElement(SVC_TAG); - - adv.appendChild(s); - - if(disabled.contains(anID)) { - ((Attributable)s).addAttribute("disabled", "true"); - } - - Element e = adv.createElement(MCID_TAG, anID.toString()); - - s.appendChild(e); - - StructuredDocumentUtils.copyElements(adv, s, aDoc, PARAM_TAG); - } - - for (Map.Entry anEntry : ads.entrySet()) { - ID anID = anEntry.getKey(); - Advertisement anAdv = anEntry.getValue(); - - Element s = adv.createElement(SVC_TAG); - - adv.appendChild(s); - - if(disabled.contains(anID)) { - ((Attributable)s).addAttribute("disabled", "true"); - } - - Element e = adv.createElement(MCID_TAG, anID.toString()); - - s.appendChild(e); - - StructuredDocument asDoc = (StructuredDocument) anAdv.getDocument(adv.getMimeType()); - - StructuredDocumentUtils.copyElements(adv, s, asDoc, PARAM_TAG); - } - - return true; - } - - /** - * Returns the number of times this object has been modified since it was - * created. This permits the detection of local changes that require - * refreshing some other data. - * - * @return int the current modification count. - */ - public int getModCount() { - return modCount.get(); - } - - /** - * Increases the modification count of this instance. - * - * @return modification count - */ - protected synchronized int incModCount() { - return modCount.incrementAndGet(); - } - - /** - * Puts a service parameter in the service parameters table - * under the given key. The key is usually a ModuleClassID. This method - * makes a clone of the given element into an independent document. - * - * @param key The key. - * @param param The parameter document. - */ - public void putServiceParam(ID key, Element param) { - incModCount(); - - params.remove(key); - ads.remove(key); - - if (param == null) { - return; - } - - boolean isDisabled = false; - - if (param instanceof XMLElement) { - Enumeration isOff = param.getChildren("isOff"); - - isDisabled = isOff.hasMoreElements(); - - Advertisement adv = null; - - try { - adv = AdvertisementFactory.newAdvertisement((XMLElement) param); - } catch (RuntimeException ignored) { - // ignored - ; - } - - if (null != adv) { - setSvcConfigAdvertisement(key,adv, !isDisabled); - return; - } - } - - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(param); - - if(isDisabled) { - disabled.add(key); - } else { - disabled.remove(key); - } - - params.put(key, newDoc); - } - - - /** - * Puts an advertisement into the service parameters table under the given - * key. The key is usually a {@code ModuleClassID}. This method makes a - * clone of the advertisement. - * - * @param key The key. - * @param adv The advertisement, a clone of which is stored or {@code null} - * to forget this key. - */ - public void setSvcConfigAdvertisement(ID key, Advertisement adv) { - setSvcConfigAdvertisement(key, adv, true); - } - - /** - * Puts an advertisement into the service parameters table under the given - * key. The key is usually a {@code ModuleClassID}. This method makes a - * clone of the advertisement. - * - * @param key The key. - * @param adv The advertisement, a clone of which is stored or {@code null} - * to forget this key. - * @param enabled If true then the service is enabled or disabled if false. - */ - public void setSvcConfigAdvertisement(ID key, Advertisement adv, boolean enabled) { - incModCount(); - - params.remove(key); - ads.remove(key); - - if(enabled) { - disabled.remove(key); - } else { - disabled.add(key); - } - - if (null == adv) { - return; - } - - try { - ads.put(key, adv.clone()); - } catch (CloneNotSupportedException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Unclonable Advertisements may not be used : " + adv.getClass().getName(), failed); - } - - throw new IllegalArgumentException("Unclonable Advertisements may not be used : " + adv.getClass().getName()); - } - } - - /** - * Gets an advertisement from the service parameters table under the given - * key. The key is usually a {@code ModuleClassID}. This method makes a - * clone of the advertisement. - * - * @param key The key. - * @return If {@code true} then the service is enabled otherwise {@false} if - * the service is disabled. - */ - public boolean isSvcEnabled(ID key) { - return !disabled.contains(key); - } - - /** - * Gets an advertisement from the service parameters table under the given - * key. The key is usually a {@code ModuleClassID}. This method makes a - * clone of the advertisement. - * - * @param key The key. - * @return The advertisement for the specified key otherwise {@code null}. - */ - public Advertisement getSvcConfigAdvertisement(ID key) { - Advertisement adv = ads.get(key); - - if (null == adv) { - if (params.containsKey(key)) { - throw new IllegalStateException("Unable to return advertisement, params are not an advertisement."); - } - - return null; - } - - try { - return adv.clone(); - } catch (CloneNotSupportedException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Unclonable Advertisements may not be used : " + adv.getClass().getName(), failed); - } - - throw new IllegalArgumentException("Unclonable Advertisements may not be used : " + adv.getClass().getName()); - } - } - - /** - * Returns the parameter element that matches the given key from the - * service parameters table. The key is of a subclass of ID; usually a - * ModuleClassID. - * - * @param key The key. - * @return StructuredDocument The matching parameter document or null if - * none matched. - */ - public StructuredDocument getServiceParam(ID key) { - StructuredDocument param = params.get(key); - - if (param == null) { - Advertisement ad = ads.get(key); - - if (null == ad) { - return null; - } - - return (XMLDocument) ad.getDocument(MimeMediaType.XMLUTF8); - } - - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(param); - - if(disabled.contains(key)) { - Enumeration isOffAlready = newDoc.getChildren("isOff"); - - if(!isOffAlready.hasMoreElements()) { - newDoc.appendChild(newDoc.createElement("isOff", null)); - } - } - - return newDoc; - } - - /** - * Removes and returns the parameter element that matches the given key - * from the service parameters table. The key is of a subclass of ID; - * usually a ModuleClassID. - * - * @param key The key. - * - * @return The removed parameter element or {@code null} if not found. - */ - public StructuredDocument removeServiceParam(ID key) { - - StructuredDocument param = params.remove(key); - - if (param == null) { - Advertisement ad = ads.remove(key); - - if (null == ad) { - return null; - } - - return (XMLDocument) ad.getDocument(MimeMediaType.XMLUTF8); - } else { - ads.remove(key); - } - - incModCount(); - - // It sound silly to clone it, but remember that we could be sharing - // this element with a clone of ours, so we have the duty to still - // protect it. - - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(param); - - if(disabled.contains(key)) { - newDoc.appendChild(newDoc.createElement("isOff", null)); - disabled.remove(key); - } - - return newDoc; - } - - /** - * Removes any parameters for the given key from the service parameters - * table. - * - * @param key The key. - */ - public void removeSvcConfigAdvertisement(ID key) { - incModCount(); - - params.remove(key); - ads.remove(key); - } - - /** - * Returns the set of params held by this object. The parameters are not - * copied and any changes to the Set are reflected in this object's version. - * incModCount should be called as appropriate. - * - * @deprecated This method exposes the internal data structures of the - * advertisement and will be removed in order to prevent unexpected - * behaviour. - */ - @Deprecated - public Set> getServiceParamsEntrySet() { - Map result = new HashMap(); - - result.putAll(params); - - for (Map.Entry anEntry : ads.entrySet()) { - XMLDocument entryDoc = (XMLDocument) anEntry.getValue().getDocument(MimeMediaType.XMLUTF8); - - if(disabled.contains(anEntry.getKey())) { - entryDoc.appendChild(entryDoc.createElement("isOff", null)); - } - - result.put(anEntry.getKey(), entryDoc); - } - - return Collections.unmodifiableSet(result.entrySet()); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/DiscoveryQueryMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/DiscoveryQueryMsg.java deleted file mode 100644 index 6d5930c0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/DiscoveryQueryMsg.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.protocol; - - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Document; -import net.jxta.document.MimeMediaType; - - -/** - * This class defines the Discovery Service message "Query". The default - * behavior of this abstract class is simply a place holder for the generic - * resolver query fields. - * - * @see net.jxta.discovery.DiscoveryService - * @see net.jxta.protocol.DiscoveryResponseMsg - */ - -public abstract class DiscoveryQueryMsg { - - private PeerAdvertisement peerAdvertisement = null; - - /** - * default threshold to limit the number of responses from one peer - */ - private int threshold = 10; - - /** - * FIXME 20030227 bondolo@jxta.org not a great default... - */ - private int type = DiscoveryService.PEER; - - private String attr = null; - private String value = null; - - /** - * returns the Attr value - * - * @return String value of Attribute - */ - public String getAttr() { - return attr; - } - - /** - * Get the response type - * - * @return int PEER, or GROUP discovery type response - */ - public int getDiscoveryType() { - return type; - } - - /** - * Write advertisement into a document. asMimeType is a mime media-type - * specification and provides the form of the document which is being - * requested. Two standard document forms are defined. "text/text" encodes - * the document in a form nice for printing out, and "text/xml" which - * provides an XML representation. - * - * @param asMimeType mime-type format requested - * @return Document representation of the document as an - * advertisement - */ - public abstract Document getDocument(MimeMediaType asMimeType); - - /** - * returns the responding peer advertisement - * - * @return String handlername name - * @deprecated Peer Advertisement is available directly via - * {@link #getPeerAdvertisement()}. - */ - @Deprecated - public String getPeerAdv() { - if (null != peerAdvertisement) { - return peerAdvertisement.toString(); - } else { - return null; - } - } - - /** - * returns the querying peer's advertisement - * - * @return peer advertisement of querier. - */ - public PeerAdvertisement getPeerAdvertisement() { - return peerAdvertisement; - } - - /** - * returns the responding peer's advertisement - * - * @param newAdv peer advertisement of querier. - */ - public void setPeerAdvertisement(PeerAdvertisement newAdv) { - peerAdvertisement = newAdv; - } - - /** - * Get the Threshold for number of responses - * - * @return int threshold - */ - public int getThreshold() { - return threshold; - } - - /** - * returns the value of Attr - * - * @return String - */ - public String getValue() { - return value; - } - - /** - * set the attr - * - * @param attr attribute of the query - */ - public void setAttr(String attr) { - this.attr = attr; - } - - /** - * set the Response type whether it's peer, or group discovery - * - * @param type type of discovery - */ - public void setDiscoveryType(int type) { - // FIXME 20030227 bondolo@jxta.org This should be value checked. - this.type = type; - } - - /** - * set the threshold - * - * @param threshold value to be set - */ - public void setThreshold(int threshold) { - this.threshold = threshold; - } - - /** - * set the query - * - * @param value value of the attribute to query - */ - public void setValue(String value) { - this.value = value; - } - - /** - * All messages have a type (in xml this is !doctype) which - * identifies the message - * - * @return String "jxta:DiscoveryQuery" - */ - public static String getAdvertisementType() { - return "jxta:DiscoveryQuery"; - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/DiscoveryResponseMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/DiscoveryResponseMsg.java deleted file mode 100644 index 7e49fdc0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/DiscoveryResponseMsg.java +++ /dev/null @@ -1,379 +0,0 @@ -/* - * Copyright(c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.util.*; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Document; -import net.jxta.document.MimeMediaType; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * This class defines the DiscoveryService message "Response".

      - * - * The default behavior of this abstract class is simply a place holder for the - * generic resolver query fields. This message is the response to the - * DiscoveryQueryMsg. - * - *@see net.jxta.discovery.DiscoveryService - *@see net.jxta.protocol.DiscoveryQueryMsg - */ -public abstract class DiscoveryResponseMsg { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(DiscoveryResponseMsg.class.getName()); - - /** - * attribute used by the query - */ - protected String attr = null; - - /** - * Responding peer's advertisement - */ - protected PeerAdvertisement peerAdvertisement = null; - - /** - * The advertisement responses serialized into strings. - */ - protected final List responses = new ArrayList(0); - - /** - * The advertisement responses deserialized. - */ - protected final List advertisements = new ArrayList(0); - - /** - * Expirations - */ - protected final List expirations = new ArrayList(0); - - /** - * Advertisement type used by the query - * - *

      FIXME 20040514 bondolo@jxta.org not a great default... - */ - protected int type = DiscoveryService.PEER; - - /** - * Value used by the query - */ - protected String value = null; - - /** - * All messages have a type(in xml this is !doctype) which identifies the - * message - * - * @return String "jxta:ResolverResponse" - */ - public static String getAdvertisementType() { - return "jxta:DiscoveryResponse"; - } - - /** - * Get the response type - * - * @return int type of discovery message PEER, GROUP or ADV discovery type - * response - */ - public int getDiscoveryType() { - return type; - } - - /** - * set the Response type whether it's peer, or group discovery - * - * @param type int representing the type - */ - public void setDiscoveryType(int type) { - this.type = type; - } - - /** - * Write advertisement into a document. asMimeType is a mime media-type - * specification and provides the form of the document which is being - * requested. Two standard document forms are defined. "text/text" encodes - * the document in a form nice for printing out and "text/xml" which - * provides an XML format. - * - * @param asMimeType mime-type requested - * @return Document document that represents the advertisement - */ - - public abstract Document getDocument(MimeMediaType asMimeType); - - /** - * returns the responding peer's advertisement - * - * @return the Peer's advertisement - */ - public PeerAdvertisement getPeerAdvertisement() { - return peerAdvertisement; - } - - /** - * Sets the responding peer's advertisement - * - * @param newAdv the responding Peer's advertisement - */ - public void setPeerAdvertisement(PeerAdvertisement newAdv) { - peerAdvertisement = newAdv; - } - - /** - * returns the attributes used by the query - * - * @return String attribute of the query - */ - public String getQueryAttr() { - return attr; - } - - /** - * returns the value used by the query - * - *@return String value used by the query - */ - public String getQueryValue() { - return value; - } - - /** - * Get the response count - * - * @return int count - */ - public int getResponseCount() { - if (expirations.isEmpty() && (peerAdvertisement != null) && (type == DiscoveryService.PEER)) { - return 1; - } else { - return responses.size(); - } - } - - /** - * Gets the expirations attribute of the DiscoveryResponseMsg object - * - * @return The expirations value - */ - public Enumeration getExpirations() { - if (expirations.isEmpty() && (peerAdvertisement != null) && (type == DiscoveryService.PEER)) { - // this takes care of the case where the only response is the peerAdv - expirations.add(DiscoveryService.DEFAULT_EXPIRATION); - } - - return Collections.enumeration(expirations); - } - - /** - * set the expirations for this query - * - * @param expirations the expirations for this query - */ - public void setExpirations(List expirations) { - this.expirations.clear(); - this.expirations.addAll(expirations); - } - - /** - * returns the response(s) - * - * @return Enumeration of String responses - */ - public Enumeration getResponses() { - if (responses.isEmpty() && (peerAdvertisement != null) && (type == DiscoveryService.PEER)) { - // this takes care of the case where the only response is the peerAdv - responses.add(peerAdvertisement.toString()); - } - - return Collections.enumeration(responses); - } - - /** - * Set the responses to the query. The responses may be either - * {@code Advertisement}, {@code String} or {@code InputStream}. - * - * @param responses List of responses - */ - public void setResponses(List responses) { - this.responses.clear(); - - for (Object response : responses) { - if (response instanceof Advertisement) { - this.responses.add(((Advertisement) response).getDocument(MimeMediaType.XMLUTF8).toString()); - } else if (response instanceof String) { - this.responses.add((String) response); - } else if (response instanceof InputStream) { - String result = streamToString((InputStream) response); - - if (null != result) { - this.responses.add(result); - } - } else { - throw new IllegalArgumentException("Non-String or InputStream response recevied."); - } - } - } - - /** - * Reads in a stream into a string - * - * @param is inputstream - * @return string representation of a stream - */ - private String streamToString(InputStream is) { - Reader reader = null; - - try { - reader = new InputStreamReader(is, "UTF-8"); - } catch (UnsupportedEncodingException impossible) { - throw new Error("UTF-8 encoding not supported?!?"); - } - - StringBuilder stw = new StringBuilder(); - char[] buf = new char[512]; - - try { - do { - int c = reader.read(buf); - - if (c == -1) { - break; - } - stw.append(buf, 0, c); - } while (true); - } catch (IOException ie) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Got an Exception during stream conversion", ie); - } - return null; - } finally { - try { - is.close(); - } catch (IOException ignored) {} - } - - return stw.toString(); - } - - /** - * Set the attribute used by the query - * - * @param attr query attribute - */ - public void setQueryAttr(String attr) { - this.attr = attr; - } - - /** - * Set the value used by the query - * - * @param value Query value - */ - public void setQueryValue(String value) { - this.value = value; - } - - /** - * Get the responses to the query as advertisements. - * - * @return The response advertisements. - */ - public Enumeration getAdvertisements() { - if (responses.isEmpty() && (peerAdvertisement != null) && (type == DiscoveryService.PEER)) { - // this takes care of the case where the only response is the peerAdv - return Collections.enumeration(Collections.singletonList((Advertisement) peerAdvertisement)); - } - - if (advertisements.isEmpty() && !responses.isEmpty()) { - // Convert the responses. - for (String aResponse : responses) { - try { - XMLDocument anXMLDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8 - , - new StringReader(aResponse)); - Advertisement anAdv = AdvertisementFactory.newAdvertisement(anXMLDoc); - - advertisements.add(anAdv); - } catch (IOException badAdvertisement) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Invalid response in message : ", badAdvertisement); - } - } - } - } - - return Collections.enumeration(advertisements); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ModuleClassAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ModuleClassAdvertisement.java deleted file mode 100644 index 1934ecfe..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ModuleClassAdvertisement.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.id.ID; -import net.jxta.platform.ModuleClassID; - - -/** - * Formally documents the existence of a module class (identified by the - * {@link net.jxta.platform.ModuleClassID} and may provide additional - * descriptive metadata about the Module Class. - * - * @see net.jxta.platform.ModuleClassID - */ -public abstract class ModuleClassAdvertisement extends ExtendableAdvertisement implements Cloneable { - - /** - * The module class id associated with the is advertisement. - */ - private ModuleClassID id = null; - - /** - * Informal, non-canonical name of module. - */ - private String name = null; - - /** - * Descriptive meta-data about this module. - */ - private Element description = null; - - /** - * Returns the identifying type of this Advertisement. - * - * @return The type of advertisement. - */ - public static String getAdvertisementType() { - return "jxta:MCA"; - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public ModuleClassAdvertisement clone() { - try { - ModuleClassAdvertisement clone = (ModuleClassAdvertisement) super.clone(); - - clone.setModuleClassID(getModuleClassID()); - clone.setName(getName()); - clone.setDesc(description); - - return clone; - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - } - - /** - * {@inheritDoc} - */ - @Override - public ID getID() { - return id; - } - - /** - * returns the name of the class - * - * @return String name of the class - */ - public String getName() { - return name; - } - - /** - * sets the name of the class - * - * @param name name of the class to be set - * - */ - public void setName(String name) { - this.name = name; - } - - /** - * returns the description - * - * @return String the description - */ - public String getDescription() { - if (null != description) { - return (String) description.getValue(); - } else { - return null; - } - } - - /** - * sets the description - * - * @param description the description - */ - public void setDescription(String description) { - - if (null != description) { - StructuredDocument newdoc = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Desc", description); - - setDesc(newdoc); - } else { - this.description = null; - } - } - - /** - * returns the description - * - * @return the description - */ - public StructuredDocument getDesc() { - if (null != description) { - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(description); - - return newDoc; - } else { - return null; - } - } - - /** - * sets the description - * - * @param desc the description - */ - public void setDesc(Element desc) { - - if (null != desc) { - this.description = StructuredDocumentUtils.copyAsDocument(desc); - } else { - this.description = null; - } - } - - /** - * returns the id of the class - * - * @return ModuleClassID the class id - */ - public ModuleClassID getModuleClassID() { - return id; - } - - /** - * sets the id of the class - * - * @param id The id of the class - */ - public void setModuleClassID(ModuleClassID id) { - this.id = id; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ModuleImplAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ModuleImplAdvertisement.java deleted file mode 100644 index 15f7e936..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ModuleImplAdvertisement.java +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.id.ID; -import net.jxta.platform.ModuleSpecID; - - -/** - * A ModuleImplAdvertisement describes one of any number of published - * implementations for a given specification. - *

      - * Module specifications are referenced by their ModuleSpecID. Given a - * ModuleSpecID, a ModuleImplAdvertisement may be searched by means of JXTA - * Discovery, filtered according to the compatibility statement it contains, - * and if compatible, loaded and initialized. The {@code loadModule()} method of - * PeerGroup performs this task automatically, given a ModuleSpecID. - *

      - * One significant example of Modules referenced and loaded in that manner are - * the services and protocols that constitute a StdPeerGroup in the Java - * reference implementation. - * - * @see net.jxta.id.ID - * @see net.jxta.platform.ModuleSpecID - * @see net.jxta.document.Advertisement - * @see net.jxta.document.StructuredDocument - * @see net.jxta.document.Element - * @see net.jxta.protocol.ModuleSpecAdvertisement - * @see net.jxta.peergroup.PeerGroup - */ -public abstract class ModuleImplAdvertisement extends ExtendableAdvertisement implements Cloneable { - - private ModuleSpecID msid = null; - private StructuredDocument description = null; - private StructuredDocument compat = null; - private String code = null; - private String uri = null; - private String provider = null; - private StructuredDocument param = null; - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:MIA"; - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * Clone this ModuleImplAdvertisement - */ - @Override - public ModuleImplAdvertisement clone() { - - try { - ModuleImplAdvertisement clone = (ModuleImplAdvertisement) super.clone(); - - clone.setModuleSpecID(getModuleSpecID()); - clone.setDesc(getDescPriv()); - clone.setCompat(getCompatPriv()); - clone.setCode(getCode()); - clone.setUri(getUri()); - clone.setProvider(getProvider()); - clone.setParam(getParamPriv()); - - return clone; - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - } - - /** - * Returns the unique ID of that advertisement for indexing purposes. - * In that case we do not have any particular one to offer. Let the indexer - * hash the document. - * - * @return ID the unique id - */ - @Override - public ID getID() { - return null; - } - - /** - * Returns the id of the spec that this implements. - * @return ID the spec id - * - */ - public ModuleSpecID getModuleSpecID() { - return msid; - } - - /** - * Sets the id of the spec that is implemented - * - * @param msid The id of the spec - */ - public void setModuleSpecID(ModuleSpecID msid) { - this.msid = msid; - } - - /** - * returns the description - * - * @return String the description - */ - public String getDescription() { - if (null != description) { - return (String) description.getValue(); - } else { - return null; - } - } - - /** - * sets the description - * - * @param description the description - */ - public void setDescription(String description) { - - if (null != description) { - StructuredDocument newdoc = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Desc", description); - - setDesc(newdoc); - } else { - this.description = null; - } - } - - /** - * returns the description - * - * @return the description - */ - public StructuredDocument getDesc() { - if (null != description) { - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(description); - - return newDoc; - } else { - return null; - } - } - - /** - * Privileged version of {@link #getDesc()} that does not clone the elements. - * - * @return the description - */ - public StructuredDocument getDescPriv() { - return description; - } - - /** - * sets the description - * - * @param desc the description - */ - public void setDesc(Element desc) { - - if (null != desc) { - this.description = StructuredDocumentUtils.copyAsDocument(desc); - } else { - this.description = null; - } - } - - /** - * Returns the opaque compatibility statement for this advertisement. Each - * JXTA implementation has the ability to recognize and evaluate it's own - * compatibility statements (even though it may not be able to evaluate the - * compatibility statements of other implementations). - * - * @return The compatibility statement as a StructuredDocument of - * unspecified content. - */ - public StructuredDocument getCompat() { - return (compat == null ? null : StructuredDocumentUtils.copyAsDocument(compat)); - } - - /** - * Privileged version of {@link #getCompat()} that does not clone the elements. - * - * @return The compatibility statement as a StructuredDocument of - * unspecified content. - */ - protected StructuredDocument getCompatPriv() { - return compat; - } - - /** - * Sets the module impl. compatibility statement. - * - * @param compat Element of an unspecified content. - */ - public void setCompat(Element compat) { - this.compat = (compat == null ? null : StructuredDocumentUtils.copyAsDocument(compat)); - } - - /** - * returns the code; a reference to or representation of the executable code - * advertised by this advertisement. - *

      - * The appropriate interpretation of the code value is dependant upon the - * compatibility statement. Any compatible consumer of this advertisement - * will be able to correctly interpret code value. The standard group - * implementations of the JXSE reference implementation expect it to be a - * reference to a jar file. - * - * @return A reference to the executable code described by this - * advertisement. - */ - public String getCode() { - return code; - } - - /** - * Sets the reference for the executable code described by this - * advertisement. - * - * @param code A reference to the executable code described by this - * advertisement. - */ - public void setCode(String code) { - this.code = code; - } - - /** - * returns the uri; that is a reference to or representation of a package - * from which the executable code referenced by the getCode method may be - * loaded. - *

      - * The appropriate interpretation of the URI value is dependant upon the - * compatibility statement. Any compatible consumer of this advertisement - * will be able to correctly interpret the URI value. The standard group - * implementations of the JXSE reference implementation expect it to be a - * reference to a jar file. - * - * @return Location URI for the code described by this advertisement. - */ - public String getUri() { - return uri; - } - - /** - * Sets the uri - * - * @param uri Location URI for the code described by this advertisement. - */ - public void setUri(String uri) { - this.uri = uri; - } - - /** - * returns the provider - * - * @return String the provider - */ - public String getProvider() { - return provider; - } - - /** - * sets the provider - * - * @param provider the provider - */ - public void setProvider(String provider) { - this.provider = provider; - } - - /** - * returns the param element. - * - * The interpretation of the param element is entirely up to the code - * that this advertises. One valid use of it is to enable the code to - * be configured so that multiple specs or multiple implementations of - * one spec may use the same code. - * - * @return A standalone structured document of unspecified content. - */ - public StructuredDocument getParam() { - return (param == null ? null : StructuredDocumentUtils.copyAsDocument(param)); - } - - /** - * Privileged version of {@link #getParam()} that does not clone the elements. - * - * @return A standalone structured document of unspecified content. - */ - protected StructuredDocument getParamPriv() { - return param; - } - - /** - * Sets the module param - * - * @param param Element of an unspecified content. - */ - public void setParam(Element param) { - this.param = (param == null ? null : StructuredDocumentUtils.copyAsDocument(param)); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ModuleSpecAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ModuleSpecAdvertisement.java deleted file mode 100644 index 5b912084..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ModuleSpecAdvertisement.java +++ /dev/null @@ -1,404 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.id.ID; -import net.jxta.platform.ModuleSpecID; - - -/** - * Provides the references that describe a module specification. Typically this - * includes references to the documentation needed in order to create conforming - * implementations of the specification. A secondary use is, optionally, to make - * running instances usable remotely, by publishing any or all of the following: - *

        - *
      • PipeAdvertisement - *
      • ModuleSpecID of a proxy module - *
      • ModuleSpecID of an authenticator module - *
      - *

      - * Not all modules are usable remotely, it is up to the specification creator to - * make that choice. However, if the specification dictates it, all - * implementations can be expected to support it. - *

      - * Note that the Standard PeerGroup implementation included with the JXSE - * reference implementation does not support replacing a group service - * with a pipe to a remote instance. However, nothing prevents a particular - * implementation of a group from using a proxy module in place of the fully - * version; provided that the API (and therefore the ClassIDs) of the proxy and - * local versions are identical. - *

      - * Note also that in the case of the local+proxy style, it is up to the - * implementation of both sides to figure-out which pipe to listen to or connect - * to. The safest method is probably for the full version to seek its own - * ModuleSpecAdvertisement, and for the proxy version to accept the full - * version's ModuleSpecAdvertisement as a parameter. Alternatively, if the proxy - * version is completely dedicated to the specification that it proxies, both - * sides may have the PipeID and type hard-coded. - * - * @see net.jxta.platform.ModuleSpecID - * @see net.jxta.protocol.PipeAdvertisement - * @see net.jxta.protocol.ModuleClassAdvertisement - * @see net.jxta.protocol.ModuleImplAdvertisement - * @see net.jxta.document.Advertisement - */ -public abstract class ModuleSpecAdvertisement extends ExtendableAdvertisement implements Cloneable { - - private ModuleSpecID id = null; - private String name = null; - private Element description = null; - private String creator = null; - private String uri = null; - private String version = null; - private PipeAdvertisement pipeAdv = null; - private ModuleSpecID proxySpecID = null; - private ModuleSpecID authSpecID = null; - private StructuredDocument param = null; - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - **/ - public static String getAdvertisementType() { - return "jxta:MSA"; - } - - /** - * {@inheritDoc} - **/ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - **/ - @Override - public ModuleSpecAdvertisement clone() { - try { - ModuleSpecAdvertisement clone = (ModuleSpecAdvertisement) super.clone(); - - clone.setModuleSpecID(getModuleSpecID()); - clone.setName(getName()); - clone.setDesc(getDesc()); - clone.setCreator(getCreator()); - clone.setSpecURI(getSpecURI()); - clone.setVersion(getVersion()); - clone.setPipeAdvertisement(getPipeAdvertisement()); - clone.setProxySpecID(getProxySpecID()); - clone.setAuthSpecID(getAuthSpecID()); - clone.setParam(param); - - return clone; - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - } - - /** - * returns a unique id for that adv for the purpose of indexing. - * The spec id uniquely identifies this advertisement. - * - * @return ID the spec id as a basic ID. - * - */ - @Override - public ID getID() { - return id; - } - - /** - * returns the id of the spec - * - * @return ModuleSpecID the spec id - **/ - public ModuleSpecID getModuleSpecID() { - return id; - } - - /** - * sets the id of the spec - * - * @param id The id of the spec - **/ - public void setModuleSpecID(ModuleSpecID id) { - this.id = id; - } - - /** - * returns the name of the module spec - * - * @return String name of the module spec - **/ - public String getName() { - return name; - } - - /** - * sets the name of the module spec - * - * @param name name of the module spec to be set - **/ - public void setName(String name) { - this.name = name; - } - - /** - * returns the description - * - * @return String the description - **/ - public String getDescription() { - if (null != description) { - return (String) description.getValue(); - } else { - return null; - } - } - - /** - * sets the description - * - * @param description the description - **/ - public void setDescription(String description) { - - if (null != description) { - StructuredDocument newdoc = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Desc", description); - - setDesc(newdoc); - } else { - this.description = null; - } - } - - /** - * returns the description - * - * @return the description - **/ - public StructuredDocument getDesc() { - if (null != description) { - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(description); - - return newDoc; - } else { - return null; - } - } - - /** - * sets the description - * - * @param desc the description - **/ - public void setDesc(Element desc) { - - if (null != desc) { - this.description = StructuredDocumentUtils.copyAsDocument(desc); - } else { - this.description = null; - } - } - - /** - * Returns the creator of the module spec, in case someone cares. - * - * @return String the creator. - **/ - public String getCreator() { - return creator; - } - - /** - * Sets the creator of this module spec. - * Note: the usefulness of this is unclear. - * - * @param creator name of the creator of the module - **/ - public void setCreator(String creator) { - this.creator = creator; - } - - /** - * returns the uri. This uri normally points at the actual specification - * that this advertises. - * - * @return String uri - **/ - public String getSpecURI() { - return uri; - } - - /** - * sets the uri - * - * @param uri string uri - **/ - public void setSpecURI(String uri) { - this.uri = uri; - } - - /** - * returns the specification version number - * - * @return String version number - **/ - public String getVersion() { - return version; - } - - /** - * sets the version of the module - * - * @param version version number - **/ - public void setVersion(String version) { - this.version = version; - } - - /** - * returns the param element. - * - * @return Element parameters as an Element of unspecified content. - **/ - public StructuredDocument getParam() { - return (param == null ? null : StructuredDocumentUtils.copyAsDocument(param)); - } - - /** - * Privileged version of {@link #getParam()} that does not clone the elements. - * - * @return StructuredDocument A stand-alone structured document of - * unspecified content. - **/ - protected StructuredDocument getParamPriv() { - return param; - } - - /** - * sets the param element. - * - * @param param Element of an unspecified content. - **/ - public void setParam(Element param) { - this.param = (param == null ? null : StructuredDocumentUtils.copyAsDocument(param)); - } - - /** - * returns the embedded pipe advertisement if any. - * - * @return PipeAdvertisement the Pipe Advertisement. null if none exists. - **/ - public PipeAdvertisement getPipeAdvertisement() { - return (pipeAdv == null ? null : pipeAdv.clone()); - } - - /** - * sets an embedded pipe advertisement. - * - * @param pipeAdv the Pipe Advertisement. null is authorized. - **/ - public void setPipeAdvertisement(PipeAdvertisement pipeAdv) { - this.pipeAdv = (pipeAdv == null ? null : pipeAdv.clone()); - } - - /** - * returns the specID of a proxy module. - * - * @return ModuleSpecID the spec id - **/ - public ModuleSpecID getProxySpecID() { - return proxySpecID; - } - - /** - * sets a proxy module specID - * - * @param proxySpecID The spec id - **/ - public void setProxySpecID(ModuleSpecID proxySpecID) { - this.proxySpecID = proxySpecID; - } - - /** - * returns the specID of an authenticator module. - * - * @return ModuleSpecID the spec id - **/ - public ModuleSpecID getAuthSpecID() { - return authSpecID; - } - - /** - * sets an authenticator module specID - * - * @param authSpecID The spec id - **/ - public void setAuthSpecID(ModuleSpecID authSpecID) { - this.authSpecID = authSpecID; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerAdvertisement.java deleted file mode 100644 index 9ffc16bc..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerAdvertisement.java +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import java.io.ByteArrayInputStream; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Level; -import java.util.logging.Logger; - -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroupID; - - -/** - * Generated when instantiating a group on a peer and contains all the - * parameters that services need to publish. It is then published within the - * group. - */ -public abstract class PeerAdvertisement extends ExtendableAdvertisement implements Cloneable { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(PeerAdvertisement.class.getName()); - - /** - * The id of this peer. - */ - private PeerID pid = null; - - /** - * The group in which this peer is located. - */ - private PeerGroupID gid = null; - - /** - * The name of this peer. Not guaranteed to be unique in any way. May be empty or - * null. - */ - private String name = null; - - /** - * Descriptive meta-data about this peer. - */ - private Element description = null; - - /** - * A table of structured documents to be interpreted by each service. - */ - private final Map serviceParams = new HashMap(); - - /** - * Counts the changes made to this object. We rely on implementations to - * increment modCount every time something is changed without going through - * the API. - */ - private final transient AtomicInteger modCount = new AtomicInteger(0); - - /** - * Returns the number of times this object has been modified since - * it was created. This permits to detection of local changes that require - * refreshing of other data which depends upon the peer advertisement. - * - * @return int the current modification count. - */ - - public int getModCount() { - return modCount.get(); - } - - /** - * Increments the modification count for this peer advertisement. - */ - protected int incModCount() { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - Throwable trace = new Throwable("Stack Trace"); - StackTraceElement elements[] = trace.getStackTrace(); - - LOG.finer("Modification #" + (getModCount() + 1) + " to PeerAdv@" + Integer.toHexString(System.identityHashCode(this)) - + " caused by : " + "\n\t" + elements[1] + "\n\t" + elements[2]); - } - - return modCount.incrementAndGet(); - } - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:PA"; - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public PeerAdvertisement clone() { - - try { - PeerAdvertisement clone = (PeerAdvertisement) super.clone(); - - clone.setPeerID(getPeerID()); - clone.setPeerGroupID(getPeerGroupID()); - clone.setName(getName()); - clone.setDesc(getDesc()); - clone.setServiceParams(getServiceParams()); - - return clone; - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - } - - /** - * returns the name of the peer. - * - * @return String name of the peer. - */ - - public String getName() { - return name; - } - - /** - * sets the name of the peer. - * - * @param name name of the peer. - */ - - public void setName(String name) { - this.name = name; - incModCount(); - } - - /** - * Returns the id of the peer. - * - * @return PeerID the peer id - */ - - public PeerID getPeerID() { - return pid; - } - - /** - * Sets the id of the peer. - * - * @param pid the id of this peer. - */ - - public void setPeerID(PeerID pid) { - this.pid = pid; - incModCount(); - } - - /** - * Returns the id of the peergroup this peer advertisement is for. - * - * @return PeerGroupID the peergroup id - */ - - public PeerGroupID getPeerGroupID() { - return gid; - } - - /** - * Returns the id of the peergroup this peer advertisement is for. - * - * @param gid The id of the peer. - */ - - public void setPeerGroupID(PeerGroupID gid) { - this.gid = gid; - incModCount(); - } - - /** - * Returns a unique ID for that peer X group intersection. This is for - * indexing purposes only. - * - * @return ID the unique ID - */ - @Override - public ID getID() { - // If it is incomplete, there's no meaningful ID that we can return. - if (gid == null || pid == null) { - return null; - } - - try { - String hashValue = getAdvertisementType() + gid.getUniqueValue().toString() + pid.getUniqueValue().toString(); - byte[] seed = hashValue.getBytes("UTF-8"); - - return IDFactory.newCodatID(gid, seed, new ByteArrayInputStream(seed)); - } catch (Exception failed) { - return null; - } - } - - /** - * returns the description - * - * @return String the description - */ - public String getDescription() { - if (null != description) { - return (String) description.getValue(); - } else { - return null; - } - } - - /** - * sets the description - * - * @param description the description - * @since JXTA 1.0 - */ - public void setDescription(String description) { - - if (null != description) { - StructuredDocument newdoc = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Desc", description); - - setDesc(newdoc); - } else { - this.description = null; - } - - incModCount(); - } - - /** - * returns the description - * - * @return the description - */ - public StructuredDocument getDesc() { - if (null != description) { - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(description); - - return newDoc; - } else { - return null; - } - } - - /** - * sets the description - * - * @param desc the description - */ - public void setDesc(Element desc) { - - if (null != desc) { - this.description = StructuredDocumentUtils.copyAsDocument(desc); - } else { - this.description = null; - } - - incModCount(); - } - - /** - * sets the sets of parameters for all services. This method first makes a - * deep copy, in order to protect the active information from uncontrolled - * sharing. This quite an expensive operation. If only a few of the - * parameters need to be added, it is wise to use putServiceParam() - * instead. - * - * @param params The whole set of parameters. - */ - public void setServiceParams(Hashtable params) { - serviceParams.clear(); - - if (params == null) { - return; - } - - for (Map.Entry anEntry : params.entrySet()) { - Element e = anEntry.getValue(); - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(e); - - serviceParams.put(anEntry.getKey(), newDoc); - } - - incModCount(); - } - - /** - * Returns the sets of parameters for all services. - * - *

      This method returns a deep copy, in order to protect the real - * information from uncontrolled sharing while keeping it shared as long as - * it is safe. This quite an expensive operation. If only a few parameters - * need to be accessed, it is wise to use getServiceParam() instead. - * - * @return all of the parameters. - */ - public Hashtable getServiceParams() { - Hashtable copy = new Hashtable(); - - for (Map.Entry anEntry : serviceParams.entrySet()) { - Element e = anEntry.getValue(); - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(e); - - copy.put(anEntry.getKey(), newDoc); - } - - return copy; - } - - /** - * Puts a service parameter in the service parameters table under the given - * key. The key is of a subclass of ID; usually a ModuleClassID. This - * method makes a deep copy of the given element into an independent - * document. - * - * @param key The key. - * @param param The parameter, as an element. What is stored is a copy as a - * standalone StructuredDocument which type is the element's name. - */ - public void putServiceParam(ID key, Element param) { - if (param == null) { - serviceParams.remove(key); - incModCount(); - return; - } - - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(param); - - serviceParams.put(key, newDoc); - - incModCount(); - } - - /** - * Returns the parameter element that matches the given key from the - * service parameters table. The key is of a subclass of ID; usually a - * ModuleClassID. - * - * @param key The key. - * @return StructuredDocument The matching parameter document or null if - * none matched. The document type id "Param". - */ - public StructuredDocument getServiceParam(ID key) { - StructuredDocument param = serviceParams.get(key); - - if (param == null) { - return null; - } - - return StructuredDocumentUtils.copyAsDocument(param); - } - - /** - * Removes and returns the parameter element that matches the given key - * from the service parameters table. The key is of a subclass of ID; - * usually a ModuleClassID. - * - * @param key The key. - * @return Element the removed parameter element or null if not found. - * This is actually a StructureDocument of type "Param". - */ - public StructuredDocument removeServiceParam(ID key) { - Element param = serviceParams.remove(key); - - if (param == null) { - return null; - } - - incModCount(); - - // It sound silly to clone it, but remember that we could be sharing - // this element with a clone of ours, so we have the duty to still - // protect it. - - return StructuredDocumentUtils.copyAsDocument(param); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerGroupAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerGroupAdvertisement.java deleted file mode 100644 index 7049b0a7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerGroupAdvertisement.java +++ /dev/null @@ -1,397 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import java.util.Hashtable; -import java.util.Map; -import java.util.HashMap; - -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.platform.ModuleSpecID; - - -/** - * Describes a peer group and references additional information required for - * instantiating it. The PeerGroup method newGroup performs the task of - * instantiating a PeerGroup given its advertisement (provided the required - * subsequent documents can actually be found). This advertisement is indexed - * on "Name", "GID", and "Desc" - * - * @see net.jxta.platform.ModuleSpecID - * @see net.jxta.protocol.ModuleImplAdvertisement - * @see net.jxta.peergroup.PeerGroup - */ - -public abstract class PeerGroupAdvertisement extends ExtendableAdvertisement implements Cloneable { - - private PeerGroupID gid = null; - private ModuleSpecID specId = null; - - /** - * Informal, non-canonical name of this peer group - */ - private String name = null; - - /** - * Descriptive meta-data about this peer group. - */ - private Element description = null; - - // A table of structured documents to be interpreted by each service. - private final Map serviceParams = new HashMap(); - - /** - * Returns the identifying type of this Advertisement. - * - *@return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:PGA"; - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * Construct a new Peer Group Advertisement. - **/ - public PeerGroupAdvertisement() {} - - /** - * {@inheritDoc} - * - *@return An object of class PeerGroupAdvertisement that is a - * deep-enough copy of this one. - */ - @Override - public PeerGroupAdvertisement clone() { - - PeerGroupAdvertisement clone; - - try { - clone = (PeerGroupAdvertisement) super.clone(); - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - - clone.setPeerGroupID(getPeerGroupID()); - clone.setModuleSpecID(getModuleSpecID()); - clone.setName(getName()); - clone.setDesc(getDesc()); - clone.setServiceParams(getServiceParams()); - - return clone; - } - - /** - * Returns the name of the group or null if no name has been - * assigned. - * - *@return String name of the group. - */ - - public String getName() { - return name; - } - - /** - * sets the name of the group. - * - *@param name name of the group. - */ - - public void setName(String name) { - this.name = name; - } - - /** - * Returns the id of the group spec that this uses. - * - *@return ID the spec id - */ - - public ModuleSpecID getModuleSpecID() { - return specId; - } - - /** - * Sets the id of the group spec that this peer group uses. - * - *@param sid The id of the spec - */ - - public void setModuleSpecID(ModuleSpecID sid) { - this.specId = sid; - } - - /** - * Returns the id of the group. - * - *@return ID the group id - */ - - public PeerGroupID getPeerGroupID() { - return gid; - } - - /** - * Sets the id of the group. - * - *@param gid The id of this group. - */ - - public void setPeerGroupID(PeerGroupID gid) { - this.gid = gid; - } - - /** - * Returns a unique ID for indexing purposes. We use the id of the group as - * a plain ID. - * - *@return ID a unique id for that advertisement. - */ - - @Override - public ID getID() { - return gid; - } - - /** - * returns the description - * - * @return String the description - */ - public String getDescription() { - if (null != description) { - return (String) description.getValue(); - } else { - return null; - } - } - - /** - * sets the description - * - * @param description the description - */ - public void setDescription(String description) { - - if (null != description) { - StructuredDocument newdoc = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Desc", description); - - setDesc(newdoc); - } else { - this.description = null; - } - } - - /** - * returns the description - * - * @return the description - */ - public StructuredDocument getDesc() { - if (null != description) { - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(description); - - return newDoc; - } else { - return null; - } - } - - /** - * sets the description - * - * @since JXTA 1.0 - * - * @param desc the description - * - */ - public void setDesc(Element desc) { - - if (null != desc) { - this.description = StructuredDocumentUtils.copyAsDocument(desc); - } else { - this.description = null; - } - } - - /** - * sets the sets of parameters for all services. This method first makes a - * deep copy, in order to protect the active information from uncontrolled - * sharing. This quite an expensive operation. If only a few of the - * parameters need to be added, it is wise to use putServiceParam() - * instead. - * - *@param params The whole set of parameters. - */ - public void setServiceParams(Hashtable params) { - serviceParams.clear(); - - if (params == null) { - return; - } - - for (Map.Entry anEntry : params.entrySet()) { - Element e = anEntry.getValue(); - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(e); - - serviceParams.put(anEntry.getKey(), newDoc); - } - - } - - /** - * Returns the sets of parameters for all services. - * - *

      This method returns a deep copy, in order to protect the real - * information from uncontrolled sharing while keeping it shared as long as - * it is safe. This quite an expensive operation. If only a few parameters - * need to be accessed, it is wise to use getServiceParam() instead. - * - *@return all of the parameters. - */ - public Hashtable getServiceParams() { - Hashtable copy = new Hashtable(); - - for (Map.Entry anEntry : serviceParams.entrySet()) { - Element e = anEntry.getValue(); - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(e); - - copy.put(anEntry.getKey(), newDoc); - } - - return copy; - } - - /** - * Puts a service parameter in the service parameters table under the given - * key. The key is of a subclass of ID; usually a ModuleClassID. This - * method makes a deep copy of the given element into an independent - * document. - * - *@param key The key. - *@param param The parameter, as an element. What is stored is a copy as a - * standalone StructuredDocument which type is the element's name. - */ - public void putServiceParam(ID key, Element param) { - if (param == null) { - serviceParams.remove(key); - return; - } - - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(param); - - serviceParams.put(key, newDoc); - } - - /** - * Returns the parameter element that matches the given key from the - * service parameters table. The key is of a subclass of ID; usually a - * ModuleClassID. - * - *@param key The key. - *@return StructuredDocument The matching parameter document or null if - * none matched. The document type id "Param". - */ - public StructuredDocument getServiceParam(ID key) { - StructuredDocument param = serviceParams.get(key); - - if (param == null) { - return null; - } - - return StructuredDocumentUtils.copyAsDocument(param); - } - - /** - * Removes and returns the parameter element that matches the given key - * from the service parameters table. The key is of a subclass of ID; - * usually a ModuleClassID. - * - *@param key The key. - *@return Element the removed parameter element or null if not found. - * This is actually a StructureDocument of type "Param". - */ - public StructuredDocument removeServiceParam(ID key) { - Element param = serviceParams.remove(key); - - if (param == null) { - return null; - } - - // It sound silly to clone it, but remember that we could be sharing - // this element with a clone of ours, so we have the duty to still - // protect it. - - return StructuredDocumentUtils.copyAsDocument(param); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerInfoQueryMessage.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerInfoQueryMessage.java deleted file mode 100644 index 3a94ce02..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerInfoQueryMessage.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.peer.PeerID; - - -/** - * This abstract class define the PeerInfoService Query message. - * - **/ -public abstract class PeerInfoQueryMessage { - - /** - * The Sender's (or Querying) Peer Id. - */ - private PeerID spid = null; - - /** - * Peer Id of the peer which published this advertisement. - */ - private PeerID tpid = null; - - /* representing request */ - private StructuredDocument request = null; - - public PeerInfoQueryMessage() { - super(); - } - - /** - * returns the Message type - * @return a string - * - * @since JXTA 1.0 - */ - public static String getMessageType() { - return "jxta:PeerInfoQueryMessage"; - } - - /** - * returns the sender's pid - * @return a string representing the peer's id - * - * @since JXTA 1.0 - */ - public PeerID getSourcePid() { - return spid; - } - - /** - * sets the sender's pid - * @param pid a string representing a peer's id - * - * @since JXTA 1.0 - */ - public void setSourcePid(PeerID pid) { - this.spid = pid; - } - - /** - * returns the target pid - * @return a string representing the peer's id - * - * @since JXTA 1.0 - */ - public PeerID getTargetPid() { - return tpid; - } - - /** - * sets the target's pid - * @param pid a string representing a peer's id - * - * @since JXTA 1.0 - */ - public void setTargetPid(PeerID pid) { - this.tpid = pid; - } - - /** - * returns the request - * @return a structured document representing request - * - * @since JXTA 1.0 - */ - public Element getRequest() { - if (null != request) { - return StructuredDocumentUtils.copyAsDocument(request); - } else { - return null; - } - } - - /** - * sets the request - * @param request a structured document representing a peerinfo request - * - * @since JXTA 1.0 - */ - public void setRequest(Element request) { - if (null != request) { - this.request = StructuredDocumentUtils.copyAsDocument(request); - } else { - this.request = null; - } - } - - public abstract Document getDocument(MimeMediaType encodeAs); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerInfoResponseMessage.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerInfoResponseMessage.java deleted file mode 100644 index 5dfa38c5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PeerInfoResponseMessage.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.peer.PeerID; - - -/** - * This abstract class define the PeerInfoService advertisement. - */ - -public abstract class PeerInfoResponseMessage { - - /** - * The Sender's (or Querying) Peer Id. - */ - private PeerID spid = null; - - /** - * Peer Id of the peer which published this advertisement. - */ - private PeerID tpid = null; - - /** String representing response */ - private StructuredDocument response = null; - - /** - * Time in seconds since this peer was started. - */ - private long uptime = 0; - - /** - * Time in milliseconds when this peer was last polled since - * "the epoch", namely January 1, 1970, 00:00:00 GMT. - */ - private long timestamp = 0; - - public PeerInfoResponseMessage() { - super(); - } - - /** - * returns the Message type - * @return a string - * - */ - public static String getMessageType() { - return "jxta:PeerInfoResponseMessage"; - } - - /** - * returns the sender's pid - * - * @return a string representing the peer's id - * - */ - public PeerID getSourcePid() { - return spid; - } - - /** - * sets the sender's pid - * - * @param pid a string representing a peer's id - * - */ - public void setSourcePid(PeerID pid) { - this.spid = pid; - } - - /** - * returns the target pid - * - * @return a string representing the peer's id - * - */ - public PeerID getTargetPid() { - return tpid; - } - - /** - * sets the target's pid - * - * @param pid a string representing a peer's id - * - */ - public void setTargetPid(PeerID pid) { - this.tpid = pid; - } - - /** - * returns the response - * - * @return a structured document representing request - * - */ - public Element getResponse() { - if (null != response) { - return StructuredDocumentUtils.copyAsDocument(response); - } else { - return null; - } - } - - /** - * sets the request - * - * @param response a structured document representing a peerinfo request - * - */ - public void setResponse(Element response) { - if (null != response) { - this.response = StructuredDocumentUtils.copyAsDocument(response); - } else { - this.response = null; - } - } - - /** - * returns the number of milliseconds since this peer was started - * @return the number of milliseconds - * - */ - public long getUptime() { - return uptime; - } - - /** - * sets the number of milliseconds since this peer was started - * @param milliseconds the number of milliseconds since this peer was started - * - */ - public void setUptime(long milliseconds) { - this.uptime = milliseconds; - } - - /** - * returns the time when this peer was last polled - * - * @return long time in milliseconds when this peer was last polled in - * milliseconds since "the epoch", namely January 1, 1970, 00:00:00 - * GMT. - * - */ - public long getTimestamp() { - return timestamp; - } - - /** - * sets the time when this peer was last polled - * - * @param milliseconds time in milliseconds when this peer was last polled - * in milliseconds since "the epoch", namely January 1, 1970, 00:00:00 - * GMT. - * - */ - public void setTimestamp(long milliseconds) { - this.timestamp = milliseconds; - } - - public abstract Document getDocument(MimeMediaType encodeAs); - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PipeAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PipeAdvertisement.java deleted file mode 100644 index a1db2691..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PipeAdvertisement.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.id.ID; - - -/** - * Describes a JXTA Pipe. A pipe is described by a pipe id and by a pipe type. - * A pipe can also optionally have a name and/or a description. - * - * @see net.jxta.pipe.PipeService - * @see JXTA Protocols Specification : Pipe Binding Protocol - */ -public abstract class PipeAdvertisement extends ExtendableAdvertisement implements Cloneable { - - /** - * XML tag to store the PipeID - */ - public static final String IdTag = "Id"; - - /** - * XML tag to store the Pipe Type - */ - public static final String TypeTag = "Type"; - - /** - * XML tag to store the name of the Pipe - */ - public static final String NameTag = "Name"; - - /** - * XML tag to store the name of the Pipe - */ - public static final String descTag = "Desc"; - - private transient ID pipeId = ID.nullID; - private String type = null; - private String name = null; - - /** - * Descriptive meta-data about this pipe. - */ - private Element description = null; - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:PipeAdvertisement"; - } - - /** - * {@inheritDoc} - */ - @Override - public PipeAdvertisement clone() { - try { - PipeAdvertisement likeMe = (PipeAdvertisement) super.clone(); - - likeMe.setPipeID(getPipeID()); - likeMe.setType(getType()); - likeMe.setName(getName()); - likeMe.setDesc(getDesc()); - - return likeMe; - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - - if (obj instanceof PipeAdvertisement) { - PipeAdvertisement likeMe = (PipeAdvertisement) obj; - - if (!getPipeID().equals(likeMe.getPipeID())) { - return false; - } - - if (!getType().equals(likeMe.getType())) { - return false; - } - - String pipeName = getName(); - - if (pipeName == null ? likeMe.getName() != null : !pipeName.equals(likeMe.getName())) { - return false; - } - - String pipeDescription = getDescription(); - - return !(pipeDescription == null ? likeMe.getDescription() != null : pipeDescription.equals(likeMe.getDescription())); - } - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - - int result = 17; - - result = 37 * result + getPipeID().hashCode(); - result = 37 * result + getType().hashCode(); - String pipeName = getName(); - - if (pipeName != null) { - result = 37 * result + pipeName.hashCode(); - } - String pipeDescription = getDescription(); - - if (pipeDescription != null) { - result = 37 * result + pipeDescription.hashCode(); - } - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - * - *

      The PipeID uniquely identifies this ADV. - */ - @Override - public ID getID() { - ID result = getPipeID(); - - if (null == result) { - result = ID.nullID; - } - return result; - } - - /** - * Return the pipe ID for the pipe described by this advertisement. - * - * @return The pipe ID for the pipe described by this advertisement. - */ - public ID getPipeID() { - return pipeId; - } - - /** - * Set the pipe ID for the pipe described by this advertisement. - * - * @param pipeId The pipe ID for the pipe described by this advertisement. - */ - public void setPipeID(ID pipeId) { - this.pipeId = pipeId; - } - - /** - * Return the pipe type for the pipe described by this advertisement. - * - * @return The pipe type for the pipe described by this advertisement. - */ - public String getType() { - return type; - } - - /** - * Set the pipe type for the pipe described by this advertisement. - * - * @param type The pipe type for the pipe described by this advertisement. - */ - public void setType(String type) { - this.type = type; - } - - /** - * Return the symbolic name for the pipe described by this advertisement. - * - * @return String The symbolic name for the pipe described by this advertisement. - */ - public String getName() { - return name; - } - - /** - * Set the symbolic name for the pipe described by this advertisement. - * - * @param name The symbolic name for the pipe described by this advertisement. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the description - * - * @return String the description - */ - public String getDescription() { - if (null != description) { - return (String) description.getValue(); - } - return null; - } - - /** - * Set the description meta-data for the pipe described by this advertisement. - * - * @param description The description meta-data for the pipe described by this advertisement. - */ - public void setDescription(String description) { - - if (null != description) { - StructuredDocument newdoc = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Desc", description); - - setDesc(newdoc); - } else { - this.description = null; - } - } - - /** - * Return the description meta-data for the pipe described by this advertisement. - * - * @return The description meta-data for the pipe described by this advertisement. - */ - public StructuredDocument getDesc() { - if (null != description) { - StructuredDocument newDoc = StructuredDocumentUtils.copyAsDocument(description); - - return newDoc; - } - return null; - } - - /** - * Set the description meta-data for the pipe described by this advertisement. - * - * @param desc The description meta-data for the pipe described by this advertisement. - */ - public void setDesc(Element desc) { - - if (null != desc) { - this.description = StructuredDocumentUtils.copyAsDocument(desc); - } else { - this.description = null; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PipeResolverMessage.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PipeResolverMessage.java deleted file mode 100644 index 727af617..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/PipeResolverMessage.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.Document; -import net.jxta.document.MimeMediaType; -import net.jxta.id.ID; -import net.jxta.peer.PeerID; -import net.jxta.pipe.PipeID; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - - -/** - * This abstract class defines the PipeResolver Message. - *

      - *

      This message is part of the Pipe Resolver Protocol. - * - * @see net.jxta.pipe.PipeService - * @see net.jxta.protocol.PipeAdvertisement - * @see JXTA Protocols Specification : Standard JXTA Protocols - */ -public abstract class PipeResolverMessage { - - /** - * The type of message this object is communicating. - */ - private MessageType msgType = null; - - /** - * The pipe which is the subject of this message. - */ - private ID pipeid = ID.nullID; - - /** - * The type of the pipe which is the subject of this message. - */ - private String pipeType = null; - - /** - *

        - *
      • For query : The peer ids which should respond to this query.
      • - *
      • For response : The peer id on which is responding.
      • - *
      - */ - private Set peerids = new HashSet(); - - /** - * For responses, if true then this message indicates the pipe is present - * otherwise the pipe is not present. - */ - private boolean found = true; - - /** - *
        - *
      • For query : The peer advertisement of the querying peer.
      • - *
      • For response : The peer advertisement of the responding peer.
      • - *
      - */ - private PeerAdvertisement inputPeerAdv = null; - - /** - * An enumeration class for message types. - */ - public enum MessageType { - - /** - * A query message - */ - QUERY, /** - * A response message - */ ANSWER - } - - /** - * Creates a new unintialized pipe resolver message - */ - public PipeResolverMessage() { - super(); - } - - /** - * returns the Message type. This will match the XML doctype declaration. - * - * @return a string - */ - public static String getMessageType() { - return "jxta:PipeResolver"; - } - - /** - * Write message into a document. asMimeType is a mime media-type - * specification and provides the form of the document which is being - * requested. Two standard document forms are defined. "text/plain" encodes - * the document in "pretty-print" format for human viewing and "text/xml" - * which provides an XML format. - * - * @param asMimeType MimeMediaType format representation requested - * @return Document the document to be used in the construction - */ - public abstract Document getDocument(MimeMediaType asMimeType); - - /** - * Returns whether this message is a query or a response. - * - * @return the type of this message. - */ - public MessageType getMsgType() { - return msgType; - } - - /** - * Sets the message type of this message. - * - * @param type the type this message is to be. - */ - public void setMsgType(MessageType type) { - msgType = type; - } - - /** - * Return the id of the pipe which is the subject of this message. - * - * @return the id of the pipe which is the subject of this message. - */ - public ID getPipeID() { - return pipeid; - } - - /** - * Set the id of pipe which is to be subject of this message. - * - * @param id the pipe id which is the subject of this message. - */ - public void setPipeID(ID id) { - - if (!(id instanceof PipeID)) { - throw new IllegalArgumentException("can only set to pipe ids."); - } - - pipeid = id; - } - - /** - * Return the pipe type of the pipe which is the subject of this message. - * - * @return the pipe type of the pipe which is the subject of this message. - */ - public String getPipeType() { - return pipeType; - } - - /** - * Set the pipe type of the pipe which is the subject of this message. - * - * @param type The pipe type of the pipe which is to be the subject of this - * message. - */ - public void setPipeType(String type) { - pipeType = type; - } - - // Query - - /** - * Returns a {@link java.util.Set} (possibly empty) containing the peer ids - * which should respond to this query. - * - * @return set containing the peer ids to which this peer is directed. - */ - public Set getPeerIDs() { - - return Collections.unmodifiableSet(peerids); - } - - /** - * Add a peer to the set of peers to which this query is directed. - * - * @param id the peer id to add. - */ - public void addPeerID(ID id) { - - if (!(id instanceof PeerID)) { - throw new IllegalArgumentException("can only add peer ids"); - } - - peerids.add(id); - } - - // Answer - - /** - * If true then the pipe was found ont he - * - * @return true if found - */ - public boolean isFound() { - return found; - } - - public void setFound(boolean isFound) { - found = isFound; - } - - public PeerAdvertisement getInputPeerAdv() { - return inputPeerAdv; - } - - public void setInputPeerAdv(PeerAdvertisement peerAdv) { - inputPeerAdv = peerAdv; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RdvAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RdvAdvertisement.java deleted file mode 100644 index 8af48830..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RdvAdvertisement.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.protocol; - - -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroupID; - - -/** - * This class defines a Rendezvous Advertisement. This advertisement is indexed - * on "RdvGroupId", "RdvPeerId", and "RdvServiceName" - */ -public abstract class RdvAdvertisement extends ExtendableAdvertisement { - - /** - * GroupID tag - */ - public final static String GroupIDTag = "RdvGroupId"; - - /** - * Name tag - */ - public final static String NameTag = "Name"; - - /** - * Rendezvous ID tag - */ - public final static String PeerIDTag = "RdvPeerId"; - - /** - * Route tage - */ - public final static String RouteTag = "RdvRoute"; - - /** - * Rendezvous service name tag - */ - public final static String ServiceNameTag = "RdvServiceName"; - - private PeerGroupID groupId = null; - - private transient ID hashID = null; - private String name = null; - private PeerID peerId = null; - private RouteAdvertisement route = null; - private String serviceName = null; - - /** - * Returns the identifying type of this Advertisement. - * - *@return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:RdvAdvertisement"; - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * get the group id - * - *@return String PeerGroupID - */ - public PeerGroupID getGroupID() { - return groupId; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized ID getID() { - - if (groupId == null) { - throw new IllegalStateException("cannot build ID: no group id"); - } - - if (peerId == null) { - throw new IllegalStateException("cannot build ID: no peer id"); - } - - if (serviceName == null) { - throw new IllegalStateException("cannot build ID: no Service Name"); - } - - if (hashID == null) { - try { - // We have not yet built it. Do it now - String seed = getAdvertisementType() + groupId.toString() + serviceName + peerId.toString(); - - InputStream in = new ByteArrayInputStream(seed.getBytes()); - - hashID = IDFactory.newCodatID(groupId, seed.getBytes(), in); - } catch (Exception ez) { - IllegalStateException failure = new IllegalStateException("cannot build ID"); - - failure.initCause(ez); - throw failure; - } - } - return hashID; - } - - /** - * get the symbolic name associated with the rdv - * - *@return String the name field. null is returned if no name has been - * associated with the advertisement. - */ - public String getName() { - - return name; - } - - /** - * get the rdv peer id - * - *@return PeerID - */ - public PeerID getPeerID() { - return peerId; - } - - /** - * Get the Route Adv. - * - *@return RouteAdvertisement or null if no - */ - public RouteAdvertisement getRouteAdv() { - return route; - } - - /** - * get the rdv service name - * - *@return String name - */ - public String getServiceName() { - - return serviceName; - } - - /** - * set the group Id - * - *@param id The new groupID value - */ - public void setGroupID(PeerGroupID id) { - groupId = id; - } - - /** - * set the symbolic name associated with the rdv - * - *@param n the name this rdv adv should have. - */ - public void setName(String n) { - name = n; - } - - /** - * set the peer Id - * - *@param id The new peerID value - */ - public void setPeerID(PeerID id) { - peerId = id; - } - - /** - * set the RouteAdvertisement - * - *@param route RouteAdvertisement - */ - public void setRouteAdv(RouteAdvertisement route) { - this.route = route; - } - - /** - * set the service name - * - *@param n The new serviceName value - */ - - public void setServiceName(String n) { - serviceName = n; - } - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ResolverQueryMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ResolverQueryMsg.java deleted file mode 100644 index 1ad545ae..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ResolverQueryMsg.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.protocol; - -import java.net.URI; - -import net.jxta.document.Document; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.id.ID; - -/** - * Generic Resolver Service message "Query". - * - * @see net.jxta.resolver.ResolverService - * @see net.jxta.protocol.ResolverResponseMsg - * @see JXTA Protocols Specification : Peer Resolver Protocol - */ -public abstract class ResolverQueryMsg { - - /** - * credential - */ - private StructuredDocument credential = null; - - /** - * Resolver query handler - */ - private String handlername = null; - - /** - * Number of times a message has been forwarded, not propagated or walked - */ - protected int hopcount = 0; - - /** - * Resolver query - */ - private String query = null; - - /** - * Query ID of this query. Unique to the originating node only, it can be - * utilized to match queries to responses. - */ - protected int queryid = 0; - - /** - * issuer of the query - */ - private ID srcPeerId = null; - - /** - * Optional route info about the issuer - */ - private RouteAdvertisement srcPeerRoute = null; - - /** - * returns the credential - * - * @return String credential - */ - public StructuredDocument getCredential() { - return credential; - } - - /** - * Write advertisement into a document. asMimeType is a mime media-type - * specification and provides the form of the document which is being - * requested. Two standard document forms are defined. 'text/text' encodes - * the document in a form nice for printing out and 'text/xml' which - * provides an XML format. - * - * @param asMimeType mime-type requested representation for the returned - * document - * @return Document document representing the advertisement - */ - public abstract Document getDocument(MimeMediaType asMimeType); - - /** - * returns the handlername - * - * @return String handlername name - */ - public String getHandlerName() { - return handlername; - } - - /** - * returns the hop count - * - * @return int hop count - */ - public int getHopCount() { - return hopcount; - } - - /** - * increment hop count - */ - public void incrementHopCount() { - hopcount++; - } - - /** - * Set hop count - * - * @param newCount hop count - */ - public void setHopCount(int newCount) { - hopcount = newCount; - } - - /** - * returns the query - * - * @return String value of the query - */ - public String getQuery() { - return query; - } - - /** - * returns queryid value - * - * @return int queryid value - */ - public int getQueryId() { - return queryid; - } - - /** - * Returns the source of the query - * - * @return String the peerid of the source of the query - * @deprecated Use {@link #getSrcPeer()} instead. - */ - @Deprecated - public String getSrc() { - return (null == srcPeerId) ? null : srcPeerId.toString(); - } - - /** - * Returns the source of the query - * - * @return The peerid of the source of the query - */ - public ID getSrcPeer() { - return (null == srcPeerId) ? null : srcPeerId; - } - - /** - * Returns the source route of the query - * - * @return RouteAdvertisement route to the issuer of the query - */ - - public RouteAdvertisement getSrcPeerRoute() { - if (srcPeerRoute == null) { - return null; - } else { - return srcPeerRoute.clone(); - } - } - - /** - * set the credential - * - * @param cred string representing credential - */ - public void setCredential(StructuredDocument cred) { - this.credential = cred; - } - - /** - * set the handlername - * - * @param name handler name - */ - public void setHandlerName(String name) { - this.handlername = name; - } - - /** - * set the Query string - * - * @param Query string representing the query - */ - public void setQuery(String Query) { - this.query = Query; - } - - /** - * set the query id. Each query has a unique id. - * - * @param id int id - */ - public void setQueryId(int id) { - queryid = id; - } - - /** - * set the source route of the query - * - * @param route route advertisement of the source peer - */ - public void setSrcPeerRoute(RouteAdvertisement route) { - srcPeerRoute = route; - } - - /** - * Set the source of the query - * - * @param src is a containing the peerid of the source - * @deprecated Use {@link #setSrcPeer(ID)} instead. - */ - @Deprecated - public void setSrc(String src) { - if (null == src) { - setSrcPeer(null); - } else { - setSrcPeer(ID.create(URI.create(src))); - } - } - - /** - * Set the source of the query - * - * @param srcPeer the peerid of the source - */ - public void setSrcPeer(ID srcPeer) { - srcPeerId = srcPeer; - } - - /** - * All messages have a type (in xml this is !doctype) which identifies the - * message - * - * @return String "jxta:ResolverQuery" - */ - public static String getAdvertisementType() { - return "jxta:ResolverQuery"; - } - - /** - * Create a ResolverResponse from a ResolverQuery message. This method - * takes advantage of any internal information available in an incoming - * Resolver query to build a resolver response for that query. For instance, - * optional route information which may be available in the query will - * be used to bypass the route resolution to send the response. - *

      - * WARNING: A side effect of this call is that the following fields are - * transfered from the query to the response: - * - HandlerName - * - QueryId - * - * @return ResolverResponseMsg resolverResponse built from the resolverQuery msg - */ - public abstract ResolverResponseMsg makeResponse(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ResolverResponseMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ResolverResponseMsg.java deleted file mode 100644 index 2eb7734f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ResolverResponseMsg.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.protocol; - - -import net.jxta.document.Document; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; - - -/** - * Generic Resolver Service message "Response". - * - * @see net.jxta.resolver.ResolverService - *@see net.jxta.protocol.ResolverQueryMsg - * @see JXTA Protocols Specification : Peer Resolver Protocol - **/ -public abstract class ResolverResponseMsg { - private StructuredDocument credential = null; - - private String handlername = null; - - /** - * Description of the Field - */ - public int queryid = 0; - - private String response = null; - - /** - * returns the credential - * - *@return StructuredDocument credential - */ - public StructuredDocument getCredential() { - return credential; - } - - /** - * Write advertisement into a document. asMimeType is a mime media-type - * specification and provides the form of the document which is being - * requested. Two standard document forms are defined. "text/text" encodes - * the document in a form nice for printing out and "text/xml" which - * provides an XML format. - * - *@param asMimeType mime-type representation requested for that document - *@return Document document representing the advertisement - */ - public abstract Document getDocument(MimeMediaType asMimeType); - - /** - * Set optional route information as part of the response. This - * information is just attached to the response and is ONLY used by the - * resolver service. This information will not be sent as part of the - * response msg and is not part of the resolver response wire format - * protocol. - * - * @param route RouteAdvertisement to send the response - */ - public abstract void setSrcPeerRoute(RouteAdvertisement route); - - /** - * Get optional route information that may be attached to the - * response. This information is just attached to the response and - * is only used internally by the resolver service. This information will - * not be sent as part of the response msg and is not part of the - * resolver response wire format. - * - * @return RouteAdvertisement to send the response - */ - public abstract RouteAdvertisement getSrcPeerRoute(); - - /** - * returns the handlername - * - *@return String handlername name - */ - public String getHandlerName() { - return handlername; - } - - /** - * returns queryid value - * - *@return int queryid value - */ - public int getQueryId() { - return queryid; - } - - /** - * returns the response body for this message. - * - *@return the response body represented as a string. - */ - public String getResponse() { - return response; - } - - /** - * set the credential for this response. - * - *@param cred string credential - */ - - public void setCredential(StructuredDocument cred) { - this.credential = cred; - } - - /** - * set the handlername - * - *@param name string handlername - */ - public void setHandlerName(String name) { - this.handlername = name; - } - - /** - * set the query id to which this message is a response. - * - *@param id the query id for this response. - */ - public void setQueryId(int id) { - this.queryid = id; - } - - /** - * Set the response body for this message. - * - *@param response response body as a string. - */ - public void setResponse(String response) { - this.response = response; - } - - /** - * All messages have a type (in xml this is !doctype) which identifies the - * message - * - *@return String type of the advertisement - */ - public static String getAdvertisementType() { - return "jxta:ResolverResponse"; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ResolverSrdiMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ResolverSrdiMsg.java deleted file mode 100644 index ea12ce67..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/ResolverSrdiMsg.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.protocol; - - -import net.jxta.document.Document; -import net.jxta.document.MimeMediaType; -import net.jxta.credential.Credential; - - -/** - * ResolverSrdiMsg is generic resolver wrapper for Services that wish to - * implement their own distribution of indices. this message provides the - * scoping within the group, and service. In addition it also defines a credential - * which should be verified by the service. - */ - -public abstract class ResolverSrdiMsg { - - private String handlername = null; - private Credential credential = null; - private String payload = null; - - /** - * All messages have a type (in xml this is !doctype) - * which identifies the message - * - * @return String type of the advertisement - */ - - public static String getMessageType() { - return "jxta:ResolverSRDI"; - } - - /** - * returns the handlername - * - * @return String handlername name - * - */ - - public String getHandlerName() { - return handlername; - } - - /** - * returns the credential - * - * @return StructuredDocument credential - */ - - public Credential getCredential() { - return credential; - } - - /** - * returns the payload - * - * @return String value of query - */ - - public String getPayload() { - return payload; - } - - /** - * set the handlername - * - * @param name string handlername - */ - - public void setHandlerName(String name) { - this.handlername = name; - } - - /** - * set the credential object - * - * @param cred credential - */ - - public void setCredential(Credential cred) { - this.credential = cred; - } - - /** - * set the SRDI payload - * - * @param payload The new payload value - */ - - public void setPayload(String payload) { - this.payload = payload; - } - - /** - * Write advertisement into a document. asMimeType is a mime media-type - * specification and provides the form of the document which is being - * requested. Two standard document forms are defined. "text/text" encodes - * the document in a form nice for printing out and "text/xml" which - * provides an XML format. - * - * @param asMimeType mime-type representation requested for that document - * @return Document document representing the advertisement - */ - - public abstract Document getDocument(MimeMediaType asMimeType); - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RouteAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RouteAdvertisement.java deleted file mode 100644 index 6748e78c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RouteAdvertisement.java +++ /dev/null @@ -1,859 +0,0 @@ -/* -Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.protocol; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroupID; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; -import java.util.Vector; - -/** - * Advertisement used to represent a route to a peer. Routes are represented in - * a generic manner as a sequence of hops to reach the destination. Each hop - * represent a potential relay peer in the route: - *

      - *

       Dest
      - *       hop 1
      - *       hop 2
      - *       hop 3
      - *       ....
      - *       hop n
      - * 
      - *

      - * A route can have as many hops as necessary. Hops are implicitly ordered - * starting from the hop with the shortest route to reach the destination. If a - * peer cannot reach directly the dest, it should try to reach in descending - * order one of the listed hops. Some hops may have the same physical distance - * to the destination. Some hops may define alternative routes. - *

      - * The destination and hops are defined using a AccessPointAdvertisements. - * - * @see net.jxta.protocol.PeerAdvertisement - * @see net.jxta.protocol.AccessPointAdvertisement - */ -public abstract class RouteAdvertisement extends ExtendableAdvertisement implements Cloneable { - - public static final String DEST_PID_TAG = "DstPID"; - - /** - * AccessPointAdvertisement of destination peer. - */ - private transient AccessPointAdvertisement dest = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - /** - * Semi-ordered list of alternative hops to the destination. - */ - private transient Vector hops = new Vector(); - - /** - * Cached value for {@link #getID()} - */ - private transient ID hashID = null; - - /** - * construct a new route - *

      - * WARNING hops may be MODIFIED. - * - * @param destPid destination - * @param firsthop first hop node ID - * @param hops routes - * @return the new route - */ - public static RouteAdvertisement newRoute(PeerID destPid, PeerID firsthop, Vector hops) { - - if (destPid == null) { - throw new IllegalArgumentException("Missing destination peer id."); - } - - for (AccessPointAdvertisement apa : hops) { - if (null == apa) { - throw new IllegalArgumentException("Bad route. null APA."); - } - - if (apa.getPeerID() == null) { - throw new IllegalArgumentException("Bad route. Incomplete APA."); - } - } - - RouteAdvertisement route = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - - route.setDestPeerID(destPid); - - // set the route hops - route.setHops(hops); - - // check if the given first hop is already in the route if not add it - // (note: we do not expect it to be there, but it is acceptable). - if (firsthop != null) { - AccessPointAdvertisement ap = route.getFirstHop(); - - if (ap == null || !ap.getPeerID().equals(firsthop)) { - ap = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - ap.setPeerID(firsthop); - route.setFirstHop(ap); - } - } - - return route; - } - - /** - * {@inheritDoc} - */ - @Override - public RouteAdvertisement clone() { - try { - RouteAdvertisement a = (RouteAdvertisement) super.clone(); - - a.setDest(getDest()); - - // deep copy of the hops - Vector clonehops = getVectorHops(); - - ListIterator eachHop = clonehops.listIterator(); - - while (eachHop.hasNext()) { - eachHop.set(eachHop.next().clone()); - } - - a.setHops(clonehops); - - return a; - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - } - - /** - * makes a copy of a route advertisement - * that only contains PID not endpoint addresses - * - * @return object clone route advertisement - */ - public RouteAdvertisement cloneOnlyPIDs() { - RouteAdvertisement routeAdvertisement; - - try { - routeAdvertisement = (RouteAdvertisement) super.clone(); - routeAdvertisement.setDestEndpointAddresses(new Vector()); - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - - // deep copy of the hops - Vector clonehops = routeAdvertisement.getVectorHops(); - - ListIterator eachHop = clonehops.listIterator(); - - while (eachHop.hasNext()) { - AccessPointAdvertisement aHop = eachHop.next(); - - eachHop.set(aHop.clone()); - } - - routeAdvertisement.setHops(clonehops); - return routeAdvertisement; - } - - /** - * Compare if two routes are equals. Equals means same destination with the - * same endpoint addresses and thee same number of hops and the same - * endpoint addresses for each hop. - * - * @param target the route to compare against - * @return boolean true if the route is equal to this route otherwise false - */ - @Override - public boolean equals(Object target) { - - if (this == target) { - return true; - } - - if (!(target instanceof RouteAdvertisement)) { - return false; - } - - RouteAdvertisement route = (RouteAdvertisement) target; - - // check the destination - if (!dest.equals(route.getDest())) { - return false; - } - - // check each of the hops - - // routes need to have the same size - if (hops.size() != route.size()) { - return false; - } - - int index = 0; - - for (AccessPointAdvertisement hop : route.hops) { - if (!hop.equals(hops.get(index++))) { - return false; - } - } - - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - if (null != dest.getPeerID()) { - return dest.getPeerID().hashCode(); - } else { - // force all incomplete advertisements to hash to the same place. - return 1; - } - } - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:RA"; - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized ID getID() { - if (null == dest.getPeerID()) { - throw new IllegalStateException("Destination peerID not defined. Incomplete RouteAdvertisement"); - } - - if (hashID == null) { - try { - // We have not yet built it. Do it now - byte[] seed = getAdvertisementType().getBytes("UTF-8"); - InputStream in = new ByteArrayInputStream(dest.getPeerID().toString().getBytes("UTF-8")); - - hashID = IDFactory.newCodatID((PeerGroupID) dest.getPeerID().getPeerGroupID(), seed, in); - } catch (Exception ez) { - return ID.nullID; - } - } - return hashID; - } - - /** - * Returns the route destination Peer ID - * - * @return peerID of the destination of the route - */ - public PeerID getDestPeerID() { - return dest.getPeerID(); - } - - /** - * Sets the route destination peer id. - * - * @param pid route destination peerID - */ - public void setDestPeerID(PeerID pid) { - if ((null != pid) && (null != dest.getPeerID()) && (!pid.equals(dest.getPeerID()))) { - throw new IllegalStateException("Changing the peer id of the destination APA." + pid + " != " + dest.getPeerID()); - } - - dest.setPeerID(pid); - - // recalculate hash. - synchronized (this) { - hashID = null; - } - } - - /** - * Returns the destination access point. This does NOT copy - * the AccessPointAdvertisement. - * - * @return AccessPointAdvertisement of the destination peer. - * @deprecated Because this method unsafely exposes destination AccessPointAdvertisement it will be removed. - */ - @Deprecated - public AccessPointAdvertisement getDest() { - return dest; - } - - /** - * Sets the access point of the destination. This does NOT copy - * the AccessPointAdvertisement. - * - * @param ap AccessPointAdvertisement of the destination peer - */ - public void setDest(AccessPointAdvertisement ap) { - PeerID destPid = dest.getPeerID(); - - this.dest = ap.clone(); - - if ((null != destPid) && (null != dest.getPeerID()) && (!destPid.equals(dest.getPeerID()))) { - throw new IllegalStateException("Changed the peer id of the destination APA." + destPid + " != " + dest.getPeerID()); - } - - if (null != destPid) { - dest.setPeerID(destPid); - } - - // recalculate hash. - synchronized (this) { - hashID = null; - } - } - - /** - * Add a new list of EndpointAddresses to the Route Destination access - * point - * - * @param addresses vector of endpoint addresses to add to the - * destination access point. Warning: The vector of endpoint addresses - * is specified as a vector of String. Each string representing - * one endpoint address. - * @deprecated Use {@link #addDestEndpointAddresses(List)} instead. - */ - @Deprecated - public void addDestEndpointAddresses(Vector addresses) { - dest.addEndpointAddresses(addresses); - } - - /** - * Clears all endpoint addresses associated with the destination peer. - */ - public void clearDestEndpointAddresses() { - dest.clearEndpointAddresses(); - } - - /** - * Add the specified endpoint address to destination peer. - * - * @param addr EndpointAddress to add. - */ - public void addDestEndpointAddress(EndpointAddress addr) { - dest.addEndpointAddress(addr); - } - - /** - * Add all of the specified endpoint addresses to destination peer. - * - * @param addrs EndpointAddresses to add. - */ - public void addDestEndpointAddresses(List addrs) { - dest.addEndpointAddresses(addrs); - } - - /** - * Remove the specified endpoint address to destination peer. - * - * @param addr EndpointAddress to add. - */ - public void removeDestEndpointAddress(EndpointAddress addr) { - dest.removeEndpointAddress(addr); - } - - /** - * Remove the specified endpoint addresses from destination peer. - * - * @param addrs EndpointAddress to add. - */ - public void removeDestEndpointAddresses(Collection addrs) { - dest.removeEndpointAddresses(addrs); - } - - /** - * Remove a list of EndpointAddresses from the Route Destination - * access point - * - * @param addresses vector of endpoint addresses to remove from the - * destination access point. - * @deprecated Use {@link #removeDestEndpointAddresses(Collection)}. - */ - @Deprecated - public void removeDestEndpointAddresses(Vector addresses) { - dest.removeEndpointAddresses(addresses); - } - - /** - * Returns the endpoint addresses of the destination peer in their - * preferred order. - * - * @return The {@code EndpointAddress}es of the destination peer. - */ - public List getDestEndpointAddresses() { - List result = new ArrayList(); - - Enumeration eachEA = dest.getEndpointAddresses(); - - while (eachEA.hasMoreElements()) { - result.add(new EndpointAddress(eachEA.nextElement())); - } - - return result; - } - - /** - * Set the route destination endpoint addresses - * - * @param ea vector of endpoint addresses. Warning: The vector is not copied - * and is used directly. - * @deprecated Use {@link #addDestEndpointAddress(EndpointAddress)} instead. - */ - @Deprecated - public void setDestEndpointAddresses(Vector ea) { - dest.setEndpointAddresses(ea); - } - - /** - * returns the list of hops - * - * @return Enumeration list of hops as AccessPointAdvertisement - */ - public Enumeration getHops() { - return hops.elements(); - } - - /** - * returns the list of hops - * - * @return Vector list of hops as AccessPointAdvertisement - */ - public Vector getVectorHops() { - return hops; - } - - /** - * Sets the list of hops associated with this route. - * - * @param newHops AccessPointAdvertisements which form the hops. The - * Vector is NOT copied. - */ - public void setHops(Vector newHops) { - // It is legal to set it to null but it is automatically converted - // to an empty vector. The member hops is NEVER null. - if (null == newHops) { - hops = new Vector(); - } else { - for (AccessPointAdvertisement hop : newHops) { - if (null == hop.getPeerID()) { - throw new IllegalArgumentException("Bad hop"); - } - } - - hops = newHops; - } - } - - /** - * Check if the route contains the following hop - * - * @param pid peer id of the hop - * @return boolean true or false if the hop is found in the route - */ - public boolean containsHop(PeerID pid) { - for (AccessPointAdvertisement hop : hops) { - PeerID hid = hop.getPeerID(); - - if (pid.equals(hid)) { - return true; - } - } - return false; - } - - /** - * Returns the AccessPointAdvertisement of first hop. The - * AccessPointAdvertisement is not cloned. - * - * @return AccessPointAdvertisement of first hop. - */ - public AccessPointAdvertisement getFirstHop() { - return hops.isEmpty() ? null : hops.firstElement(); - } - - /** - * Sets the AccessPointAdvertisement for the first hop. The - * AccessPointAdvertisement is not cloned. - * - * @param ap AccessPointAdvertisement of the first hop. - */ - public void setFirstHop(AccessPointAdvertisement ap) { - if (null == ap.getPeerID()) { - throw new IllegalArgumentException("Bad hop"); - } - - hops.add(0, ap); - } - - /** - * Returns the access point for the last hop. The - * AccessPointAdvertisement is not cloned. - * - * @return AccessPointAdvertisement last hop. - */ - public AccessPointAdvertisement getLastHop() { - return hops.isEmpty() ? null : hops.lastElement(); - } - - /** - * Sets the AccessPointAdvertisement of the last hop. The - * AccessPointAdvertisement is not cloned. - * - * @param ap AccessPointAdvertisement of the last hop. - */ - public void setLastHop(AccessPointAdvertisement ap) { - if (null == ap.getPeerID()) { - throw new IllegalArgumentException("Bad hop"); - } - - hops.add(ap); - } - - /** - * check if the route has a loop - * - * @return boolean true or false if the route has a loop - */ - public boolean hasALoop() { - // Now check for any other potential loops. - - Set seenPeers = new HashSet(hops.size()); - - for (AccessPointAdvertisement anAPA : hops) { - PeerID pid = anAPA.getPeerID(); - - if (seenPeers.contains(pid)) { - return true; // There is a loop. - } - - seenPeers.add(pid); - } - return false; - } - - /** - * return the length of the route - * - * @return int size of the route - */ - public int size() { - return hops.size(); - } - - /** - * Return the hop that follows the specified currentHop. The - * AccessPointAdvertisement is not cloned. - * - * @param currentHop PeerID of the current hop - * @return ap AccessPointAdvertisement of the next Hop - */ - public AccessPointAdvertisement nextHop(PeerID currentHop) { - - // check if we have a real route - if (hops.isEmpty()) { - // Empty vector. - return null; - } - - // find the index of the route - int index = 0; - boolean found = false; - - for (AccessPointAdvertisement ap : hops) { - if (currentHop.equals(ap.getPeerID())) { - found = true; - break; - } - index++; - } - - AccessPointAdvertisement nextHop = null; - - if (!found) { - // The peer is not into the list. Since we have got that message, - // the best we can do is to send it to the first gateway in the - // forward path. - nextHop = hops.get(0); - } else { - // Found the peer within the vector of hops. Get the next hop. - if (index < hops.size()) { - nextHop = hops.get(index); - } - } - - return nextHop; - } - - /** - * Generate a string that displays the route - * information for logging or debugging purpose - * - * @return String return a string containing the route info - */ - public String display() { - StringBuilder routeBuf = new StringBuilder(); - - routeBuf.append("Dest APA : "); - AccessPointAdvertisement dest = getDest(); - - routeBuf.append(dest.display()); - routeBuf.append("\n"); - - int i = 1; - Enumeration e = getHops(); - - while (e.hasMoreElements()) { - AccessPointAdvertisement hop = e.nextElement(); - - if (i == 1) { - routeBuf.append("HOPS = "); - } - routeBuf.append("\n\t[").append(i++).append("] "); - - routeBuf.append(hop.display()); - } - return routeBuf.toString(); - } - - /** - * Remove a hop from the list of hops. - * - * @param pid peer id of the hop - * @return boolean true or false if the hop is found in the route - */ - public boolean removeHop(PeerID pid) { - Iterator eachHop = hops.iterator(); - - while (eachHop.hasNext()) { - AccessPointAdvertisement hop = eachHop.next(); - PeerID hid = hop.getPeerID(); - - if (pid.equals(hid)) { - eachHop.remove(); - return true; - } - } - - return false; - } - - /** - * Return a hop from the list of hops. - * - * @param pid peer id of the hop - * @return AccessPointAdvertisement of the corresponding hop - */ - public AccessPointAdvertisement getHop(PeerID pid) { - for (AccessPointAdvertisement hop : hops) { - PeerID hid = hop.getPeerID(); - - if (pid.equals(hid)) { - return hop.clone(); - } - } - return null; - } - - /** - * Alter the given newRoute (which does not start from here) by using firstLeg, a known route to whence - * it starts from. So that the complete route goes from here to the end-destination via firstLeg. - * public static boolean stichRoute(RouteAdvertisement newRoute, - * - * @param newRoute the new route - * @param firstLeg the first route - * @return true if successful - */ - public static boolean stichRoute(RouteAdvertisement newRoute, RouteAdvertisement firstLeg) { - return stichRoute(newRoute, firstLeg, null); - } - - /** - * Alter the given newRoute (which does not start from here) by using firstLeg, a known route to whence - * it starts from. So that the complete route goes from here to the end-destination via firstLeg - * also shortcut the route by removing the local peer. - * - * @param newRoute the new route - * @param firstLeg first hop - * @param localPeer local PeerID - * @return true if successful - */ - public static boolean stichRoute(RouteAdvertisement newRoute, RouteAdvertisement firstLeg, PeerID localPeer) { - - if (newRoute.hasALoop()) { - return false; - } - - Vector hops = newRoute.getVectorHops(); - - // Make room - hops.ensureCapacity(firstLeg.getVectorHops().size() + 1 + hops.size()); - - // prepend the routing peer unless the routing peer happens to be - // in the route already. That happens if the routing peer is the relay. - // or if the route does not have a first leg - PeerID routerPid = firstLeg.getDest().getPeerID(); - - if (newRoute.size() == 0 || (!newRoute.getFirstHop().getPeerID().equals(routerPid))) { - AccessPointAdvertisement ap = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - // prepend the route with the routing peer. - ap.setPeerID(routerPid); - hops.add(0, ap); - } - - // prepend the rest of the route - hops.addAll(0, firstLeg.getVectorHops()); - - // remove any loop from the root - cleanupLoop(newRoute, localPeer); - return true; - } - - /** - * Remove loops from the route advertisement - * by shortcutting cycle from the route - * - * @param route the route advertisement - * @param localPeer local PeerID - */ - public static void cleanupLoop(RouteAdvertisement route, PeerID localPeer) { - - // Note: we cleanup all enp addresses except for the last hop (which we - // use to shorten routes often enough). - // If we end-up removing the last hop, it means that it is the local - // peer and thus the route ends up with a size 0. - - Vector hops = route.getVectorHops(); - Vector newHops = new Vector(hops.size()); - AccessPointAdvertisement lastHop = null; - - // Replace all by PID-only entries, but keep the last hop on the side. - if (!hops.isEmpty()) { - lastHop = hops.get(hops.size() - 1); - } - hops = (route.cloneOnlyPIDs()).getVectorHops(); - - // remove cycle from the route - for (int i = 0; i < hops.size(); i++) { - int loopAt = newHops.indexOf(hops.elementAt(i)); - - if (loopAt != -1) { // we found a cycle - - // remove all entries after loopAt - for (int j = newHops.size(); --j > loopAt;) { - newHops.remove(j); - } - } else { // did not find it so we add it - newHops.add(hops.get(i)); - } - } - - // Remove the local peer in the route if we were given one - if (localPeer != null) { - for (int i = newHops.size(); --i >= 0;) { - if (localPeer.equals(newHops.elementAt(i).getPeerID())) { - // remove all the entries up to that point we - // need to keep the remaining of the route from that - // point - for (int j = 0; j <= i; j++) { - newHops.remove(0); - } - break; - } - } - } - - if (lastHop != null && newHops.size() > 0) { - newHops.setElementAt(lastHop, newHops.size() - 1); - } - - // update the new hops in the route - route.setHops(newHops); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RouteQueryMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RouteQueryMsg.java deleted file mode 100644 index bde49265..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RouteQueryMsg.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.Document; -import net.jxta.document.MimeMediaType; -import net.jxta.peer.PeerID; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - - -/** - * This class defines the EndpointRouter RouteQuery message "Query" - *

      - * This message is part of the Endpoint Routing Protocol. - * - * @deprecated This class will be removed from the public JXTA API. It is used - * only by the standard router message transport implementation and is of no use - * to applications. - * - * @see net.jxta.protocol.RouteResponseMsg - */ -@Deprecated -public abstract class RouteQueryMsg { - - private PeerID destPID = null; - private RouteAdvertisement srcRoute = null; - private final Set badHops = new HashSet(); - - /** - * All messages have a type (in xml this is !doctype) - * which identifies the message - * - * @return String "jxta:ERQ" - */ - public static String getAdvertisementType() { - return "jxta:ERQ"; - } - - /** - * set the destination PeerID we are searching a route for - * - * @param pid destination peerID - */ - public void setDestPeerID(PeerID pid) { - destPID = pid; - } - - /** - * returns the destination peer ID we are looking for - * - * @return pid PeerID of the route destination - */ - - public PeerID getDestPeerID() { - return destPID; - } - - /** - * set the Route advertisement of the source peer that is originating - * the query - * - * @param route RouteAdvertisement of the source - */ - public void setSrcRoute(RouteAdvertisement route) { - if(null == route.getDestPeerID()) { - throw new IllegalArgumentException("route lacks destination!"); - } - - srcRoute = route.clone(); - } - - /** - * returns the route of the src peer that issued the routequery - * - * @return route RouteAdvertisement of the source peer - */ - public RouteAdvertisement getSrcRoute() { - if(null == srcRoute) { - return null; - } else { - return srcRoute.clone(); - } - } - - /** - * Adds a bad hop to the list of those known to be bad for this route. - * - * @param badHop The known bad hop for the route. - */ - public void addBadHop(PeerID badHop) { - badHops.add(badHop); - } - - /** - * Set the bad hops known into that route - * - * @param hops RouteAdvertisement of the source - */ - public void setBadHops(Collection hops) { - badHops.clear(); - if (null != hops) { - badHops.addAll(hops); - } - } - - /** - * returns the bad hops know to the route - * - * @return The known bad hops for the route - */ - public Set getBadHops() { - return new HashSet(badHops); - } - - /** - * Write message into a document. asMimeType is a mime media-type - * specification and provides the form of the document which is being - * requested. Two standard document forms are defined. "text/text" encodes - * the document in a form nice for printing out, and "text/xml" which - * provides an XML representation. - * - * @param asMimeType mime-type format requested - * @return Document representation of the document as an advertisement - */ - public abstract Document getDocument(MimeMediaType asMimeType); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RouteResponseMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RouteResponseMsg.java deleted file mode 100644 index 7bf0777f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/RouteResponseMsg.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.Document; -import net.jxta.document.MimeMediaType; - - -/** - * Sent by peers in response to Route Query Messages as part of the Endpoint - * Router Protocol (ERp). Contains a route advertisement for the destination - * peer. Route Response Messages are transmitted as responses within Resolver - * Response Message. - * - * @deprecated This message is private to the Endpoint Router implementation and - * not part of the JXTA public API. It will be moved from this package. - * - * @see net.jxta.protocol.RouteQueryMsg - * @see JXTA Protocols Specification : Endpoint Routing Protocol - **/ -@Deprecated -public abstract class RouteResponseMsg { - - private RouteAdvertisement dstRoute = null; - private RouteAdvertisement srcRoute = null; - - /** - * All messages have a type (in xml this is !doctype) - * which identifies the message - * @return String "jxta:ERR" - */ - - public static String getAdvertisementType() { - return "jxta:ERR"; - } - - /** - * set the destination route we were looking for - * - * @param dst destination route - */ - - public void setDestRoute(RouteAdvertisement dst) { - dstRoute = dst; - } - - /** - * returns the destination route we were looking for - * - * @return route destination route advertisement - */ - - public RouteAdvertisement getDestRoute() { - return dstRoute; - } - - /** - * Set the Route advertisement of the source peer that is originating - * the query - * - * @param route RouteAdvertisement of the source - */ - - public void setSrcRoute(RouteAdvertisement route) { - srcRoute = route; - } - - /** - * Returns the route of the src peer that responded - * - * @return route RouteAdvertisement of the source peer - * that responded to the query - */ - - public RouteAdvertisement getSrcRoute() { - return srcRoute; - } - - /** - * Write advertisement into a document. asMimeType is a mime media-type - * specification and provides the form of the document which is being - * requested. Two standard document forms are defined. "text/text" encodes - * the document in a form nice for printing out, and "text/xml" which - * provides an XML representation. - * - * @param asMimeType mime-type format requested - * @return Document representation of the document as an advertisement - */ - - public abstract Document getDocument(MimeMediaType asMimeType); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/SignedAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/SignedAdvertisement.java deleted file mode 100644 index d76b330c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/SignedAdvertisement.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.credential.Credential; -import net.jxta.document.Advertisement; -import net.jxta.document.ExtendableAdvertisement; - - -/** - * A container for signed Advertisements - */ -public abstract class SignedAdvertisement extends ExtendableAdvertisement { - - protected Credential signer = null; - - protected Advertisement adv = null; - - // todo implement clone - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:SA"; - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * Gets the Advertisement. - * - * @return a signed advertisement - */ - public Advertisement getAdvertisement() { - return adv; - } - - /** - * Sets the Advertisement to be signed. - * - * @param adv set the advertisment - */ - public void setAdvertisement(Advertisement adv) { - this.adv = adv; - } - - /** - * Returns the credential which signed the advertisement. - * - * @return the credential which signed the advertisement. - */ - public Credential getSigner() { - return signer; - } - - /** - * Sets the Credential which will sign the advertisement. - * - * @param cred the credential - */ - public void setSigner(Credential cred) { - signer = cred; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/SrdiMessage.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/SrdiMessage.java deleted file mode 100644 index 297f5362..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/SrdiMessage.java +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.protocol; - - -import net.jxta.document.Document; -import net.jxta.document.MimeMediaType; -import net.jxta.peer.PeerID; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; - - -/** - * A generic message that can be used by services to push shared resources to - * other peers on the network. - *

      - */ -public abstract class SrdiMessage { - - /** - * PERSIST Scope is persist only. i.e. A node receiving such message is expected to only persist - * the indexes contained within. - */ - public static final int PERSISTONLY = 0; - - /** - * REPLICATE Scope is persist and replicate. i.e. A node receiving such message is expected - * to pnly persist the indexes contained within. - */ - public static final int REPLICATE = 1; - private final Collection entries = new ArrayList(); - private PeerID peerid = null; - private String primaryKey = null; - - /** - * The scope of SrdiMesage (0, or 1) - */ - private int scope = 0; - - /** - * Write advertisement into a document. asMimeType is a mime media-type - * specification and provides the form of the document which is being - * requested. Two standard document forms are defined. 'text/text' encodes - * the document in a form nice for printing out and 'text/xml' which - * provides an XML format. - * - * @param asMimeType mime-type requested representation for the returned - * document - * @return Document document representing the advertisement - */ - public abstract Document getDocument(MimeMediaType asMimeType); - - /** - * returns the source peerid - * - * @return PeerID - */ - public PeerID getPeerID() { - return peerid; - } - - /** - * get the primary key - * - * @return primaryKey - */ - public String getPrimaryKey() { - return this.primaryKey; - } - - /** - * Returns the current TTL value. - * - * @return The current TTL value. - * @deprecated ttl is a misnomer, it is meant to be defined as scope. use #getScope() instead - */ - @Deprecated - public int getTTL() { - return scope; - } - - /** - * sets the ttl - * - * @param newTTL The new TTL value. - * @deprecated ttl is a misnomer, it is meant to be defined as scope. use #setScope() instead - */ - @Deprecated - public void setTTL(int newTTL) { - scope = newTTL; - } - - /** - * Returns the current scope of this message. - *

      - * Scope is either 0 (persist only), or 1 (persist and replicate) - * - * @return The current scope value. - */ - public int getScope() { - return scope; - } - - /** - * Sets the current scope of this message. - *

      - * Scope is either 0 (persist only), or 1 (persist and replicate) - * @see #PERSISTONLY - * @see #REPLICATE - * - * @param scope The new TTL value. - */ - public void setScope(int scope) { - this.scope = scope; - } - - /** - * Decrements TTL - */ - public void decrementTTL() { - - if (this.scope > 0) { - this.scope--; - } - } - - /** - * Returns the entries of this SrdiMessage - * - * @return the entries of this SrdiMessage - */ - public Collection getEntries() { - return new ArrayList(entries); - } - - /** - * Adds an index entry - * @param key key - * @param value the value - * @param expiration expiration in millisconds - */ - public void addEntry(String key, String value, long expiration) { - addEntry(new SrdiMessage.Entry(key, value, expiration)); - } - - public void addEntry(SrdiMessage.Entry entry) { - entries.add(entry); - } - - /** - * Set the Entries for this SrdiMessage. - * - * @param newEntries The entries to be included in this message. - */ - public void setEntries(Collection newEntries) { - entries.clear(); - entries.addAll(newEntries); - } - - /** - * Set the source peerid - * - * @param peerid the source PeerID - */ - public void setPeerID(PeerID peerid) { - this.peerid = peerid; - } - - /** - * Set the primary key - * - * @param pkey the primary key - */ - public void setPrimaryKey(String pkey) { - this.primaryKey = pkey; - } - - /** - * All messages have a type (in xml this is !doctype) which identifies the - * message, if no expiration is defined Default expiration infinite for - * entries. This is the amount of time which an entry will live in cache. - * After this time, the entry is garbage collected, it also worthy to note - * that it is up to the peer caching these entries to honor the lifetime of - * the entry, and peer may choose to garbage collect entries based on - * quotas, relationship with other peers, etc. * - * - * @return String "jxta:GenSRDI" - */ - public static String getMessageType() { - return "jxta:GenSRDI"; - } - - /** - * Entries object, which describes each entry described by this message - */ - public final static class Entry { - - /** - * Entry Expiration expressed in relative time in ms - */ - public long expiration; - - /** - * Entry key attribute - */ - public String key; - - /** - * Entry key value - */ - public String value; - - /** - * {@inheritDoc} - *

      - * Expiration time is not considered in calculation. - */ - @Override - public boolean equals(Object target) { - - if (this == target) { - return true; - } - - if (target instanceof Entry) { - Entry likeMe = (Entry) target; - - return key.equals(likeMe.key) && value.equals(likeMe.value); - } - - return false; - } - - /** - * {@inheritDoc} - *

      - * Expiration time is not considered in calculation. - */ - @Override - public int hashCode() { - int result = 0; - - if (null != key) { - result ^= key.hashCode(); - } - - if (null != value) { - result ^= value.hashCode(); - } - - return result; - } - - /** - * Creates a Entry with key, value, and expiration - * - * @param key key attribute - * @param value key value - * @param expiration expressed in relative time in ms - */ - public Entry(String key, String value, long expiration) { - this.key = key; - this.value = value; - this.expiration = expiration; - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/TransportAdvertisement.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/TransportAdvertisement.java deleted file mode 100644 index 391fd8fa..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/TransportAdvertisement.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.protocol; - - -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.id.ID; - - -/** - * This abstract class defines a Transport advertisement. Each peer endpoint - * protocol is associated with a transport advertisement that describes the - * protocol and network interface associated with the endpoint transport. For - * example for TCP endpoint. the following transport information needs to be - * maintained for this endpoint: - *

      - *

      Transport : - *

        - *
      • Protocol : TCP - *

      • Port : 6001 - *

      • MulticastAddr : 224.0.1.85 - *

      • MulticastPort : 1234 - *

      • MulticastSize : 8192 - *

      - *

      - *

      This class is an abstract class that needs to be extended by implementation - * to support the different types of transport advertisements (TCP, HTTP, etc) - *

      - *

      - * <?xml version="1.0"?>
      - *  <TransportAdvertisement type="HTTPAdvertisement">
      - *          ..........
      - *  </TransportAdvertisement>
      - * 
      - * - * @see net.jxta.protocol.AccessPointAdvertisement - */ - - -public abstract class TransportAdvertisement extends ExtendableAdvertisement { - - protected String protocol = null; - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:TransportAdvertisement"; - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * Return ID for indexing. We don't have one so return the nullID. - * - * @return jxta id associated with this advertisement. - */ - @Override - public ID getID() { - return ID.nullID; - } - - /** - * Sets the URI scheme to be used for EndpointAddresses of this Message Transport. - * - * @return The URI scheme used for EndpointAddresses of this Message Transport. - */ - public String getProtocol() { - return protocol; - } - - /** - * Returns the URI scheme to be used for EndpointAddresses of this Message Transport. - * - * @param protocol The URI scheme used for EndpointAddresses of this Message Transport. - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/package.html deleted file mode 100644 index 30c19821..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/protocol/package.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - Provides inteface objects for Advertisments and protocol messages for the JXTA - Core - and - Standard - Protocols. - - @see net.jxta.document.Advertisement - @see JXTA Protocols Specification - Overview : Advertisements - @see JXTA Protocols Specification - Advertisements - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezVousService.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezVousService.java deleted file mode 100644 index 22f51f4f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezVousService.java +++ /dev/null @@ -1,455 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.rendezvous; - - -import java.io.IOException; -import java.util.Enumeration; -import java.util.Vector; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.Message; -import net.jxta.id.ID; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.service.Service; - - -/** - * The RendezVous Service provides propagation of messages within a JXTA - * PeerGroup. - * - *

      The JXTA RendezVous Service defines a subscription mechanism - * allowing JXTA peers to receive propagated messages (clients of the service) - * or become a repeater of the service (rendezvous peers). - * - *

      The Standard Reference Implementation requires that at least one peer in - * a PeerGroup to act as a Rendezvous. Rendezvous peers may dynamically join or - * leave the PeerGroup over time. - * - * @see JXTA Protocols Specification : Rendezvous - */ -public interface RendezVousService extends Service { - - /** - * Perform propagate() or walk() using the most - * appropriate TTL value for the implementation and configuration. The - * message will almost certainly be sent with a TTL value much less than - * this value. - */ - public final static int DEFAULT_TTL = Integer.MAX_VALUE; - - /** - * Attempt connection to the specified RendezVous peer. - * - * @deprecated Directly connecting to rendezvous peers is not recommended. - * Seed rendezvous should be specified using the RdvConfigAdv mechanisms. - * - * @param adv the advertisement of the RendezVousService peer - * @throws IOException When the specified peer is unreachable - */ - @Deprecated - public void connectToRendezVous(PeerAdvertisement adv) throws IOException; - - /** - * Attempt connection to the specified RendezVous peer. - * - * @deprecated Directly connecting to rendezvous peers is not recommended. - * Seed rendezvous should be specified using the RdvConfigAdv mechanisms. - * - * @param addr EndpointAddress of the rendezvous peer - * @throws IOException When the specified peer is unreachable - */ - @Deprecated - public void connectToRendezVous(EndpointAddress addr) throws IOException; - - /** - * Disconnect from the specified rendezvous. - * - * @param peerID the PeerId of the RendezVous to disconnect from. - */ - public void disconnectFromRendezVous(ID peerID); - - /** - * Returns an Enumeration of the PeerID all the RendezVous on which this - * Peer is currently connected. This returns the same result as - * {@link #getConnectedPeers()}. - * - * @return Enumeration enumeration of RendezVous. - */ - public Enumeration getConnectedRendezVous(); - - /** - * Returns an Enumeration of the PeerID all the RendezVous on which this - * Peer failed to connect to. - * - * @deprecated Due to design changes this no longer returns accurate nor - * complete results. It will eventually be removed. - * - * @return Enumeration of the PeerID all the RendezVous on which this - * Peer failed to connect to. - */ - @Deprecated - public Enumeration getDisconnectedRendezVous(); - - /** - * Start the local peer as a RendezVous peer. - */ - public void startRendezVous(); - - /** - * Stop the RendezVous function on the local Peer. All connected Peers are - * disconnected. - */ - public void stopRendezVous(); - - /** - * Returns an Enumeration of the PeerID of the peers that are currently - * connected to this peer. Depending upon the role of of this peer the - * result may be an enumeration of clients or an enumeration of rendezvous - * peers. - * - * @return Enumeration of {@link net.jxta.peer.PeerID} connected to this peer. - */ - public Enumeration getConnectedPeers(); - - /** - * Returns a Vector of the PeerID of the peers that are currently - * connected to this peer. Depending upon the role of of this peer the - * result may be an enumeration of clients or an enumeration of rendezvous - * peers. - * - * @return Vector of {@link net.jxta.peer.PeerID} connected to this peer. - */ - public Vector getConnectedPeerIDs(); - - /** - * Registers the provided listener under the given serviceName and - * serviceParam to receive messages propagated by the Rendezvous service. - * The listener will be added only if no other listener is already - * registered with these names. - * - * @deprecated This method just calls - * {@link net.jxta.endpoint.EndpointService#addIncomingMessageListener}. It's better to just - * register your listener with the Endpoint. This call may be - * eventually removed. - * - * @param serviceName The serviceName of the listener. - * @param serviceParam The serviceParam of the listener. - * @param listener An EndpointListener to process the message. - * @return true if listener was registered, otherwise false. - */ - @Deprecated - public boolean addPropagateListener(String serviceName, String serviceParam, EndpointListener listener); - - /** - * Removes a Listener previously added with addPropagateListener. - * If the given listener is not the one currently registered, nothing is removed. - * - * @deprecated This method just calls - * {@link net.jxta.endpoint.EndpointService#removeIncomingMessageListener}. - * It's better to just deregister your listener with the Endpoint. This call - * may be eventually removed. - * - * @param serviceName The serviceName of the listener. - * @param serviceParam The serviceParam of the listener. - * @param listener An EndpointListener to process the message. - * @return the listener removed, null if the listener was not registered. - */ - @Deprecated - public EndpointListener removePropagateListener(String serviceName, String serviceParam, EndpointListener listener); - - /** - * Add a listener for RendezVousEvents. - * - * @param listener An RendezvousListener to process the event. - */ - public void addListener(RendezvousListener listener); - - /** - * Removes a Rendezvous event listener previously added with addListener. - * - * @param listener the RendezvousListener listener remove - * @return true if successful - */ - public boolean removeListener(RendezvousListener listener); - - /** - * Propagates a message to the local network and to as many members of - * the peer group as possible. - * - *

      This method sends the message to all peers, rendezvous peers and - * edge peer. This method of propagation is very expensive and should - * be used very cautiously. When rendezvous peers are used in order to - * cache index of data, it is more efficient to use the walk() method. - * - *

      Only a single HOP at a time is performed. Messages are always - * delivered to the destination handler on arrival. This handler - * is responsible for repropagating further, if deemed appropriate. - * - *

      Loop and TTL control are performed automatically. - * - *

      Messages can be propagated via this method for the first time or - * can be re-propagated by re-using a message that came in via propagation. - * In the later case, the TTL and loop detection parameters CANNOT be - * re-initialized. If one wants to "re-propagate" a message with a new TTL - * and blank gateways list one must generate a completely new message. - * This limits the risk of accidental propagation storms, although they - * can always be engineered deliberately. - * - * @param msg is the message to propagate. - * @param serviceName is the name of the service. - * @param serviceParam is the parameter of the service. - * @param ttl The requested TTL for the message. - * @exception IOException if an io error occurs - */ - public void propagate(Message msg, String serviceName, String serviceParam, int ttl) throws IOException; - - /** - * Propagates a message to the specified peers. - * - * @param destPeerIds An enumeration of PeerIDs of the peers that are the - * intended recipients of the propagated message. - * @param msg The message to propagate. - * @param serviceName The name of the service. - * @param serviceParam The parameter of the service. - * @param ttl The requested TTL for the message. - * @exception IOException if an io error occurs - */ - public void propagate(Enumeration destPeerIds, Message msg, String serviceName, String serviceParam, int ttl) throws IOException; - - /** - * Propagates a message to members of the peer group reachable via the - * local network. Typically this is accomplished by broadcasting or - * multicasting. - * - *

      Only a single HOP at a time is performed. Messages are always - * delivered to the destination handler on arrival. This handler - * is responsible for repropagating further, if deemed appropriate. - * - *

      Loop and TTL control are performed automatically. - * - *

      Messages can be propagated via this method for the first time or - * can be re-propagated by re-using a message that came in via propagation. - * In the later case, the TTL and loop detection parameters CANNOT be - * re-initialized. If one wants to "re-propagate" a message with a new TTL - * and blank gateways list one must generate a completely new message. - * This limits the risk of accidental propagation storms, although they - * can always be engineered deliberately. - * - * @param msg is the message to propagate. - * @param serviceName is the name of the service. - * @param serviceParam is the parameter of the service. - * @param ttl The requested TTL for the message. - * @exception IOException if an io error occurs - */ - public void propagateToNeighbors(Message msg, String serviceName, String serviceParam, int ttl) throws IOException; - - /** - * Propagates a message to as many members of the peer group as possible. - * - *

      Only a single HOP at a time is performed. Messages are always - * delivered to the destination handler on arrival. This handler - * is responsible for repropagating further, if deemed appropriate. - * - *

      Loop and TTL control are performed automatically. - * - *

      Messages can be propagated via this method for the first time or - * can be re-propagated by re-using a message that came in via propagation. - * In the later case, the TTL and loop detection parameters CANNOT be - * re-initialized. If one wants to "re-propagate" a message with a new TTL - * and blank gateways list one must generate a completely new message. - * This limits the risk of accidental propagation storms, although they - * can always be engineered deliberately. - * - * @param msg is the message to propagate. - * @param serviceName is the name of the service - * @param serviceParam is the parameter of the service - * @param ttl The requested TTL for the message. - * @exception IOException if an io error occurs - */ - public void propagateInGroup(Message msg, String serviceName, String serviceParam, int ttl) throws IOException; - - /** - * Return {@code true} if connected to a rendezvous. - * - * @return {@code true} if connected to a rendezvous otherwise {@code false}. - */ - public boolean isConnectedToRendezVous(); - - /** - * Returns {@code true} if this peer is acting as a rendezvous peer (per the - * implementation definition) within the peer group. {@code false} is - * returned for all other peer roles. - * - * @return {@code true} if this peer is acting as a rendezvous peer (per the - * implementation definition) within the peer group. {@code false} is - * returned for all other peer roles. - */ - public boolean isRendezVous(); - - /** - * Returns the current role of this peer within the peergroup. - * - * @return The current role of this peer within the peergroup. - */ - public RendezVousStatus getRendezVousStatus(); - - /** - * Enable or disable the automatic switching between an Edge Peer - * and a Rendezvous Peer. - * - * @param auto {@code true} will activate automatic role switching. - * @return The previous auto start value. - */ - public boolean setAutoStart(boolean auto); - - /** - * Enable or disable the automatic switching between an Edge Peer - * and a Rendezvous Peer. - * - * @param auto {@code true} will activate automatic role switching. - * @param period The interval in milliseconds at which the peer should - * reconsider it's role. - * @return The previous auto start value. - */ - public boolean setAutoStart(boolean auto, long period); - - /** - * Walk a message through the rendezvous peers of the network: only - * rendezvous peers will receive the message. - * - *

      Only a single HOP at a time is performed. Messages are always - * delivered to the destination handler on arrival. This handler - * is responsible for repropagating further, if deemed appropriate. - * - *

      Loop and TTL control are performed automatically. - * - *

      Messages can be propagated via this method for the first time or - * can be re-propagated by re-using a message that came in via propagation. - * In the later case, the TTL and loop detection parameters CANNOT be - * re-initialized. If one wants to "re-propagate" a message with a new TTL - * and blank gateways list one must generate a completely new message. - * This limits the risk of accidental propagation storms, although they - * can always be engineered deliberately. - * - *

      Note: The original msg is not modified and may be reused upon return. - * - * @param msg is the message to walk. - * @param serviceName is the name of the service - * @param serviceParam is the parameter of the service - * @param ttl is the maximum TTL of the message. - * @throws IOException when walking the message is impossible (network failure) - */ - public void walk(Message msg, String serviceName, String serviceParam, int ttl) throws IOException; - - /** - *

      Walk a message through the rendezvous peers of the network: only - * rendezvous peers will receive the message. - * - *

      Only a single HOP at a time is performed. Messages are always - * delivered to the destination handler on arrival. This handler - * is responsible for repropagating further, if deemed appropriate. - * - *

      Loop and TTL control are performed automatically. - * - *

      Messages can be propagated via this method for the first time or - * can be re-propagated by re-using a message that came in via propagation. - * In the later case, the TTL and loop detection parameters CANNOT be - * re-initialized. If one wants to "re-propagate" a message with a new TTL - * and blank gateways list one must generate a completely new message. - * This limits the risk of accidental propagation storms, although they - * can always be engineered deliberately. - * - *

      Note: The original msg is not modified and may be reused upon return. - * - * @param destPeerIDs is a Vector of PeerIDs of the peers which are receiving - * first the walker. Note that each entry in the Vector will create its own - * walker. - * @param msg is the message to walk. - * @param serviceName is the name of the service - * @param serviceParam is the parameter of the service - * @param ttl is the maximum TTL of the message. - * @throws IOException when walking the message is impossible (network failure) - */ - public void walk(Vector destPeerIDs, Message msg, String serviceName, String serviceParam, int ttl) throws IOException; - - /** - * Returns a vector of RdvAdvertisement of the local view of rendezvous peers. - * - * @deprecated Due to design changes, the list of peers may be empty in - * configurations which previously returned a non-empty result. Future - * JXTA versions are likely to use a different API. - * - * @return The local view of RDV peers. - */ - @Deprecated - public Vector getLocalWalkView(); - - /** - * Set a new deadline for the rendezvous to be proven alive. - * As a result a lease response must be sought and obtained within the - * specified delay or the rdv is considered disconnected. - * - *

      A timeout of 0 or less triggers immediate disconnection. - * - * @param peer The peer to be challenged - * @param timeout The delay - */ - public void challengeRendezVous(ID peer, long timeout); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezVousStatus.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezVousStatus.java deleted file mode 100644 index fb1486aa..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezVousStatus.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.rendezvous; - - -/** - * A static "enum" class for RendezVous Status. - */ -public enum RendezVousStatus { - - /** - * No RendezVous Service is configured. - */ - NONE, - - /** - * An unknown RendezVous Service is configured. - */ - UNKNOWN, - - /** - * An ad hoc (connectionless) RendezVous Service is configured. - */ - ADHOC, - - /** - * RendezVous Service is configured as an edge peer. - */ - EDGE, - - /** - * RendezVous Service is configured to automatically choose, but is - * currently running as an edge. - */ - AUTO_EDGE, - - /** - * RendezVous Service is configured to automatically choose, but is - * currently running as a Rendezvous. - */ - AUTO_RENDEZVOUS, - - /** - * RendezVous Service is configured as an rendezvous peer. - */ - RENDEZVOUS -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezvousEvent.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezvousEvent.java deleted file mode 100644 index ed6adf0e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezvousEvent.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.rendezvous; - - -import java.util.EventObject; - -import net.jxta.id.ID; - - -/** - * Container for Rendezvous Service events. The source of the event is the - * rendezvous service generating the event - */ -public class RendezvousEvent extends EventObject { - - /** - * Rendezvous connection event - */ - public final static int RDVCONNECT = 0; - - /** - * Connection renewal event - */ - public final static int RDVRECONNECT = 1; - - /** - * Client connection event - */ - public final static int CLIENTCONNECT = 2; - - /** - * Client Connection renewal event - */ - public final static int CLIENTRECONNECT = 3; - - /** - * Rendezvous disconnection event - */ - public final static int RDVDISCONNECT = 4; - - /** - * Rendezvous connection failure - */ - public final static int RDVFAILED = 5; - - /** - * Client disconnection event - */ - public final static int CLIENTDISCONNECT = 6; - - /** - * Client connection failure - */ - public final static int CLIENTFAILED = 7; - - /** - * Node has become a rendezvous - */ - public final static int BECAMERDV = 8; - - /** - * Node has become a edge - */ - public final static int BECAMEEDGE = 9; - - private final static String EVENTNAMES[] = { - "RDVCONNECT", "RDVRECONNECT", "CLIENTCONNECT", "CLIENTRECONNECT", "RDVDISCONNECT", "RDVFAILED", "CLIENTDISCONNECT" - , - "CLIENTFAILED", "BECAMERDV", "BECAMEEDGE" - }; - - private int type; - private ID peer; - - /** - * Creates a new event - * - * @param source The rendezvous service which generated the event. - * @param type the event type. - * @param peer the peer associated with the event. - */ - public RendezvousEvent(Object source, int type, ID peer) { - super(source); - this.type = type; - this.peer = peer; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - String eventType; - - if ((type >= RDVCONNECT) && (type <= BECAMEEDGE)) { - eventType = EVENTNAMES[type]; - } else { - eventType = "UNKNOWN (" + type + ")"; - } - - return super.toString() + " : " + eventType + " for [" + peer + "]"; - } - - /** - * Returns the event type - * - * @return int type - */ - public int getType() { - return type; - } - - /** - * Returns peerid - * - * @return the peer associated with the event - */ - public String getPeer() { - return peer.toString(); - } - - /** - * Returns peerid - * - * @return the peer associated with the event - */ - public ID getPeerID() { - return peer; - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezvousListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezvousListener.java deleted file mode 100644 index 18c77425..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/RendezvousListener.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.rendezvous; - - -import java.util.EventListener; - - -/** - * The listener interface for receiving RendezVousService events. - * - * The following example illustrate how to implement a - * RendezvousListener: - * - *

      
      - * public class MyApp implements RendezvousListener {
      - *           ..
      - *           rendezvous = mygroup.getRendezVousService();
      - *           rendezvous.addListener(this);
      - *           ..
      - *           ..
      - *           ..
      - *   public void rendezvousEvent (RendezvousEvent event) {
      - *       if (event.getType() == event.RDVCONNECT) {
      - *          ..
      - *       }
      - *   }
      - * }
      - * 
      - */ -public interface RendezvousListener extends EventListener { - - /** - * Called when an event occurs for the Rendezvous service - * - * @param event the rendezvous event - */ - void rendezvousEvent(RendezvousEvent event); - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/package.html deleted file mode 100644 index ce1e7e3a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/rendezvous/package.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - The RendezVous Service is responsible for propagating messages within a JXTA - PeerGroup. - - @see net.jxta.protocol.RdvAdvertisement - @see net.jxta.rendezvous.RendezVousService - @see JXTA Protocols Specification : Rendezvous - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/GenericResolver.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/GenericResolver.java deleted file mode 100644 index 7d63e478..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/GenericResolver.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.resolver; - - -/** - * @deprecated This interface has been subsumed into the - * {@link net.jxta.resolver.ResolverService}. - */ -@Deprecated -public interface GenericResolver {} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/QueryHandler.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/QueryHandler.java deleted file mode 100644 index 57ad8885..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/QueryHandler.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.resolver; - - -import net.jxta.protocol.ResolverQueryMsg; -import net.jxta.protocol.ResolverResponseMsg; -import net.jxta.exception.*; -import java.io.*; - - -/** - * Services that wish to act as a resolver handler must implement this interface - * - * @see net.jxta.resolver.ResolverService - * @see net.jxta.protocol.ResolverQueryMsg - * @see net.jxta.protocol.ResolverResponseMsg - **/ -public interface QueryHandler { - - /** - * Process the resolver query, and generate response - * it is the responsibility of the handler to send the response - * - *

      -     * result = processIncomingQuery(query);
      -     * if (result != null) {
      -     *   resolver.sendResponse(query.getSrc(), response);
      -     *   return ResolverService.OK;
      -     *  } else return ResolverService.Repropagate;
      -     * 
      - * - * @param query ResolverQueryMsg query - * @return int status, {@link net.jxta.resolver.ResolverService#OK OK} - * success, {@link net.jxta.resolver.ResolverService#Repropagate Repropagate} - * to indicate a re-propagation is needed. - */ - - public int processQuery(ResolverQueryMsg query); - - /** - * Called when messages are received by the ResolverService - * it calls back this method to deal with received responses - * - * @param response ResolverQueryMsg response - **/ - public void processResponse(ResolverResponseMsg response); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/ResolverService.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/ResolverService.java deleted file mode 100644 index bff38674..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/ResolverService.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.resolver; - - -import net.jxta.service.Service; -import net.jxta.protocol.ResolverQueryMsg; -import net.jxta.protocol.ResolverResponseMsg; -import net.jxta.protocol.ResolverSrdiMsg; - - -/** - * Provides a generic mechanism for JXTA Services to send "Queries", and receive - * "Responses". It removes the burden for registered handlers in deal with : - * - *
        - *
      • Setting message tags, to ensure uniqueness of tags and - * ensures that messages are sent to the correct address, and group.

        - *
      • Authentication, and verification of credentials.

        - *
      • Query routing.

        - *
      • drop rogue messages.

        - *
      - * - *

      The ResolverService does not proccess the queries, nor does it not - * compose reponses. Processing of queries, and composition of responses is left - * up to the registered handlers. Services that wish to handle queries and - * generate reponses must implement {@link net.jxta.resolver.QueryHandler}. - * - * @see net.jxta.service.Service - * @see net.jxta.resolver.QueryHandler - * @see net.jxta.protocol.ResolverQueryMsg - * @see net.jxta.protocol.ResolverResponseMsg - */ -public interface ResolverService extends Service, GenericResolver { - - /** - * Returned by query handlers to indicate that the query should be - * forwarded to the rest of the network. - */ - public final static int Repropagate = -1; - - /** - * Returned by query handlers to indicate that the query has been resolved - * and a response has been sent. - */ - public final static int OK = 0; - - /** - * Registers a given QueryHandler, returns the previous handler registered - * under this name. - * - * @param name The name under which this handler is to be registered. - * @param handler The handler. - * @return The previous handler registered under this name. - */ - public QueryHandler registerHandler(String name, QueryHandler handler); - - /** - * Unregisters a given QueryHandler, returns the previous handler - * registered under this name. - * - * @param name The name of the handler to unregister. - * @return The previous handler registered under this name. - */ - public QueryHandler unregisterHandler(String name); - - /** - * Registers a given SrdiHandler, returns the previous handler registered - * under this name. - * - * @param name The name under which this handler is to be registered. - * @param handler The handler. - * @return The previous handler registered under this name. - * - */ - public SrdiHandler registerSrdiHandler(String name, SrdiHandler handler); - - /** - * Unregisters a given SrdiHandler, returns the previous handler registered - * under this name. - * - * @param name The name of the handler to unregister. - * @return The previous handler registered under this name - * - */ - public SrdiHandler unregisterSrdiHandler(String name); - - /** - * Sends a resolver query. If destPeer is null the - * message is propagated. - * - * @param destPeer The destination peer of the query or null if - * the query is to be propagated. - * @param query The query to match. - */ - public void sendQuery(String destPeer, ResolverQueryMsg query); - - /** - * Send a resolver response. If destPeer is null then the - * response is propagated. Propagated responses are generally announcements - * and not responses to active queries. - * - * @param destPeer The destination peer of the response or null if - * the response is to be propagated. - * @param response The response to be sent. - */ - public void sendResponse(String destPeer, ResolverResponseMsg response); - - /** - * Send an SRDI message. - * - *

      If destPeer is null the message is walked. - * - * @param destPeer is the destination of the SRDI message. - * @param srdi is the SRDI message to be sent. - */ - public void sendSrdi(String destPeer, ResolverSrdiMsg srdi); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/SrdiHandler.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/SrdiHandler.java deleted file mode 100644 index 321f0b58..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/SrdiHandler.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.resolver; - - -import net.jxta.protocol.ResolverSrdiMsg; -import net.jxta.endpoint.OutgoingMessageEvent; -import net.jxta.peer.PeerID; - - -/** - * Services that wish to receive shared resource indecies must implement this - * interface. - * - *@see net.jxta.protocol.SrdiMessage - */ - -public interface SrdiHandler { - - /** - * Process the SrdiMessage message, returns true if the message was - * processed properly - * - *@param message Description of the Parameter - *@return true if the message was processed properly - */ - - public boolean processSrdi(ResolverSrdiMsg message); - - /** - * Resolver calls this method when a failure to send a message to specified - * peer occurs - * - *@param peerid peerid failure occured on - */ - - public void messageSendFailed(PeerID peerid, OutgoingMessageEvent e); - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/package.html deleted file mode 100644 index 791c05c0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/resolver/package.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - The JXTA Resolver Services provides a generic mechanism for JXTA Services - to send "Queries", and receive "Responses". - - @see JXTA Protocols Specification : Peer Resolver Protocol - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/service/Service.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/service/Service.java deleted file mode 100644 index fdb70fec..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/service/Service.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.service; - - -import net.jxta.platform.Module; -import net.jxta.document.Advertisement; - - -/** - * This interface implements the peer group service interface. Peer groups - * are formed as a collection of peers that have agreed upon a common set of - * services. The JXTA platform provides a predefined set of services to build - * peer groups - * - *

      Every service is defined by a - * {@link net.jxta.protocol.ModuleImplAdvertisement}. The Service - * advertisement provides the necessary information to uniquely identify - * the service and to contact its associated service(s). - * - *

      When a new peer is joining a peer group an instance of all the - * services associated with the new peer group is created on this peer - * dynamically. Not all services need to be resident on a peer. A peer can - * dynamically load a new service from the peer it contacted to join the - * new peer group (via the PeerGroupAdvertisement of this group). - * - * @see net.jxta.peergroup.PeerGroup - * @see net.jxta.platform.Application - * @see net.jxta.protocol.PeerGroupAdvertisement - * @see net.jxta.protocol.ModuleImplAdvertisement - **/ -public interface Service extends Module { - - /** - * Service objects are not manipulated directly to protect usage - * of the service. A Service interface is returned to access the service - * methods. - * - * @return Service public interface of the service - * - */ - public Service getInterface(); - - /** - * Returns the advertisement for this service. - * - * @return Advertisement the advertisement. This is always a - * {@code ModuleImplAdvertisement}. - * - **/ - public Advertisement getImplAdvertisement(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/service/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/service/package.html deleted file mode 100644 index a248abb0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/service/package.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - Every service is defined by a - {@link net.jxta.protocol.ModuleImplAdvertisement}. The Service - advertisement provides the necessary information to uniquely identify - the service and to contact its associated service(s). - - @see JXTA Protocols Specification : Services - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaMulticastSocket.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaMulticastSocket.java deleted file mode 100644 index 429e1c09..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaMulticastSocket.java +++ /dev/null @@ -1,478 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.socket; - - -import net.jxta.credential.Credential; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.endpoint.ByteArrayMessageElement; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.id.IDFactory; -import net.jxta.impl.util.ProducerBiasedQueue; -import net.jxta.logging.Logging; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.PipeAdvertisement; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MulticastSocket; -import java.net.SocketAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.URI; -import java.util.Collections; -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * The JxtaMulticastSocket class is useful for sending and receiving - * JXTA multicast packets. A JxtaMulticastSocket is a (UDP) DatagramSocket, - * with additional capabilities for joining "groups" of other multicast hosts - * on the internet. - * A multicast group is specified within the context of PeerGroup and a propagate - * pipe advertisement. - * One would join a multicast group by first creating a MulticastSocket - * with the desired peer group and pipe advertisement : - *

      - *

      - *  // join a Multicast group and send the group salutations
      - *  ...
      - *  String msg = "Hello";
      - *  MulticastSocket s = new JxtaMulticastSocket(peergroup, propPipeAdv);
      - *  //We are joined at this point
      - *  DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length());
      - *  s.send(hi);
      - *  // get their responses!
      - *  byte[] buf = new byte[1000];
      - *  DatagramPacket recv = new DatagramPacket(buf, buf.length);
      - *  s.receive(recv);
      - *  ...
      - *  // OK, I'm done talking - leave the group...
      - *  s.close();
      - * 
      - *

      - * One can also respond only to the sender of the datagram as follows : - *

      - *  DatagramPacket res = new DatagramPacket(response.getBytes(), response.length());
      - *  res.setAddress(recv.getAddress());
      - *  s.send(res);
      - * 
      - *

      - * When one sends a message to a multicast group, all subscribing recipients to - * that peergroup and pipe receive the message (including themselves) - * When a socket subscribes to a multicast group/port, it receives datagrams - * sent by other hosts to the group/pipe, as do all other members of the group - * and pipe. A socket relinquishes membership in a group by the - * close() method. Multiple MulticastSocket's may - * subscribe to a multicast group and pipe concurrently, and they will all receive - * group datagrams. - *

      - * When a datagram is sent it carries along with the peerid of the sender. - * The PeerID is represented as a InetAddress in the form of host/ipadress - * where host name is the peerid, and ip address is always represented as 0.0.0.0 - * since it is meaningless in the context of JXTA. - * e.g of InetAddress resembles the following: - *

      - *

      - * uuid-59616261646162614A787461503250339C6014B0F21A49DBBDF2ADBDDBCB314703/0.0.0.0
      - * 
      - */ - -public class JxtaMulticastSocket extends MulticastSocket implements PipeMsgListener { - private final static Logger LOG = Logger.getLogger(JxtaMulticastSocket.class.getName()); - public static final String NAMESPACE = "JXTAMCAST"; - public static final String DATATAG = "DATAGRAM"; - public static final String SRCIDTAG = "SRCID"; - protected PipeAdvertisement pipeAdv; - protected PipeService pipeSvc; - protected InputPipe in; - protected PeerGroup group; - protected SocketAddress socketAddress; - protected InetAddress localAddress; - protected OutputPipe outputPipe; - protected boolean closed = false; - protected boolean bound = false; - protected ProducerBiasedQueue queue = new ProducerBiasedQueue(); - protected Credential credential = null; - protected StructuredDocument credentialDoc = null; - private int timeout = 60000; - private byte[] fauxip = new byte[4]; - private boolean jxtamode = false; - private MessageElement srcElement = null; - - /** - * Create a multicast socket and bind it to a specific pipe within specified - * peer group - * - * @param group group context - * @param pipeAd PipeAdvertisement - * @throws IOException if an io error occurs - */ - public JxtaMulticastSocket(PeerGroup group, PipeAdvertisement pipeAd) throws IOException { - super(); - joinGroup(group, pipeAd); - } - - /** - * joins MutlicastSocket to specified pipe within the context of group - * - * @param group group context - * @param pipeAd PipeAdvertisement - * @throws IOException if an io error occurs - */ - public void joinGroup(PeerGroup group, PipeAdvertisement pipeAd) throws IOException { - - if (pipeAd.getType() != null && !pipeAd.getType().equals(PipeService.PropagateType)) { - throw new IOException("Only propagate pipe advertisements are supported"); - } - if (pipeAd.getPipeID() == null) { - throw new IOException("Invalid pipe advertisement"); - } - - this.group = group; - this.pipeAdv = pipeAd; - pipeSvc = group.getPipeService(); - this.in = pipeSvc.createInputPipe(pipeAd, this); - this.credentialDoc = getCredDoc(group); - outputPipe = pipeSvc.createOutputPipe(pipeAd, 1); - String id = group.getPeerID().toString(); - - srcElement = new StringMessageElement(SRCIDTAG, id, null); - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Starting JxtaMulticastSocket on pipe id :" + pipeAdv.getID()); - } - String pipeStr = pipeAd.getPipeID().getUniqueValue().toString(); - - localAddress = InetAddress.getByAddress(pipeStr, fauxip); - socketAddress = new InetSocketAddress(localAddress, 0); - bound = true; - } - - /** - * Obtain the credential doc from the group object - * - * @param group group context - * @return The credDoc value - */ - protected static StructuredDocument getCredDoc(PeerGroup group) { - try { - MembershipService membership = group.getMembershipService(); - Enumeration each = membership.getCurrentCredentials(); - - if (each.hasMoreElements()) { - // get the only credential "nobody" - Credential credential = (Credential) each.nextElement(); - - return credential.getDocument(MimeMediaType.XMLUTF8); - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to get credential", e); - } - } - return null; - } - - /** - * Returns the binding state of the MutlicastSocket. - * - * @return true if the MutlicastSocket successfully bound to an address - */ - @Override - public boolean isBound() { - return bound; - } - - /** - * Closes this MutlicastSocket. - */ - @Override - public synchronized void close() { - if (closed) { - return; - } - bound = false; - closed = true; - in.close(); - outputPipe.close(); - queue.close(); - in = null; - } - - /** - * {@inheritDoc} - */ - public void pipeMsgEvent(PipeMsgEvent event) { - - Message message = event.getMessage(); - - if (message == null) { - return; - } - - MessageElement element = null; - - // does the message contain any data - element = message.getMessageElement(NAMESPACE, DATATAG); - if (element == null) { - return; - } - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Pushing a message onto queue"); - } - queue.push(message, -1); - } catch (InterruptedException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Interrupted", e); - } - } - } - - /** - * Gets the Timeout attribute of the JxtaMulticastSocket - * - * @return The soTimeout value - */ - @Override - public synchronized int getSoTimeout() { - return timeout; - } - - /** - * Sets the Timeout attribute of the JxtaMulticastSocket - * a timeout of 0 blocks forever, by default this Socket's - * timeout is set to 0 - * - * @param timeout The new soTimeout value - */ - @Override - public synchronized void setSoTimeout(int timeout) throws SocketException { - checkState(); - this.timeout = timeout; - } - - /** - * Returns the closed state of the JxtaMulticastSocket. - * - * @return true if the socket has been closed - */ - @Override - public synchronized boolean isClosed() { - return closed; - } - - /** - * Throws a SocketException if closed or not bound - * - * @throws SocketException if closed - */ - private void checkState() throws SocketException { - if (isClosed()) { - throw new SocketException("MulticastSocket is closed"); - } else if (!isBound()) { - throw new SocketException("MulticastSocket not bound"); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void send(DatagramPacket packet) throws IOException { - checkState(); - byte[] data = new byte[packet.getLength()]; - - System.arraycopy(packet.getData(), packet.getOffset(), data, 0, packet.getLength()); - - Message msg = new Message(); - - msg.addMessageElement(NAMESPACE, srcElement); - msg.addMessageElement(NAMESPACE, new ByteArrayMessageElement(DATATAG, MimeMediaType.AOS, data, null)); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending a data packet"); - } - InetAddress address = packet.getAddress(); - PeerID pid = null; - - if (address != null) { - String pidStr = address.getHostName(); - - try { - pid = (PeerID) IDFactory.fromURI(new URI(pidStr)); - } catch (Exception ex) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Invalid source PeerID multicasting instead"); - } - } - } - if (pid != null) { - // Unicast datagram - // create a op pipe to the destination peer - OutputPipe op = pipeSvc.createOutputPipe(pipeAdv, Collections.singleton(pid), 1000); - - op.send(msg); - op.close(); - } else { - // multicast - outputPipe.send(msg); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void receive(DatagramPacket packet) throws IOException { - checkState(); - Message msg = null; - // data - MessageElement del = null; - // src - MessageElement sel = null; - - try { - msg = (Message) queue.pop(timeout); - if (msg == null) { - if (timeout > 0) { - throw new SocketTimeoutException("Socket timeout reached"); - } else { - return; - } - } - del = msg.getMessageElement(NAMESPACE, DATATAG); - sel = msg.getMessageElement(NAMESPACE, SRCIDTAG); - if (del == null || sel == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Message contains no data element, returning"); - } - return; - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Popped a message off the queue"); - } - } - } catch (InterruptedException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Exception occured", e); - } - throw new IOException(e.toString()); - } - if (del.getByteLength() > packet.getLength()) { - throw new IOException("Datagram can not accomodate message of size :" + del.getByteLength()); - } - String addrStr = new String(sel.getBytes(false), 0, (int) sel.getByteLength(), "UTF8"); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Src Address :" + addrStr); - } - InetAddress address = InetAddress.getByAddress(addrStr, fauxip); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Setting Data, and Src Address :" + address); - } - packet.setAddress(address); - packet.setData(del.getBytes(false)); - } - - /** - * {@inheritDoc} - */ - @Override - public InetAddress getLocalAddress() { - if (isClosed()) { - return null; - } - return localAddress; - } - - /** - * {@inheritDoc} - */ - @Override - public SocketAddress getLocalSocketAddress() { - if (isClosed()) { - return null; - } - return socketAddress; - } - - /** - * {@inheritDoc} - */ - @Override - public void bind(SocketAddress addr) throws SocketException { - if (isBound()) { - throw new SocketException("Already bound"); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaServerSocket.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaServerSocket.java deleted file mode 100644 index 470065b7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaServerSocket.java +++ /dev/null @@ -1,700 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.socket; - -import net.jxta.credential.Credential; -import net.jxta.credential.CredentialValidator; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeAdvertisement; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * JxtaServerSocket is a bi-directional Pipe that behaves very much like - * ServerSocket. It creates an inputpipe and listens for pipe connection - * requests. JxtaServerSocket also defines it own protocol. Requests arrive as - * a JXTA Message with the following elements: - *

      - * <Cred> Credentials which can be used to determine trust </Cred> - *

      - * <reqPipe> requestor's pipe advertisement </reqPipe> - *

      - * <remPipe> Remote pipe advertisement </remPipe> - *

      - * <reqPeer> Remote peer advertisement </reqPeer> - *

      - * <stream> determine whether the connection is reliable, or not </stream> - *

      - * <close> close request </close> - *

      - * <data> Data </data> - *

      - * JxtaServerSocket then creates a new private pipe, listens for messages on that pipe, - * resolves the requestor's pipe, and sends a <remPipe> private pipe created </remotePipe> - * advertisement back, where the remote side is resolved. - *

      - * The {@code accept()} backlog defaults to 50 requests. - *

      - * The timeout default to 60 seconds, i.e. blocking. - */ -public class JxtaServerSocket extends ServerSocket implements PipeMsgListener { - - private static final Logger LOG = Logger.getLogger(JxtaServerSocket.class.getName()); - - protected static final String MSG_ELEMENT_NAMESPACE = "JXTASOC"; - protected static final String credTag = "Cred"; - protected static final String reqPipeTag = "reqPipe"; - protected static final String remPeerTag = "remPeer"; - protected static final String remPipeTag = "remPipe"; - protected static final String dataTag = "data"; - protected static final String closeTag = "close"; - protected final static String closeReqValue = "close"; - protected final static String closeAckValue = "closeACK"; - protected static final String streamTag = "stream"; - - private final static int DEFAULT_BACKLOG = 50; - private final static long DEFAULT_TIMEOUT = 60 * 1000L; - - /** - * QUEUE_END_MESSAGE is used to signal that the queue has been closed. - */ - protected static final Message QUEUE_END_MESSAGE = new Message(); - - /** - * The PeerGroup - */ - protected PeerGroup group; - - /** - * The pipe advertisement we are serving. - */ - protected PipeAdvertisement pipeAdv; - - /** - * The input pipe on which we listen for connect requests. - */ - protected InputPipe serverPipe; - - /** - * The credential we will present to connect requests. - */ - protected Credential localCredential = null; - - /** - * The number of connect requests we will allow to become backlogged. - */ - protected int backlog = DEFAULT_BACKLOG; - - /** - * The timeout for accept operations. - */ - protected long timeout = DEFAULT_TIMEOUT; - - protected BlockingQueue queue = null; - protected volatile boolean bound = false; - protected volatile boolean closed = false; - private CredentialValidator credValidator = null; - - /** - * Default Constructor - *

      - * A call to {@code bind()} is needed to finish initializing this object. - * - * @throws IOException if an io error occurs - */ - public JxtaServerSocket() throws IOException {} - - /** - * Constructs and binds a JxtaServerSocket using a JxtaSocketAddress as - * the address. - * - * @param address an instance of JxtaSocketAddress - * @throws IOException if an io error occurs - * @see net.jxta.socket.JxtaSocketAddress - */ - public JxtaServerSocket(SocketAddress address) throws IOException { - this(address, DEFAULT_BACKLOG); - } - - /** - * Constructs and binds a JxtaServerSocket to the specified pipe. - * - * @param group JXTA PeerGroup - * @param pipeAdv PipeAdvertisement on which pipe requests are accepted - * @throws IOException if an I/O error occurs - */ - public JxtaServerSocket(PeerGroup group, PipeAdvertisement pipeAdv) throws IOException { - this(group, pipeAdv, DEFAULT_BACKLOG); - } - - /** - * Constructs and binds a JxtaServerSocket using a JxtaSocketAddress as - * the address. - * - * @param address an instance of JxtaSocketAddress - * @param backlog the size of the backlog queue - * @throws IOException if an I/O error occurs - * @see net.jxta.socket.JxtaSocketAddress - */ - public JxtaServerSocket(SocketAddress address, int backlog) throws IOException { - this(address, backlog, (int) DEFAULT_TIMEOUT); - } - - /** - * Constructor for the JxtaServerSocket object - * - * @param group JXTA PeerGroup - * @param pipeAdv PipeAdvertisement on which pipe requests are accepted - * @param backlog the maximum length of the queue. - * @throws IOException if an I/O error occurs - */ - public JxtaServerSocket(PeerGroup group, PipeAdvertisement pipeAdv, int backlog) throws IOException { - this(group, pipeAdv, backlog, (int) DEFAULT_TIMEOUT); - } - - /** - * Constructs and binds a JxtaServerSocket using a JxtaSocketAddress as - * the address. - * - * @param address an instance of JxtaSocketAddress - * @param backlog the size of the backlog queue - * @param timeout connection timeout in milliseconds - * @throws IOException if an I/O error occurs - * @see net.jxta.socket.JxtaSocketAddress - */ - public JxtaServerSocket(SocketAddress address, int backlog, int timeout) throws IOException { - setSoTimeout(timeout); - bind(address, backlog); - } - - /** - * Constructor for the JxtaServerSocket object. - * - * @param group JXTA PeerGroup - * @param pipeAdv PipeAdvertisement on which pipe requests are accepted - * @param backlog the maximum length of the queue. - * @param timeout the specified timeout, in milliseconds - * @throws IOException if an I/O error occurs - */ - public JxtaServerSocket(PeerGroup group, PipeAdvertisement pipeAdv, int backlog, int timeout) throws IOException { - this(group, pipeAdv, backlog, timeout, null); - } - - /** - * Constructor for the JxtaServerSocket object. - * - * @param group JXTA PeerGroup - * @param pipeAdv PipeAdvertisement on which pipe requests are accepted - * @param backlog the maximum length of the queue. - * @param timeout the specified timeout, in milliseconds - * @param credValidator the CredentialValidator - * @throws IOException if an I/O error occurs - */ - public JxtaServerSocket(PeerGroup group, PipeAdvertisement pipeAdv, int backlog, int timeout, CredentialValidator credValidator) throws IOException { - setSoTimeout(timeout); - this.credValidator = credValidator; - bind(group, pipeAdv, backlog); - } - - /** - * {@inheritDoc} - *

      - * Closes the JxtaServerPipe. - */ - @Override - protected void finalize() throws Throwable { - super.finalize(); - if (!closed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("JxtaServerSocket is being finalized without being previously closed. This is likely an application level bug."); - } - } - close(); - } - - /** - * {@inheritDoc} - */ - @Override - public Socket accept() throws IOException { - if (!isBound()) { - throw new SocketException("Socket is not bound yet"); - } - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Waiting for a connection"); - } - - while (true) { - if (isClosed()) { - throw new SocketException("Socket is closed"); - } - Message msg = queue.poll(timeout, TimeUnit.MILLISECONDS); - - if (isClosed()) { - throw new SocketException("Socket is closed"); - } - if (msg == null) { - throw new SocketTimeoutException("Timeout reached"); - } - - if (QUEUE_END_MESSAGE == msg) { - throw new SocketException("Socket is closed."); - } - - JxtaSocket socket = processMessage(msg); - - // make sure we have a socket returning - if (socket != null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("New socket connection " + socket); - } - return socket; - } else if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("No connection."); - } - } - } catch (InterruptedException ie) { - SocketException interrupted = new SocketException("interrupted"); - - interrupted.initCause(ie); - throw interrupted; - } - } - - /** - * Binds the JxtaServerSocket to a specific pipe advertisement - * - * @param group JXTA PeerGroup - * @param pipeAdv PipeAdvertisement on which pipe requests are accepted - * @throws IOException if an I/O error occurs - */ - public void bind(PeerGroup group, PipeAdvertisement pipeAdv) throws IOException { - bind(group, pipeAdv, DEFAULT_BACKLOG); - } - - /** - * Binds the JxtaServerSocket to a specific pipe advertisement - * - * @param group JXTA PeerGroup - * @param pipeadv PipeAdvertisement on which pipe requests are accepted - * @param backlog the maximum length of the queue. - * @throws IOException if an I/O error occurs - */ - public void bind(PeerGroup group, PipeAdvertisement pipeadv, int backlog) throws IOException { - if (PipeService.PropagateType.equals(pipeadv.getType())) { - throw new IOException("Propagate pipe advertisements are not supported"); - } - - if (backlog <= 0) { - throw new IllegalArgumentException("backlog must be > 0"); - } - - this.backlog = backlog; - queue = new ArrayBlockingQueue(backlog); - this.group = group; - this.pipeAdv = pipeadv; - PipeService pipeSvc = group.getPipeService(); - - serverPipe = pipeSvc.createInputPipe(pipeadv, this); - setBound(true); - } - - /** - * {@inheritDoc} - *

      - * Used to bind a JxtaServerSocket created with the no-arg constructor. - */ - @Override - public void bind(SocketAddress endpoint) throws IOException { - bind(endpoint, backlog); - } - - /** - * {@inheritDoc} - *

      - * Used to bind a JxtaServerSocket created with the no-arg constructor. - */ - @Override - public void bind(SocketAddress endpoint, int backlog) throws IOException { - if (endpoint instanceof JxtaSocketAddress) { - JxtaSocketAddress socketAddress = (JxtaSocketAddress) endpoint; - PeerGroup pg = PeerGroup.globalRegistry.lookupInstance(socketAddress.getPeerGroupId()); - - if (pg == null) { - throw new IOException( - "Can't connect socket in PeerGroup with id " + socketAddress.getPeerGroupId() - + ". No running instance of the group is registered."); - } - bind(pg.getWeakInterface(), socketAddress.getPipeAdv(), backlog); - pg.unref(); - } else { - throw new IllegalArgumentException("Unsupported subclass of SocketAddress; " + "use JxtaSocketAddress instead."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void close() throws IOException { - - if (closed) { - return; - } - closed = true; - - if (isBound()) { - // close all the pipe - serverPipe.close(); - setBound(false); - } - - queue.clear(); - while (true) { - try { - queue.put(QUEUE_END_MESSAGE); - // end queue message is now on the queue, we are done. - break; - } catch (InterruptedException woken) { - // We MUST put the terminal message onto the queue before - // finishing. We won't have a second chance. - Thread.interrupted(); - } - } - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Closed : " + this); - } - } - - /** - * @return the server socket's JxtaSocketAddress - * @see java.net.ServerSocket#getLocalSocketAddress() - */ - @Override - public SocketAddress getLocalSocketAddress() { - return new JxtaSocketAddress(getGroup(), getPipeAdv()); - } - - /** - * {@inheritDoc} - */ - @Override - public int getSoTimeout() throws IOException { - if (isClosed()) { - throw new SocketException("Socket is closed"); - } - - if (timeout > Integer.MAX_VALUE) { - return 0; - } else { - return (int) timeout; - } - } - - /** - * {@inheritDoc} - */ - @Override - public void setSoTimeout(int timeout) throws SocketException { - if (isClosed()) { - throw new SocketException("Socket is closed"); - } - - if (timeout < 0) { - throw new IllegalArgumentException("timeout must be >= 0"); - } - - if (0 == timeout) { - this.timeout = Long.MAX_VALUE; - } else { - this.timeout = (long) timeout; - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBound() { - return bound; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isClosed() { - return closed; - } - - /** - * Sets whether this socket is currently bound or not. A socket is - * considered bound if the local resources required in order to interact - * with a remote peer are allocated and open. - * - * @param boundState The new bound state. - */ - private synchronized void setBound(boolean boundState) { - this.bound = boundState; - } - - /** - * Gets the group associated with this JxtaServerSocket object - * - * @return The group value - */ - public PeerGroup getGroup() { - return group; - } - - /** - * Gets the PipeAdvertisement associated with this JxtaServerSocket object - * - * @return The pipeAdv value - */ - public PipeAdvertisement getPipeAdv() { - return pipeAdv; - } - - /** - * {@inheritDoc} - */ - public void pipeMsgEvent(PipeMsgEvent event) { - - // deal with messages as they come in - Message message = event.getMessage(); - - if (message == null) { - return; - } - - boolean pushed = false; - try { - pushed = queue.offer(message, timeout, TimeUnit.MILLISECONDS); - } catch (InterruptedException woken) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Interrupted", woken); - } - } - - if (!pushed && Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("backlog queue full, connect request dropped"); - } - } - - /** - * processMessage is the main mechanism in establishing bi-directional connections - *

      - * It accepts connection messages and constructs a JxtaSocket with a ephemeral - * InputPipe and a messenger. - * - * @param msg The client connection request (assumed not null) - * @return JxtaSocket Which may be null if an error occurs. - */ - private JxtaSocket processMessage(Message msg) { - - PipeAdvertisement remoteEphemeralPipeAdv = null; - PeerAdvertisement remotePeerAdv = null; - Credential credential = null; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Processing a connection message : " + msg); - } - - try { - MessageElement el = msg.getMessageElement(MSG_ELEMENT_NAMESPACE, reqPipeTag); - if (el != null) { - XMLDocument pipeAdvDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(el); - remoteEphemeralPipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(pipeAdvDoc); - } - - el = msg.getMessageElement(MSG_ELEMENT_NAMESPACE, remPeerTag); - if (el != null) { - XMLDocument peerAdvDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(el); - remotePeerAdv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(peerAdvDoc); - } - - el = msg.getMessageElement(MSG_ELEMENT_NAMESPACE, credTag); - if (el != null) { - try { - XMLDocument credDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(el); - credential = group.getMembershipService().makeCredential(credDoc); - if (!checkCred(credential)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Invalid credential"); - } - return null; - } - } catch (Exception ignored) { - // ignored - } - } - - boolean isReliable = false; - - el = msg.getMessageElement(MSG_ELEMENT_NAMESPACE, streamTag); - if (el != null) { - isReliable = Boolean.valueOf(el.toString()); - } - - if ((null != remoteEphemeralPipeAdv) && (null != remotePeerAdv)) { - return createEphemeralSocket(group, pipeAdv, remoteEphemeralPipeAdv, remotePeerAdv, localCredential, credential, isReliable); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Connection message did not contain valid connection information."); - } - return null; - } - } catch (IOException e) { - // deal with the error - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "IOException occured", e); - } - } catch (RuntimeException e) { - // deal with the error - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception occured", e); - } - } - return null; - } - - /** - * Invokes the specified CredentialValidator to very a credential - * @param cred the credential - * @return true if valid, or if no validator is specified - */ - private boolean checkCred(Credential cred) { - return credValidator == null || credValidator.checkCred(cred); - } - - /** - * Construct the emphemeral socket result from accept. This method exists - * primarily so that sub-classes can substitute a different JxtaSocket - * sub-class. - * - * @param group The peer group for the socket. - * @param pipeAdv The public pipe advertisement. - * @param remoteEphemeralPipeAdv The pipe advertisement of the remote peer's - * ephemeral pipe. - * @param remotePeerAdv The peer advertisement of the remote peer. - * @param localCredential Our credential. - * @param credential The credential of the remote peer. - * @param isReliable if true, uses the reliability library in non-direct mode - * @return The new JxtaSocket instance. - * @throws IOException if an io error occurs - */ - protected JxtaSocket createEphemeralSocket(PeerGroup group, PipeAdvertisement pipeAdv, PipeAdvertisement remoteEphemeralPipeAdv, PeerAdvertisement remotePeerAdv, Credential localCredential, Credential credential, boolean isReliable) throws IOException { - return new JxtaSocket(group, pipeAdv, remoteEphemeralPipeAdv, remotePeerAdv, localCredential, credential, isReliable); - } - - /** - * Sets the credential to be used by this socket connection. If no - * credentials are set, the default group credential will be used. - * - * @param localCredential The credential to be used for connection responses - * or null if the default credential is to be used. - */ - public void setCredential(Credential localCredential) { - this.localCredential = localCredential; - } - - /** - * {@inheritDoc} - *

      - * This output is suitable for debugging but should not be parsed. All - * of the information is available through other means. - */ - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - - result.append(getClass().getName()); - result.append('@'); - result.append(System.identityHashCode(this)); - - result.append('['); - result.append(pipeAdv.getPipeID()); - result.append(']'); - - result.append(isClosed() ? " CLOSED :" : " OPEN :"); - result.append(isBound() ? " BOUND " : " UNBOUND "); - return result.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocket.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocket.java deleted file mode 100644 index 0296f014..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocket.java +++ /dev/null @@ -1,1804 +0,0 @@ -/* - * Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.socket; - -import net.jxta.credential.Credential; -import net.jxta.document.*; -import net.jxta.endpoint.*; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.util.pipe.reliable.FixedFlowControl; -import net.jxta.impl.util.pipe.reliable.Outgoing; -import net.jxta.impl.util.pipe.reliable.OutgoingMsgrAdaptor; -import net.jxta.impl.util.pipe.reliable.ReliableInputStream; -import net.jxta.impl.util.pipe.reliable.ReliableOutputStream; -import net.jxta.logging.Logging; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.pipe.*; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.util.Collections; -import java.util.Iterator; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * JxtaSocket is a sub-class of java.net.socket, and should be used like a java.net.Socket. - * Key differences to keep in mind are the following : - *

      - * - JxtaSocket does not implement Nagle's algorithm, therefore at end of a data frame a flush must invoked to enure all - * buffered data is packaged and transmitted. - * - JxtaSocket does not implement keep-alive, therefore it is possible the underlaying messengers to be closed due to - * lack of inactivity, which manifests in a short latency, while the messenger are recreated. This limitation should cease - * to exist as soon the inactivity logic is removed. - * - */ -public class JxtaSocket extends Socket implements PipeMsgListener, OutputPipeListener { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(JxtaSocket.class.getName()); - private final static int MAXRETRYTIMEOUT = 120 * 1000; - private final static int DEFAULT_TIMEOUT = 15 * 1000; - - /** - * Default size for output buffers. Only used when we do not know the MTU - * size for messengers sending to the remote peer and as an upper bounds - * should the MTU size be really huge. - */ - private final static int DEFAULT_OUTPUT_BUFFER_SIZE = 256 * 1024; - - /** - * If true then this peer initiated the connection. - */ - private boolean initiator = false; - - /** - * The PeerGroup - */ - protected PeerGroup group; - - /** - * Pipe Advertisement of the well known pipe. - */ - protected PipeAdvertisement pipeAdv; - - /** - * Pipe Advertisement of local ephemeral pipe. - */ - protected PipeAdvertisement localEphemeralPipeAdv; - - /** - * The input pipe for our ephemeral pipe. We will receive all messages on this pipe. - */ - protected InputPipe localEphemeralPipeIn; - - /** - * Pipe Advertisement of it's ephemeral pipe. - */ - protected PipeAdvertisement remoteEphemeralPipeAdv; - - /** - * The Messenger we use to - */ - protected Messenger remoteEphemeralPipeMsgr; - - protected PipeService pipeSvc; - - /** - * The peer id of the peer we are connecting to or {@code null} if we are - * willing to connect to any peer. - */ - protected PeerID remotePeerID; - - /** - * Used to negotiate connection parameters - */ - protected OutputPipe connectOutpipe; - - /** - * The timeout of the read() of this socket's input stream - */ - private int soTimeout = 0; - - /** - * timeout for connect and close - */ - protected long timeout = 60 * 1000; - - /** - * retry timeout in millisecods - */ - protected int retryTimeout = 60 * 1000; - - /** - * maximum retry timeout allowed - */ - protected int maxRetryTimeout = MAXRETRYTIMEOUT; - - /** - * retry window size - */ - protected int windowSize = 20; - - /** - * Lock for output pipe resolution. - */ - protected final Object pipeResolveLock = new Object(); - - /** - * Lock for ephemeral pipe connect states. - */ - protected final Object socketConnectLock = new Object(); - - /** - * Lock for closing states. - */ - protected final Object closeLock = new Object(); - - /* - *used to determine whether to wait for an ack - */ - private boolean closeAckReceived = false; - - /** - * If {@code true} then this socket has been closed and can no longer be used. - */ - protected volatile boolean closed = false; - - /** - * If {@code true} then we believer our end of the connection is open. - */ - protected boolean bound = false; - - /** - * If {@code true} then we believe the remote peer currently has this socket open. - */ - protected boolean connected = false; - - /** - * Credential of the remote peer. - */ - protected Credential remoteCredential = null; - - /** - * Our credential that we provide to the remote peer. - */ - protected Credential localCredential = null; - - /** - * The remote peer advertisement. - */ - private PeerAdvertisement remotePeerAdv = null; - - /** - * If {@code true} then the socket is a stream socket otherwise it is a datagram socket. - */ - protected boolean isReliable = true; - - /** - * If {@code true} then the output stream has been shutdown. All attempts - * to write to the socket will fail. This socket can no longer be used to - * send data though it may remain capable of receiving data. - */ - private boolean outputShutdown = false; - - /** - * If {@code true} then the input stream has been shutdown. All attempts - * to read from the socket will fail. This socket can no longer be used to - * receive data though it may remain capable of sending data. - */ - private boolean inputShutdown = false; - - /** - * Used for sending all messages by the reliable output and input streams. - */ - protected Outgoing outgoing = null; - - /** - * The reliable input stream we use for receiving data if - * {@link #isReliable} is {@code true}. - */ - protected ReliableInputStream ris = null; - - /** - * The reliable output stream we use for sending data if - * {@link #isReliable} is {@code true}. - */ - protected ReliableOutputStream ros = null; - - /** - * The unreliable input stream we use for receiving data if - * {@link #isReliable} is {@code false}. - */ - protected JxtaSocketInputStream nonReliableInputStream = null; - - /** - * The unreliable output stream we use for sending data if - * {@link #isReliable} is {@code false}. - */ - protected JxtaSocketOutputStream nonReliableOutputStream = null; - - /** - * The size of the output buffers to use. If not set this defaults to the - * MTU size of the messenger to the remote peer. - */ - private int outputBufferSize = -1; - - /** - * This constructor does not establish a connection. Use this constructor - * when altering the default parameters, and options of the socket. - *

      - * By default connections are reliable, and the default timeout is 60 - * seconds. To alter a connection a call to create(false) changes the - * connection to an unreliable one. - */ - public JxtaSocket() {} - - /** - * This constructor is used by JxtaServer socket for creating JxtaSocket - * instances in response to incoming connections. - * - * @param group group context - * @param pipeAdv The original PipeAdvertisement - * @param localCredential Our credential. - * @param remoteEphemeralPipeAdv the phemeral pipe advertisement - * @param remotePeerAdv remote peer advertisement - * @param remoteCredential The remote peer's credential. - * @param isReliable {@code true} for reliable stream connection or - * {@code false} for unreliable stream connection. - * @throws IOException if an io error occurs - */ - protected JxtaSocket(PeerGroup group, PipeAdvertisement pipeAdv, PipeAdvertisement remoteEphemeralPipeAdv, PeerAdvertisement remotePeerAdv, Credential localCredential, Credential remoteCredential, boolean isReliable) throws IOException { - - this.initiator = false; - this.group = group; - this.pipeAdv = pipeAdv; - this.remoteEphemeralPipeAdv = remoteEphemeralPipeAdv; - this.localEphemeralPipeAdv = newEphemeralPipeAdv(pipeAdv); - this.remotePeerAdv = remotePeerAdv; - this.remotePeerID = remotePeerAdv.getPeerID(); - this.localCredential = localCredential; - this.remoteCredential = remoteCredential; - this.isReliable = isReliable; - - pipeSvc = group.getPipeService(); - bind(); - connect(); - - Message connectResponse = createConnectMessage(group, localEphemeralPipeAdv, localCredential, isReliable, initiator); - - remoteEphemeralPipeMsgr.sendMessage(connectResponse); - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("New socket : " + this); - } - } - - /** - * Create a JxtaSocket connected to the give JxtaSocketAddress. - * - * @param address JxtaSocketAddress to connect to - * @throws IOException if an io error occurs - */ - public JxtaSocket(SocketAddress address) throws IOException { - connect(address, DEFAULT_TIMEOUT); - } - - /** - * Create a JxtaSocket to any node listening on pipeAdv - * - * @param group group context - * @param pipeAdv PipeAdvertisement - * @throws IOException if an io error occurs - */ - public JxtaSocket(PeerGroup group, PipeAdvertisement pipeAdv) throws IOException { - connect(group, pipeAdv); - } - - /** - * Create a JxtaSocket to the given JxtaSocketAddress, within the timeout - * specified in milliseconds. - * - * @param address JxtaSocket address to connect to - * @param timeout The number of milliseconds within which the socket must - * be successfully created. An exception will be thrown if the socket - * cannot be created in the allotted time. A timeout value of {@code 0} - * (zero) specifies an infinite timeout. - * @throws IOException For failures in creating the socket. - * @throws SocketTimeoutException If the socket cannot be created before - * the timeout occurs. - */ - public JxtaSocket(SocketAddress address, int timeout) throws IOException { - connect(address, timeout); - } - - /** - * Create a JxtaSocket to any peer listening on pipeAdv this attempts - * establish a connection to specified pipe within the context of the - * specified group within timeout specified in milliseconds. - * - * @param group group context - * @param pipeAdv PipeAdvertisement - * @param timeout The number of milliseconds within which the socket must - * be successfully created. An exception will be thrown if the socket - * cannot be created in the allotted time. A timeout value of {@code 0} - * (zero) specifies an infinite timeout. - * @throws IOException if an io error occurs - * @throws SocketTimeoutException If the socket cannot be created before - * the timeout occurs. - */ - public JxtaSocket(PeerGroup group, PipeAdvertisement pipeAdv, int timeout) throws IOException { - connect(group, pipeAdv, timeout); - } - - /** - * Create a JxtaSocket to any peer listening on pipeAdv - * this attempts establish a connection to specified - * pipe within a context of group and within the timeout specified in milliseconds - * - * @param group group context - * @param peerid node to connect to - * @param pipeAdv PipeAdvertisement - * @param timeout The number of milliseconds within which the socket must - * be successfully created. An exception will be thrown if the socket - * cannot be created in the allotted time. A timeout value of {@code 0} - * (zero) specifies an infinite timeout. - * @throws IOException For failures in creating the socket. - * @throws SocketTimeoutException If the socket cannot be created before - * the timeout occurs. - */ - public JxtaSocket(PeerGroup group, PeerID peerid, PipeAdvertisement pipeAdv, int timeout) throws IOException { - connect(group, peerid, pipeAdv, timeout); - } - - /** - * Create a JxtaSocket to the given JxtaSocketAddress, within the timeout - * specified in milliseconds. The JxtaSocket can be reliable (stream) or - * not (datagram). If you want to use a SocketAddress in the constructor, - * this is the preferred method. Either that, or use JxtaSocket(), followed - * by create(boolean) to turn on reliability, followed by - * connect(SocketAddress, int) or connect(SocketAddress) to make the - * connection. - * - * @param address JxtaSocket address to connect to - * @param timeout The number of milliseconds within which the socket must - * be successfully created. An exception will be thrown if the socket - * cannot be created in the allotted time. A timeout value of {@code 0} - * (zero) specifies an infinite timeout. - * @param reliable {@code true} for reliable stream connection or - * {@code false} for unreliable stream connection. - * @throws IOException For failures in creating the socket. - * @throws SocketTimeoutException If the socket cannot be created before - * the timeout occurs. - */ - public JxtaSocket(SocketAddress address, int timeout, boolean reliable) throws IOException { - this.isReliable = reliable; - connect(address, timeout); - } - - /** - * Create a JxtaSocket to any peer listening on pipeAdv - * this attempts establish a connection to specified - * pipe within a context of group and within the timeout specified in milliseconds - * - * @param group group context - * @param peerid node to connect to - * @param pipeAdv PipeAdvertisement - * @param timeout The number of milliseconds within which the socket must - * be successfully created. An exception will be thrown if the socket - * cannot be created in the allotted time. A timeout value of {@code 0} - * (zero) specifies an infinite timeout. - * @param reliable {@code true} for reliable stream connection or - * {@code false} for unreliable stream connection. - * @throws IOException For failures in creating the socket. - * @throws SocketTimeoutException If the socket cannot be created before - * the timeout occurs. - */ - public JxtaSocket(PeerGroup group, PeerID peerid, PipeAdvertisement pipeAdv, int timeout, boolean reliable) throws IOException { - - this.isReliable = reliable; - connect(group, peerid, pipeAdv, timeout); - } - - /** - * {@inheritDoc} - */ - @Override - protected void finalize() throws Throwable { - if (!closed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("JxtaSocket is being finalized without being previously closed. This is likely a users bug."); - } - } - close(); - super.finalize(); - } - - /** - * Creates either a stream or a datagram socket. - * - * @param reliable {@code true} for reliable stream connection or {@code false} for unreliable stream connection. - * @throws IOException if an I/O error occurs while creating the socket. - * @deprecated Unreliable mode is being removed. Use JxtaBiDiPipe instead. - */ - @Deprecated - public void create(boolean reliable) throws IOException { - if (isBound()) { - throw new IOException("Socket already bound, it is not possible to change connection type"); - } - this.isReliable = reliable; - } - - /** - * {@inheritDoc} - *

      - * Unsupported operation, an IOException will be thrown. - * - * @throws IOException Thrown in all cases as this operation is not supported. - */ - @Override - public void bind(SocketAddress address) throws IOException { - throw new IOException("Unsupported operation, use java.net.Socket instead"); - } - - /** - * {@inheritDoc} - *

      - * The default connect timeout of 60 seconds is used If SocketAddress is not an instance of JxtaSocketAddress, an - * IOException will be thrown. - */ - @Override - public void connect(SocketAddress address) throws IOException { - connect(address, DEFAULT_TIMEOUT); - } - - /** - * {@inheritDoc} - *

      - * If SocketAddress is not an instance of JxtaSocketAddress, an IOException will be thrown. - */ - @Override - public void connect(SocketAddress address, int timeout) throws IOException { - if (!(address instanceof JxtaSocketAddress)) { - throw new IOException("Subclass of SocketAddress not supported. Use JxtaSocketAddress instead."); - } - JxtaSocketAddress socketAddress = (JxtaSocketAddress) address; - PeerGroup pg = PeerGroup.globalRegistry.lookupInstance(socketAddress.getPeerGroupId()); - - if (pg == null) { - throw new IOException("Can't connect socket in PeerGroup with id " + socketAddress.getPeerGroupId() - + ". No running instance of the group is registered."); - } - connect(pg.getWeakInterface(), socketAddress.getPeerId(), socketAddress.getPipeAdv(), timeout); - pg.unref(); - } - - /** - * Connects to a JxtaServerSocket on any peer within the default timeout of 60 seconds - * - * @param group group context - * @param pipeAdv PipeAdvertisement - * @throws IOException if an io error occurs - */ - public void connect(PeerGroup group, PipeAdvertisement pipeAdv) throws IOException { - connect(group, pipeAdv, DEFAULT_TIMEOUT); - } - - /** - * Connects to a JxtaServerSocket on any peer within a timeout specified in milliseconds - * - * @param group group context - * @param pipeAdv PipeAdvertisement - * @param timeout in milliseconds - * @throws IOException if an io error occurs - */ - public void connect(PeerGroup group, PipeAdvertisement pipeAdv, int timeout) throws IOException { - connect(group, null, pipeAdv, timeout); - } - - /** - * Connects to a JxtaServerSocket on a specific peer within a timeout specified in milliseconds - * - * @param group group context - * @param peerid peer to connect to - * @param pipeAdv PipeAdvertisement - * @param timeout timeout in milliseconds - * @throws IOException if an io error occurs - */ - public void connect(PeerGroup group, PeerID peerid, PipeAdvertisement pipeAdv, int timeout) throws IOException { - if (PipeService.PropagateType.equals(pipeAdv.getType())) { - throw new IOException("Propagate pipe advertisements are not supported"); - } - - if (timeout < 0) { - throw new IllegalArgumentException("timeout may not be negative"); - } - - this.initiator = true; - this.group = group; - this.remotePeerID = peerid; - this.pipeAdv = pipeAdv; - this.localEphemeralPipeAdv = newEphemeralPipeAdv(pipeAdv); - this.timeout = (timeout == 0) ? Long.MAX_VALUE : timeout; - - pipeSvc = group.getPipeService(); - bind(); - Message openMsg = createConnectMessage(group, localEphemeralPipeAdv, localCredential, isReliable, initiator); - long connectTimeoutAt = System.currentTimeMillis() + timeout; - - if (connectTimeoutAt < timeout) { - // ensure no overflow - connectTimeoutAt = Long.MAX_VALUE; - } - - // Create the output pipe and send this message. Need to retry the call - // to createOutputPipe. If there is no rendezvous yet and the - // destination is not reachable by mcast, then createOutputPipe has no - // effect. We repeat it with exponential delays. - if (peerid == null) { - pipeSvc.createOutputPipe(pipeAdv, this); - } else { - pipeSvc.createOutputPipe(pipeAdv, Collections.singleton(peerid), this); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Beginning Output Pipe Resolution. " + this); - } - - // Wait for the pipe resolution. - synchronized (pipeResolveLock) { - while (connectOutpipe == null) { - try { - long waitFor = connectTimeoutAt - System.currentTimeMillis(); - - if (waitFor <= 0) { - // too late - break; - } - if (connectOutpipe == null) { - // in case the pipe is resolved - pipeResolveLock.wait(waitFor); - } - } catch (InterruptedException ie) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Interrupted", ie); - } - Thread.interrupted(); - SocketException exp = new SocketException("Connect Interrupted"); - exp.initCause(ie); - throw exp; - } - } - } - - if (connectOutpipe == null) { - throw new SocketTimeoutException("Connection (resolution) timeout"); - } - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Sending connect message. " + this); - } - - // send connect message - connectOutpipe.send(openMsg); - - // wait for the connect response. - synchronized (socketConnectLock) { - while (!isConnected()) { - try { - long waitFor = connectTimeoutAt - System.currentTimeMillis(); - if (waitFor <= 0) { - // too late - break; - } - socketConnectLock.wait(waitFor); - } catch (InterruptedException ie) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Interrupted", ie); - } - Thread.interrupted(); - SocketException exp = new SocketException("Connect Interrupted"); - exp.initCause(ie); - throw exp; - } - } - } - } finally { - connectOutpipe.close(); - connectOutpipe = null; - } - - if (!isConnected()) { - throw new SocketTimeoutException("Connection timeout (connect)"); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("New socket connection : " + this); - } - } - - /** - * obtain the cred doc from the group object - * - * @param group the group context - * @return The Credential value - */ - protected static Credential getDefaultCredential(PeerGroup group) { - try { - MembershipService membership = group.getMembershipService(); - return membership.getDefaultCredential(); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to get credential", e); - } - } - return null; - } - - /** - * get the remote credential doc - * - * @return Credential StructuredDocument - */ - public Credential getCredentialDoc() { - try { - return remoteCredential; - } catch (Exception failure) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to generate credential document ", failure); - } - return null; - } - } - - /** - * Sets our credential to be used by this socket connection. If no - * credentials are set, the default group credential will be used. - * - * @param localCredential The credential to be used for connection responses - * or null if the default credential is to be used. - */ - public void setCredential(Credential localCredential) { - if (localCredential == null) { - this.localCredential = localCredential; - } else { - try { - MembershipService membership = group.getMembershipService(); - this.localCredential = membership.getDefaultCredential(); - } catch (Exception failed) { - this.localCredential = null; - } - } - } - - /** - * Create a connection request/response message - * - * @param group The group in which the socket is being used. - * @param pipeAdv Advertisement for our ephemeral pipe. - * @param credential Our credential or null if default credential is to - * be used. - * @param isReliable The socket is to be reliable (stream). - * @param initiator indicates initiator - * @return The message. - * @throws IOException if an I/O error occurs - */ - protected Message createConnectMessage(PeerGroup group, PipeAdvertisement pipeAdv, Credential credential, boolean isReliable, boolean initiator) throws IOException { - - Message msg = new Message(); - - if (credential == null) { - credential = getDefaultCredential(group); - } - - if ((credential == null) && PipeService.UnicastSecureType.equals(pipeAdv.getType())) { - throw new IOException("Credentials must be established to initiate a secure connection."); - } - - if (credential != null) { - try { - XMLDocument credDoc = (XMLDocument) credential.getDocument(MimeMediaType.XMLUTF8); - - msg.addMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, - new TextDocumentMessageElement(JxtaServerSocket.credTag, credDoc, null)); - } catch (Exception failed) { - IOException failure = new IOException("Could not generate credential element."); - failure.initCause(failed); - throw failure; - } - } - - msg.addMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, - new TextDocumentMessageElement(initiator ? JxtaServerSocket.reqPipeTag : JxtaServerSocket.remPipeTag, - (XMLDocument) pipeAdv.getDocument(MimeMediaType.XMLUTF8), null)); - - msg.addMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, - new TextDocumentMessageElement(JxtaServerSocket.remPeerTag, - (XMLDocument) group.getPeerAdvertisement().getDocument(MimeMediaType.XMLUTF8), null)); - - msg.addMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, - new StringMessageElement(JxtaServerSocket.streamTag, Boolean.toString(isReliable), null)); - - return msg; - } - - /** - * Create a pipe advertisement for an ephemeral pipe (w/random pipe ID) from an existing pipe advertisement. - * The specified pipe adveritsement is only used for the name and type - * - * @param pipeAdv to get the basename and type from - * @return A new pipe advertisement for an ephemeral pipe. - */ - protected static PipeAdvertisement newEphemeralPipeAdv(PipeAdvertisement pipeAdv) { - PipeAdvertisement adv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType()); - PeerGroupID gid = (PeerGroupID) ((PipeID) pipeAdv.getPipeID()).getPeerGroupID(); - adv.setPipeID(IDFactory.newPipeID(gid)); - adv.setName(pipeAdv.getName() + ".remote"); - adv.setType(pipeAdv.getType()); - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBound() { - return bound; - } - - /** - * Sets whether this socket is currently bound or not. A socket is considered bound if the local resources required - * in order to interact with a remote peer are allocated and open. - * - * @param boundState The new bound state. - */ - private void setBound(boolean boundState) { - bound = boundState; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isConnected() { - return connected; - } - - /** - * Sets whether this socket is currently connected or not. A socket is - * considered connected if is believed that the Socket's remote peer has - * the resources required in order to interact with a local peer (us) - * allocated and open. - * - * @param connectedState The new connected state. - */ - private void setConnected(boolean connectedState) { - connected = connectedState; - } - - /** - * Opens our ephemeral input pipe enabling us to receive messages. - * - * @throws IOException Thrown for errors in creating the input pipe. - */ - private void bind() throws IOException { - this.localEphemeralPipeIn = pipeSvc.createInputPipe(localEphemeralPipeAdv, this); - // The socket is bound now. - setBound(true); - } - - /** - * Create an appropriate Outgoing Adaptor. This method exists primarily - * so that sub-classes can substitute a different Outgoing sub-class. - * - * @param msgr The messenger to be wrapped. - * @param timeout The timeout value; - * @return Outgoing The messenger wrapped in an appropriate adaptor. - */ - protected Outgoing makeOutgoing(Messenger msgr, long timeout) { - return new OutgoingMsgrAdaptor(msgr, (int) timeout); - } - - /** - * Opens the ephemeral output pipe for the remote peer. Also opens the - * input and output streams. (delaying adds complexity). - * - * @throws IOException Thrown for errors in opening resources. - */ - private void connect() throws IOException { - - remoteEphemeralPipeMsgr = lightweightOutputPipe(group, remoteEphemeralPipeAdv, remotePeerAdv); - - if (remoteEphemeralPipeMsgr == null) { - throw new IOException("Could not create messenger back to connecting peer"); - } - - // Force the buffer size smaller if user set it too high. - if (remoteEphemeralPipeMsgr.getMTU() < outputBufferSize) { - outputBufferSize = Math.min((int) remoteEphemeralPipeMsgr.getMTU(), DEFAULT_OUTPUT_BUFFER_SIZE); - } - - if (outputBufferSize == -1) { - outputBufferSize = Math.min((int) remoteEphemeralPipeMsgr.getMTU(), DEFAULT_OUTPUT_BUFFER_SIZE); - } - - // Force the creation of the inputStream now. Waiting until someone - // calls getInputStream() would likely cause us to drop messages. - if (isReliable) { - outgoing = makeOutgoing(remoteEphemeralPipeMsgr, retryTimeout); - ris = new ReliableInputStream(outgoing, soTimeout); - ros = new ReliableOutputStream(outgoing, new FixedFlowControl(windowSize)); - try { - ros.setSendBufferSize(outputBufferSize); - } catch (IOException ignored) {// it's only a preference... - } - } else { - nonReliableInputStream = new JxtaSocketInputStream(this, windowSize); - nonReliableOutputStream = new JxtaSocketOutputStream(this, outputBufferSize); - } - - // the socket is now connected! - setConnected(true); - } - - /** - * Returns the internal output stream buffer size - * - * @return the internal buffer size. - * @deprecated Use the standard {@link #getSendBufferSize()} method instead. - */ - @Deprecated - public int getOutputStreamBufferSize() { - return (outputBufferSize == -1) ? DEFAULT_OUTPUT_BUFFER_SIZE : outputBufferSize; - } - - /** - * Sets the internal output stream buffer size. - * - * @param size The internal buffer size. - * @throws IOException if an I/O error occurs - * @deprecated Use the standard {@link #setSendBufferSize(int)} method instead. - */ - @Deprecated - public void setOutputStreamBufferSize(int size) throws IOException { - setSendBufferSize(size); - } - - /** - * {@inheritDoc} - */ - @Override - public InputStream getInputStream() throws IOException { - checkState(); - - if (isInputShutdown()) { - throw new SocketException("Input already shutdown."); - } - - if (isReliable) { - return ris; - } else { - return nonReliableInputStream; - } - } - - /** - * {@inheritDoc} - */ - @Override - public OutputStream getOutputStream() throws IOException { - checkState(); - if (isOutputShutdown()) { - throw new SocketException("Output already shutdown."); - } - return isReliable ? ros : nonReliableOutputStream; - } - - /** - * {@inheritDoc} - *

      - * We hard-close both the input and output streams. Nothing can be - * written or read to the socket after this method. Any queued incoming - * data is discarded. Any additional incoming messages will be ACKed but - * their content will be discarded. We will attempt to send any data which - * has already been written to the OutputStream. - *

      - * Once the output queue is empty we will send a close message to tell - * the remote side that no more data is coming. - *

      - * This is the only method in this class which is {@code synchronized}. - * All others use internal synchronization. - */ - @Override - public synchronized void close() throws IOException { - try { - synchronized (closeLock) { - long closeEndsAt = System.currentTimeMillis() + timeout; - - if (closeEndsAt < timeout) { - closeEndsAt = Long.MAX_VALUE; - } - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Closing " + this + " timeout=" + timeout + "ms."); - } - if (closed) { - return; - } - - closed = true; - shutdownOutput(); - shutdownInput(); - while (isConnected()) { - long closingFor = closeEndsAt - System.currentTimeMillis(); - - if (closingFor <= 0) { - break; - } - - if (isReliable) { - try { - if (ros.isQueueEmpty()) { - // Only send a close if the queue is empty. - sendClose(); - } else { - // Reliable Output Stream not empty. Don't send close yet. - ros.waitQueueEmpty(1000); - continue; - } - } catch (InterruptedException woken) { - Thread.interrupted(); - break; - } - } else { - sendClose(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sent close, awaiting ACK for " + this); - } - - // Don't send our close too many times. - try { - long nextTry = Math.min(20000, closingFor); - - if (nextTry > 0 && isConnected()) { - closeLock.wait(nextTry); - } - } catch (InterruptedException woken) { - Thread.interrupted(); - break; - } - } - - if (isConnected()) { - // Last ditch close attempt - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Still connected at end of timeout. Forcing closed." + this); - } - sendClose(); - throw new SocketTimeoutException("Failed to receive close ack from remote connection."); - } - } - } finally { - // No matter what else happens at the end of close() we are no - // longer connected and no longer bound. - setConnected(false); - unbind(); - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Socket closed : " + this); - } - } - } - - /** - * This is called when closure is initiated on the remote side. By - * convention we receive the close message only after we have ACKed the last - * data segment. - *

      - * We soft-close the InputStream which allows us to read data already - * received. - *

      - * We hard-close our output stream and discard all queued, unACKed data - * as the remote side doesn't want to receive it (the remote side has - * already unbound themselves, they just want our close ACK in order to clean - * up.) - * - * @throws IOException if an I/O error occurs - */ - protected void closeFromRemote() throws IOException { - synchronized (closeLock) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.INFO)) { - LOG.info("Received a remote close request." + this); - } - - if (isConnected()) { - setConnected(false); - if (isReliable) { - ris.softClose(); - ros.hardClose(); - } else { - nonReliableInputStream.softClose(); - nonReliableOutputStream.hardClose(); - } - } - - // If we are still bound then send them a close ACK. - if (isBound() && (ros != null && ros.isQueueEmpty())) { - // do not ack until the queue is empty - sendCloseACK(); - } - if (closeAckReceived) { - closeLock.notifyAll(); - } - } - } - - /** - * Closes the input pipe which we use to receive messages and the messenger - * used for sending messages. - */ - protected synchronized void unbind() { - if (!isBound()) { - return; - } - - if (isReliable) { - try { - ris.close(); - } catch (IOException ignored) {// ignored - } - - ros.hardClose(); - } else { - nonReliableInputStream.close(); - nonReliableOutputStream.hardClose(); - } - - // We are no longer bound - setBound(false); - - // close pipe and messenger - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Closing ephemeral input pipe"); - } - - localEphemeralPipeIn.close(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Closing remote ephemeral pipe messenger"); - } - - if(null != outgoing) { - outgoing.close(); - } - remoteEphemeralPipeMsgr.close(); - } - - /** - * {@inheritDoc} - */ - public void pipeMsgEvent(PipeMsgEvent event) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.log(Level.FINER, "Pipe Message Event for " + this + "\n\t" + event.getMessage() + " for " + event.getPipeID()); - } - - Message message = event.getMessage(); - if (message == null) { - return; - } - - // look for close request/ack - MessageElement element = message.getMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, JxtaServerSocket.closeTag); - - if (element != null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Handling a close message " + this + " : " + element.toString()); - } - if (JxtaServerSocket.closeReqValue.equals(element.toString())) { - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received a close request"); - } - closeFromRemote(); - } catch (IOException ie) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "failed during closeFromRemote", ie); - } - } - } else if (JxtaServerSocket.closeAckValue.equals(element.toString())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received a close acknowledgement"); - } - synchronized (closeLock) { - closeAckReceived = true; - setConnected(false); - closeLock.notifyAll(); - } - } - return; - } - - if (!isConnected()) { - // connect response - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Processing connect response : " + message); - } - - // look for a remote pipe answer - element = message.getMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, JxtaServerSocket.remPipeTag); - PipeAdvertisement incomingPipeAdv = null; - - if (element != null) { - try { - XMLDocument pipeAdvDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(element); - - incomingPipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(pipeAdvDoc); - } catch (IOException badPipeAdv) {// ignored - } - } - - element = message.getMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, JxtaServerSocket.remPeerTag); - PeerAdvertisement incomingRemotePeerAdv = null; - - if (element != null) { - try { - XMLDocument peerAdvDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(element); - incomingRemotePeerAdv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(peerAdvDoc); - } catch (IOException badPeerAdv) {// ignored - } - } - - element = message.getMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, JxtaServerSocket.credTag); - Credential incomingCredential = null; - - if (element != null) { - try { - StructuredDocument incomingCredentialDoc = StructuredDocumentFactory.newStructuredDocument(element); - incomingCredential = group.getMembershipService().makeCredential(incomingCredentialDoc); - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Unable to generate credential for " + this, failed); - } - } - } - - element = message.getMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, JxtaServerSocket.streamTag); - boolean incomingIsReliable = isReliable; - - if (element != null) { - incomingIsReliable = Boolean.valueOf(element.toString()); - } - - if ((null != incomingPipeAdv) && (null != incomingRemotePeerAdv)) { - if ((null != remotePeerID) && (remotePeerID != incomingRemotePeerAdv.getPeerID())) { - // let the connection attempt timeout - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning( - "Connection response from wrong peer! " + remotePeerID + " != " - + incomingRemotePeerAdv.getPeerID()); - } - return; - } - - synchronized (socketConnectLock) { - if (!isConnected()) { - remoteCredential = incomingCredential; - remotePeerAdv = incomingRemotePeerAdv; - remotePeerID = incomingRemotePeerAdv.getPeerID(); - remoteEphemeralPipeAdv = incomingPipeAdv; - isReliable = incomingIsReliable; - - // Force the creation of the inputStream now. Waiting until someone - // calls getInputStream() would likely cause us to drop messages. - - // FIXME: it would be even better if we could create the - // input stream BEFORE having the output pipe resolved, but - // that would force us to have the MsrgAdaptor block - // until we can give it the real pipe or msgr... later. - try { - connect(); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Connection failed : " + this, failed); - } - return; - } - socketConnectLock.notify(); - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "New Socket Connection : " + this); - } - } - } - return; - } - } - - // Often we are called to handle data before the socket is connected. - synchronized (socketConnectLock) { - long timeoutAt = System.currentTimeMillis() + timeout; - if (timeoutAt < timeout) { - timeoutAt = Long.MAX_VALUE; - } - - while (!isClosed() && !isConnected()) { - long waitFor = timeoutAt - System.currentTimeMillis(); - - if (waitFor <= 0) { - break; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Holding " + message + " for " + timeout); - } - - try { - socketConnectLock.wait(timeout); - } catch (InterruptedException woken) { - return; - } - } - } - - if (!isReliable) { - // is there data ? - Iterator dataElements = message.getMessageElements(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, - JxtaServerSocket.dataTag); - - while (dataElements.hasNext()) { - MessageElement anElement = dataElements.next(); - nonReliableInputStream.enqueue(anElement); - } - } else { - // Give ACKs to the Reliable Output Stream - if (ros != null) { - ros.recv(message); - } - // Give data blocks to the Reliable Input Stream - if (ris != null) { - ris.recv(message); - } - } - } - - /** - * {@inheritDoc} - */ - public void outputPipeEvent(OutputPipeEvent event) { - OutputPipe op = event.getOutputPipe(); - - if (op.getAdvertisement() == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("The output pipe has no internal pipe advertisement. discarding event"); - } - return; - } - // name can be different, therefore check the id + type - if (pipeAdv.getID().equals(op.getAdvertisement().getID()) && pipeAdv.getType().equals(op.getAdvertisement().getType())) { - synchronized (pipeResolveLock) { - // modify op within lock to prevent a race with the if. - if (connectOutpipe == null) { - connectOutpipe = op; - // if not null, will be closed. - op = null; - } - pipeResolveLock.notify(); - } - // Ooops one too many, we were too fast re-trying. - if (op != null) { - op.close(); - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unexpected OutputPipe :" + op); - } - } - } - - /** - * A lightweight output pipe constructor, note the return type - * Since all the info needed is available, there's no need for to use the pipe service - * to resolve the pipe we have all we need to construct a messenger. - * - * @param group group context - * @param pipeAdv Remote Pipe Advertisement - * @param peerAdv Remote Peer Advertisement - * @return Messenger - */ - protected static Messenger lightweightOutputPipe(PeerGroup group, PipeAdvertisement pipeAdv, PeerAdvertisement peerAdv) { - EndpointService endpoint = group.getEndpointService(); - ID opId = pipeAdv.getPipeID(); - String destPeer = peerAdv.getPeerID().getUniqueValue().toString(); - - // Get an endpoint messenger to that address - EndpointAddress addr; - RouteAdvertisement routeHint = net.jxta.impl.endpoint.EndpointUtils.extractRouteAdv(peerAdv); - if (pipeAdv.getType().equals(PipeService.UnicastType)) { - addr = new EndpointAddress("jxta", destPeer, "PipeService", opId.toString()); - } else if (pipeAdv.getType().equals(PipeService.UnicastSecureType)) { - addr = new EndpointAddress("jxtatls", destPeer, "PipeService", opId.toString()); - } else { - // not a supported type - throw new IllegalArgumentException(pipeAdv.getType() + " is not a supported pipe type"); - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("New pipe lightweight messenger for " + addr); - } - return endpoint.getMessenger(addr, routeHint); - } - - /** - * Sends a close message - * @throws IOException if an io error occurs - */ - private void sendClose() throws IOException { - Message msg = new Message(); - - msg.addMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE - , - new StringMessageElement(JxtaServerSocket.closeTag, JxtaServerSocket.closeReqValue, null)); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending a close request " + this + " : " + msg); - } - remoteEphemeralPipeMsgr.sendMessageN(msg, null, null); - } - - /** - * Sends a close ack message - * @throws IOException if an io error occurs - */ - private void sendCloseACK() throws IOException { - Message msg = new Message(); - msg.addMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, - new StringMessageElement(JxtaServerSocket.closeTag, JxtaServerSocket.closeAckValue, null)); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending a close ACK " + this + " : " + msg); - } - remoteEphemeralPipeMsgr.sendMessageN(msg, null, null); - } - - /** - * {@inheritDoc} - */ - @Override - public int getSoTimeout() throws SocketException { - if (isClosed()) { - throw new SocketException("Socket is closed"); - } - if (timeout > Integer.MAX_VALUE) { - return 0; - } else { - return (int) timeout; - } - } - - /** - * {@inheritDoc} - */ - @Override - public void setSoTimeout(int soTimeout) throws SocketException { - if (soTimeout < 0) { - throw new IllegalArgumentException("Invalid Socket timeout :" + soTimeout); - } - - this.timeout = soTimeout; - if (!isBound()) { - return; - } - - // If we are bound then set the timeout on the streams. - // FIXME, ros does not define a timeout as it only relies on window saturation, it should take into account - // the socket timeout - if (isReliable) { - if (ris != null) { - ris.setTimeout(soTimeout); - } - } else { - nonReliableInputStream.setTimeout((long) soTimeout); - } - } - - /** - * Gets the Maximum Retry Timeout of the reliability layer - * - * @return The maximum retry Timeout value - * @deprecated The reliability layer manages it's own maximum. This value is not useful. - */ - @Deprecated - public int getMaxRetryTimeout() { - return maxRetryTimeout; - } - - /** - * Gets the Maximum Retry Timeout of the reliability layer - * - * @param maxRetryTimeout The new maximum retry timeout value - * @throws IllegalArgumentException if maxRetryTimeout exceeds jxta platform maximum retry timeout - * @deprecated The reliability layer manages it's own maximum. This value is not useful. - */ - @Deprecated - public void setMaxRetryTimeout(int maxRetryTimeout) { - if (maxRetryTimeout <= 0 || maxRetryTimeout > MAXRETRYTIMEOUT) { - throw new IllegalArgumentException("Invalid Maximum retry timeout :" + maxRetryTimeout + " Exceed Global maximum retry timeout :" - + MAXRETRYTIMEOUT); - } - this.maxRetryTimeout = maxRetryTimeout; - } - - /** - * Gets the Retry Timeout of the reliability layer - * - * @return The retry Timeout value - */ - public int getRetryTimeout() { - return retryTimeout; - } - - /** - * Sets the Retry Timeout of the underlying reliability layer. - * In reliable mode it is possible for this call to block - * trying to obtain a lock on reliable input stream - * - * @param retryTimeout The new retry timeout value - * @throws SocketException if an I/O error occurs - */ - public void setRetryTimeout(int retryTimeout) throws SocketException { - if (retryTimeout <= 0 || retryTimeout > maxRetryTimeout) { - throw new IllegalArgumentException("Invalid Retry Socket timeout :" + retryTimeout); - } - this.retryTimeout = retryTimeout; - if (outgoing != null) { - outgoing.setTimeout(retryTimeout); - } - } - - /** - * When in reliable mode, gets the Reliable library window size - * - * @return The windowSize value - */ - public int getWindowSize() { - return windowSize; - } - - /** - * When in reliable mode, sets the Reliable library window size - * - * @param windowSize The new window size value - * @throws SocketException if an I/O error occurs - */ - public void setWindowSize(int windowSize) throws SocketException { - if (isBound()) { - throw new SocketException("Socket bound. Can not change the window size"); - } - this.windowSize = windowSize; - } - - /** - * Returns the closed state of the JxtaSocket. - * - * @return true if the socket has been closed - */ - @Override - public boolean isClosed() { - return closed; - } - - /** - * Performs on behalf of JxtaSocketOutputStream. - * - * @param buf the data. - * @param offset the start offset in the data. - * @param length the number of bytes to write. - * @throws IOException if an I/O error occurs - * @see java.io.OutputStream#write - */ - protected void write(byte[] buf, int offset, int length) throws IOException { - checkState(); - if (isReliable) { - ros.write(buf, offset, length); - } else { - byte[] bufCopy = new byte[length]; - System.arraycopy(buf, offset, bufCopy, 0, length); - - Message msg = new Message(); - msg.addMessageElement(JxtaServerSocket.MSG_ELEMENT_NAMESPACE, - new ByteArrayMessageElement(JxtaServerSocket.dataTag, MimeMediaType.AOS, bufCopy, 0, length, null)); - remoteEphemeralPipeMsgr.sendMessageB(msg, null, null); - } - } - - /** - * @throws SocketException if closed, not bound or not connected. - */ - private void checkState() throws SocketException { - if (isClosed()) { - throw new SocketException("Socket is closed."); - } else if (!isBound()) { - throw new SocketException("Socket not bound."); - } else if (!isConnected()) { - throw new SocketException("Socket not connected."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public int getSendBufferSize() throws SocketException { - if (isOutputShutdown()) { - throw new SocketException("Socket is closed"); - } - return (outputBufferSize == -1) ? DEFAULT_OUTPUT_BUFFER_SIZE : outputBufferSize; - } - - /** - * {@inheritDoc} - */ - @Override - public void setSendBufferSize(int size) throws SocketException { - if (isOutputShutdown()) { - throw new SocketException("Socket is closed"); - } - - if (size < 1) { - throw new IllegalArgumentException("negative/zero buffer size"); - } - - if ((null != remoteEphemeralPipeMsgr) && (size > remoteEphemeralPipeMsgr.getMTU())) { - throw new IllegalArgumentException("Buffer size larger than limit : " + remoteEphemeralPipeMsgr.getMTU()); - } - - outputBufferSize = size; - if (null != ros) { - try { - ros.setSendBufferSize(size); - } catch (SocketException failure) { - throw failure; - } catch (IOException failed) { - SocketException failure = new SocketException("Failed"); - - failure.initCause(failed); - throw failure; - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public int getReceiveBufferSize() throws SocketException { - if (isInputShutdown()) { - throw new SocketException("Socket is closed"); - } - // this is just rough size - return outputBufferSize * windowSize; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean getKeepAlive() throws SocketException { - if (inputShutdown) { - throw new SocketException("Socket is closed"); - } - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public int getTrafficClass() throws SocketException { - throw new SocketException("TrafficClass not yet defined"); - } - - /** - * {@inheritDoc} - */ - @Override - public void setTrafficClass(int tc) throws SocketException { - // a place holder when and if we decide to add hints regarding - // flow info hints such as (IPTOS_LOWCOST (0x02), IPTOS_RELIABILITY (0x04), etc - throw new SocketException("TrafficClass not yet defined"); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isInputShutdown() { - return inputShutdown; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isOutputShutdown() { - return outputShutdown; - } - - /** - * {@inheritDoc} - */ - @Override - public void sendUrgentData(int data) throws IOException { - throw new SocketException("Urgent data not supported"); - } - - /** - * {@inheritDoc} - */ - @Override - public void setOOBInline(boolean state) throws SocketException { - throw new SocketException("Enable/disable OOBINLINE supported"); - } - - /** - * {@inheritDoc} - */ - @Override - public void setKeepAlive(boolean state) throws SocketException { - if (isClosed()) { - throw new SocketException("Socket is closed"); - } - throw new SocketException("Operation not supported"); - } - - /** - * {@inheritDoc} - */ - @Override - public void shutdownInput() throws IOException { - inputShutdown = true; - if (isReliable) { - // hard close (EOF on next read) - ris.close(); - } else { - // hard close (EOF on next read) - nonReliableInputStream.close(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void shutdownOutput() throws IOException { - outputShutdown = true; - if (isReliable) { - ros.setLingerDelay(timeout); - // soft close (finish sending if you can) - ros.close(); - } else { - // soft close (finish sending if you can) - nonReliableOutputStream.close(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public SocketAddress getLocalSocketAddress() { - if (!isBound()) { - return null; - } - return new JxtaSocketAddress(group, localEphemeralPipeAdv, group.getPeerAdvertisement()); - } - - /** - * {@inheritDoc} - */ - @Override - public SocketAddress getRemoteSocketAddress() { - if (!isConnected()) { - return null; - } - return new JxtaSocketAddress(group, remoteEphemeralPipeAdv, remotePeerAdv); - } - - /** - * {@inheritDoc} - *

      - * This output is suitable for debugging but should not be parsed. All - * of the information is available through other means. - */ - @Override - public String toString() { - - StringBuilder result = new StringBuilder(); - - result.append(getClass().getName()); - result.append('@'); - result.append(System.identityHashCode(this)); - result.append('['); - - if (null != pipeAdv) { - result.append(pipeAdv.getPipeID().getUniqueValue()); - } - result.append('/'); - - if (null != localEphemeralPipeAdv) { - result.append(localEphemeralPipeAdv.getPipeID().getUniqueValue()); - } - result.append(']'); - result.append(isClosed() ? " CLOSED :" : " OPEN :"); - result.append(initiator ? " I " : " i "); - result.append(isReliable ? " R " : " r "); - result.append(isBound() ? " B " : " b "); - result.append(isConnected() ? " C " : " c "); - - return result.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocketAddress.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocketAddress.java deleted file mode 100644 index 749dd74e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocketAddress.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.socket; - - -import net.jxta.document.MimeMediaType; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeAdvertisement; - -import java.net.SocketAddress; - - -/** - * This class implements a JxtaSocket address (PeerGroup ID + Pipe Advertisement - * + (optional) Peer ID). - *

      - * It provides an immutable object used by sockets for binding, connecting, or as - * returned values. - * - * @author vwilliams - * @see net.jxta.socket.JxtaSocket - * @see net.jxta.socket.JxtaServerSocket - * @see java.net.SocketAddress - * @see java.net.Socket - * @see java.net.ServerSocket - */ -public class JxtaSocketAddress extends SocketAddress { - - private final PeerGroupID peerGroupId; - private final PipeAdvertisement pipeAdv; - private final PeerID peerId; - private final PeerAdvertisement peerAdv; - - private transient String pipeDoc; // convenience, see getPipeDocAsString() - - /** - * Creates a new instance of JxtaSocketAddress. - * - * @param peerGroup peer group within which this socket exists - * @param pipeAdv the advertisement of a pipe for the socket to listen on - */ - public JxtaSocketAddress(PeerGroup peerGroup, PipeAdvertisement pipeAdv) { - this(peerGroup.getPeerGroupID(), pipeAdv, null); - } - - /** - * Creates a new instance of JxtaSocketAddress. - * - * @param peerGroup peer group within which this socket exists - * @param pipeAdv the advertisement of a pipe for the socket to listen on - * @param peerId the ID of a specific peer to be contacted over this socket - * (may be null) - * @deprecated use the PeerAdvertisement variant instead - */ - @Deprecated - public JxtaSocketAddress(PeerGroup peerGroup, PipeAdvertisement pipeAdv, PeerID peerId) { - this(peerGroup.getPeerGroupID(), pipeAdv, peerId); - } - - /** - * Creates a new instance of JxtaSocketAddress. - * - * @param peerGroup peer group within which this socket exists - * @param pipeAdv the advertisement of a pipe for the socket to listen on - * @param peerAdv the PeerAdvertisement (may not be null) - */ - public JxtaSocketAddress(PeerGroup peerGroup, PipeAdvertisement pipeAdv, PeerAdvertisement peerAdv) { - if (peerGroup == null) { - throw new IllegalArgumentException("peerGroupId is required."); - } - if (pipeAdv == null) { - throw new IllegalArgumentException("pipeAdv is required."); - } - if (peerAdv == null) { - throw new IllegalArgumentException("pipeAdv is required."); - } - - this.pipeAdv = pipeAdv.clone(); - this.peerGroupId = peerGroup.getPeerGroupID(); - this.peerId = peerAdv.getPeerID(); - this.peerAdv = peerAdv.clone(); - } - - /** - * Creates a new instance of JxtaSocketAddress. - * - * @param peerGroupId ID of peer group within which this socket exists - * @param pipeAdv the advertisement of a pipe for the socket to listen on - * @deprecated use the PeerAdvertisement variant instead - */ - @Deprecated - public JxtaSocketAddress(PeerGroupID peerGroupId, PipeAdvertisement pipeAdv) { - this(peerGroupId, pipeAdv, null); - } - - /** - * Creates a new instance of JxtaSocketAddress. - * - * @param peerGroupId ID of peer group within which this socket exists - * @param pipeAdv the advertisement of a pipe for the socket to listen on - * @param peerId the ID of a specific peer to be contacted over this socket - * (may be null) - * @throws IllegalArgumentException if peerGroupId or pipeAdv are null - * @deprecated use the PeerAdvertisement variant instead - */ - @Deprecated - public JxtaSocketAddress(PeerGroupID peerGroupId, PipeAdvertisement pipeAdv, PeerID peerId) { - - if (peerGroupId == null) { - throw new IllegalArgumentException("peerGroupId is required."); - } - if (pipeAdv == null) { - throw new IllegalArgumentException("pipeAdv is required."); - } - - this.pipeAdv = pipeAdv.clone(); - this.peerGroupId = peerGroupId; - this.peerId = peerId; - this.peerAdv = null; - } - - /** - * Returns the PeerGroupID element of the address - * - * @return the PeerGroupID - */ - public PeerGroupID getPeerGroupId() { - return this.peerGroupId; - } - - /** - * Returns the PipeAdvertisement element of the address - * - * @return the PipeAdvertisement - */ - public PipeAdvertisement getPipeAdv() { - // preserve immutability - return pipeAdv.clone(); - } - - /** - * Returns the PeerID element of the address. May be null. - * - * @return the PeerID, if there is one, null otherwise - */ - public PeerID getPeerId() { - return this.peerId; - } - - /** - * Returns the PeerID element of the address. May be null. - * - * @return the PeerAdvertisement, if there is one, null otherwise - */ - public PeerAdvertisement getPeerAdvertisement() { - return this.peerAdv; - } - - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - - if (obj instanceof JxtaSocketAddress) { - JxtaSocketAddress addr = (JxtaSocketAddress) obj; - - if (!peerGroupId.equals(addr.getPeerGroupId())) { - return false; - } - if (!pipeAdv.equals(addr.getPipeAdv())) { - return false; - } - if (peerId != null) { - if (!peerId.equals(addr.getPeerId())) { - return false; - } - } else if (addr.getPeerId() != null) { - return false; - } - - return true; - } - return false; - } - - @Override - public int hashCode() { - - int result = 17; - - result = 37 * result + peerGroupId.hashCode(); - result = 37 * result + pipeAdv.hashCode(); - if (peerId != null) { - result = 37 * result + peerId.hashCode(); - } - return result; - } - - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - String lineSep = System.getProperty("line.separator"); - - result.append(lineSep).append("JxtaSocketAdress:").append(lineSep); - result.append(" PeerGroupID: ").append(peerGroupId.toString()).append(lineSep); - if (peerId != null) { - result.append(lineSep).append(" PeerID: ").append(peerId.toString()).append(lineSep); - } - result.append(" Pipe Adv: ").append(lineSep).append(" ").append(getPipeDocAsString()); - return result.toString(); - } - - /* - * A convenience function to lazily-initialize a variable with the string - * representaiton of the pipe advertisement and return it as needed. - */ - private synchronized String getPipeDocAsString() { - if (pipeDoc == null) { - // Using plain text to avoid unpredictable white space - // nodes. [vwilliams] - pipeDoc = pipeAdv.getDocument(MimeMediaType.TEXTUTF8).toString(); - } - return pipeDoc; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocketInputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocketInputStream.java deleted file mode 100644 index bae578a3..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocketInputStream.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.socket; - - -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InterruptedIOException; -import java.net.SocketTimeoutException; -import java.util.LinkedList; -import java.util.Queue; - - -/** - * Provides the stream data source for JxtaSocket. - * - * @author Athomas Goldberg - */ -class JxtaSocketInputStream extends InputStream { - - /** - * We push this "poison" value into the accept backlog queue in order to - * signal that the queue has been closed. - */ - protected static final MessageElement QUEUE_END = new StringMessageElement("Terminal", "Terminal", null); - - /** - * Our read timeout. - */ - private long timeout = 60 * 1000; - - /** - * The associated socket. - */ - private final JxtaSocket socket; - - /** - * Our queue of message elements waiting to be read. - */ - protected final Queue queue; - - /** - * The maximum number of message elements we will allow in the queue. - */ - protected final int queueSize; - - /** - * The current message element input stream we are processing. - */ - private InputStream currentMsgStream = null; - - /** - * Construct an InputStream for a specified JxtaSocket. - * - * @param socket the JxtaSocket - * @param queueSize the queue size - */ - JxtaSocketInputStream(JxtaSocket socket, int queueSize) { - this.socket = socket; - this.queueSize = queueSize; - queue = new LinkedList(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int available() throws IOException { - int result; - InputStream in = getCurrentStream(false); - - if (in != null) { - result = in.available(); - } else { - // We chose not to block, if we have no inputstream then - // that means there are no bytes available. - result = 0; - } - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int read() throws IOException { - byte[] b = new byte[1]; - int result = 0; - - // The result of read() can be -1 (EOF), 0 (yes, its true) or 1. - while (0 == result) { - result = read(b, 0, 1); - } - - if (-1 != result) { - result = (int) b[0]; - } - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized int read(byte b[], int off, int len) throws IOException { - if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { - throw new IndexOutOfBoundsException(); - } - - while (true) { - int result = -1; - InputStream in = getCurrentStream(true); - - if (null == in) { - return -1; - } - - result = in.read(b, off, len); - if (0 == result) { - // Some streams annoyingly return 0 result. We won't - // perpetuate this behaviour. - continue; - } - - if (result == -1) { - closeCurrentStream(); - continue; - } - return result; - } - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void close() { - queue.clear(); - closeCurrentStream(); - queue.offer(QUEUE_END); - notify(); - } - - /** - * Rather than force the InputStream closed we add the EOF at the end of - * any current data. - */ - synchronized void softClose() { - queue.offer(QUEUE_END); - notify(); - } - - /** - * Get the input stream for the current segment and optionally block until - * a segment is available. - * - * @param block If {@code true} then block until a segment is available. - * @return the InputStream - * @throws IOException if an io error occurs - */ - private InputStream getCurrentStream(boolean block) throws IOException { - - if (currentMsgStream == null) { - - if (QUEUE_END == queue.peek()) { - // We are at the end of the queue. - return null; - } - - MessageElement me = null; - long pollUntil = (Long.MAX_VALUE == timeout) ? Long.MAX_VALUE : System.currentTimeMillis() + timeout; - - while (pollUntil >= System.currentTimeMillis()) { - try { - me = queue.poll(); - - if (null == me) { - long sleepFor = pollUntil - System.currentTimeMillis(); - - if (sleepFor > 0) { - wait(sleepFor); - } - } else { - break; - } - } catch (InterruptedException woken) { - InterruptedIOException incomplete = new InterruptedIOException("Interrupted waiting for data."); - - incomplete.initCause(woken); - incomplete.bytesTransferred = 0; - throw incomplete; - } - } - - if (block && (null == me)) { - throw new SocketTimeoutException("Socket timeout during read."); - } - - if (me != null) { - currentMsgStream = me.getStream(); - } - } - return currentMsgStream; - } - - private void closeCurrentStream() { - if (currentMsgStream != null) { - try { - currentMsgStream.close(); - } catch (IOException ignored) {// ignored - } - currentMsgStream = null; - } - } - - synchronized void enqueue(MessageElement element) { - if (queue.contains(QUEUE_END)) { - // We have already marked the end of the queue. - return; - } - if (queue.size() < queueSize) { - queue.offer(element); - } - notify(); - } - - /** - * Returns the timeout value for this socket. This is the amount of time in - * relative milliseconds which we will wait for read() operations to - * complete. - * - * @return The timeout value in milliseconds or 0 (zero) for - * infinite timeout. - */ - long getTimeout() { - if (timeout < Long.MAX_VALUE) { - return timeout; - } else { - return 0; - } - } - - /** - * Returns the timeout value for this socket. This is the amount of time in - * relative milliseconds which we will wait for read() operations to - * operations to complete. - * - * @param timeout The timeout value in milliseconds or 0 (zero) for - * infinite timeout. - */ - void setTimeout(long timeout) { - if (timeout < 0) { - throw new IllegalArgumentException("Negative timeout not allowed."); - } - - if (0 == timeout) { - timeout = Long.MAX_VALUE; - } - this.timeout = timeout; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocketOutputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocketOutputStream.java deleted file mode 100644 index 7ad728b8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/JxtaSocketOutputStream.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.socket; - - -import java.io.IOException; -import java.io.OutputStream; -import java.net.SocketException; - - -/** - * This class implements a buffered output stream. By setting up such an output - * stream, an application can write bytes to the underlying output stream - * without necessarily causing a call to the underlying system for each byte - * written. Data buffer is flushed to the underlying stream, when it is full, - * or an explicit call to flush is made. - */ -class JxtaSocketOutputStream extends OutputStream { - - /** - * If {@code true} then this socket is closed. - */ - protected boolean closed = false; - - /** - * Data buffer - */ - protected byte buf[]; - - /** - * byte count in buffer - */ - protected int count; - - /** - * JxtaSocket associated with this stream - */ - protected JxtaSocket socket; - - /** - * Constructor for the JxtaSocketOutputStream object - * - * @param socket JxtaSocket associated with this stream - * @param size buffer size in bytes - */ - public JxtaSocketOutputStream(JxtaSocket socket, int size) { - if (size <= 0) { - throw new IllegalArgumentException("Buffer size <= 0"); - } - buf = new byte[size]; - this.socket = socket; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void close() throws IOException { - flushBuffer(); - closed = true; - } - - /** - * Similar to close except that any buffered data is discarded. - */ - synchronized void hardClose() { - count = 0; - closed = true; - } - - /** - * Flush the internal buffer - * - * @throws IOException if an i/o error occurs - */ - private void flushBuffer() throws IOException { - if (count > 0) { - // send the message - socket.write(buf, 0, count); - count = 0; - } - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void write(int b) throws IOException { - - if (closed) { - throw new SocketException("Socket Closed."); - } - - if (count >= buf.length) { - flushBuffer(); - } - buf[count++] = (byte) b; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void write(byte b[], int off, int len) throws IOException { - int left = buf.length - count; - - if (closed) { - throw new SocketException("Socket Closed."); - } - - if (len > left) { - System.arraycopy(b, off, buf, count, left); - len -= left; - off += left; - count += left; - flushBuffer(); - } - - // chunk data if larger than buf.length - while (len >= buf.length) { - socket.write(b, off, buf.length); - len -= buf.length; - off += buf.length; - } - System.arraycopy(b, off, buf, count, len); - count += len; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void flush() throws IOException { - flushBuffer(); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/package.html deleted file mode 100644 index 63f1fc27..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/socket/package.html +++ /dev/null @@ -1,63 +0,0 @@ - - - - - -

      The socket package provides interface ala {@link java.net.Socket} -over JXTA pipes. Since the PipeService provides uni-directional, and -unreliable communication channels, the JxtaSocket employs it's own -protocol over pipes to establish bi-directional connections for every -request. In addition the JxtaSocket also employs the reliability -library to ensure reliable delivery of data.  Another feature of -JxtaSockets is chunking, which relieves applications from having to -worry about mtu size, just remember to invoke flush at the end of data -transmission
      -

      -


      -

      -

      JxtaSocket defines the following message elements employed during -the life cycle of a JxtaSocket :
      -

      -
      <> -<Cred>Credentials to determine trust</Cred>
      -<><reqPipe>requestor's -pipe advertisement</reqPipe>
      -<remPipe>Remote -pipe advertisement</remPipe>
      -<reqPeer>Remote -peer advertisement</remPeer>
      -<stream>true|false -== reliable|or not</stream>
      -<close>close request</close>
      -
      <closeACK>ack -close request</closeACK>
      -<data>data</data>
      -
      -

      The socket package also provides interface ala {@link -java.net.MulticastSocket} over propagated pipes.  Keep in mind -JxtaMulticastSocket does not provide chunking nor reliability at this -time, therefore one must consider configuration parameters such as the -multicast datagram size defined for the TCP Message Transport :
      -

      -
      <MulticastSize>
      -    16384
      -</MulticastSize>
      -
      -

      As well as any other mtu size imposed by the JXTA Platform, or the -operating system.
      -

      -

      For examples on how to utilize the net.jxta.socket see the online -tutorials on JxtaSocket, -and JxtaMulticastSocket -available at http://www.jxta.org/Tutorials.html
      -

      -


      -

      - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/user.properties b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/user.properties deleted file mode 100644 index 66d16b78..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/user.properties +++ /dev/null @@ -1,22 +0,0 @@ -# Amount of time in minutes after which a connection is considered idle and may -# be scavenged expressed in minutes -impl.endpoint.tls.connection.idletimeout=5 - -# Amount of time in minutes a connection must be idle before a reconnection -# attempt will be considered expressed in minutes -impl.endpoint.tls.connection.minidlereconnect=1 - -# Amount if time in minutes which retries may remain queued for retrasmission. -# expressed in minutes -impl.endpoint.tls.connection.maxretryage=2 - -# Cache Manager Deffered checkpoint -# a setting of true deffers commit checkpoint to the Filer -# this setting increases performance, with a caveat of possible -# data corruption in unexpected process termination due to kernel -# crash, or power loss -impl.cm.defferedcheckpoint=true - -#Discovery provides the ability to disable discovery network traffic -#when defined, it renders discovery a local cache -impl.discovery.localonly=false diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/AbstractSimpleSelectable.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/AbstractSimpleSelectable.java deleted file mode 100644 index 0714118b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/AbstractSimpleSelectable.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -import net.jxta.logging.Logging; -import net.jxta.util.SimpleSelectable.IdentityReference; - -/** - * This a tool to implement selectable objects. It may be composed or extended. - *

      - * {@code SimpleSelectable} objects that are not {@code SimpleSelector} objects - * only report changes to their listeners. - *

      - * The listeners of a {@code SimpleSelectable} may be {@code SimpleSelector} - * objects or other {@code SimpleSelectable} objects. However the method to - * register non-selectors is and must remain protected since it would allow the - * connection of arbitrary listeners. - * - * @see SimpleSelector - */ - -public abstract class AbstractSimpleSelectable implements SimpleSelectable { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(AbstractSimpleSelectable.class.getName()); - - /** - * The identity reference for this selectable. - * - * @see SimpleSelectable.IdentityReference - */ - public final IdentityReference identityReference = new IdentityReference(this); - - /** - * The object that is to reported to listeners as having changed. When this - * class is composed rather than extended, "this" is probably not the right - * choice. - */ - private final SimpleSelectable srcObject; - - /** - * Registered Change Listeners. - *

      - * We use a weakHashMap as a Set. The values are never used. - */ - private final Map myListeners = new WeakHashMap(2); - - /** - * Standard constructor for cases where the selectable object is this - * object. - */ - public AbstractSimpleSelectable() { - this.srcObject = this; - } - - /** - * Standard constructor for cases where the selectable object is some other - * object. - * - * @param srcObject the source object - */ - public AbstractSimpleSelectable(SimpleSelectable srcObject) { - this.srcObject = srcObject; - } - - /** - * {@inheritDoc} - */ - public IdentityReference getIdentityReference() { - return identityReference; - } - - /** - * Tells whether there are registered selectors right now, or not. A - * SimpleSelectable that also registers with something else may want to - * unregister (with the obvious consistency precautions) if it no longer has - * selectors of its own. - * - * @return true if there are listeners. - */ - protected boolean haveListeners() { - synchronized(myListeners) { - return !myListeners.isEmpty(); - } - } - - /** - * This method takes any listener, not just a SimpleSelector. - * - * @param selectable The SimpleSelectable to register - */ - protected void registerListener(SimpleSelectable selectable) { - synchronized(myListeners) { - myListeners.put(selectable, null); - } - } - - /** - * This method takes any listener, not just a SimpleSelector. - * - * @param selectable The SimpleSelectable to unregister - */ - protected void unregisterListener(SimpleSelectable selectable) { - synchronized(myListeners) { - myListeners.remove(selectable); - } - } - - /** - * {@inheritDoc} - */ - public void register(SimpleSelector simpleSelector) { - registerListener(simpleSelector); - simpleSelector.itemChanged(this); - } - - /** - * {@inheritDoc} - */ - public void unregister(SimpleSelector simpleSelector) { - unregisterListener(simpleSelector); - } - - /** - * This method tells us that something changed and so we need to notify our - * selectors by invoking their {@code itemChanged()} method. This is - * normally invoked internally by the implementation. One of the reasons for - * the implementation to invoke this method is that a SimpleSelectable - * object that this one is registered with has changed and so has invoked - * the itemChanged method. However, the correlation between the two is left - * up to the implementation. - *

      - * No external synchronization needed, nor desirable. - * - * @return false if there are no selectors left (that's a suggestion for the - * implementation to use haveListeners and possibly unregister itself). - */ - protected final boolean notifyChange() { - Collection listeners; - - synchronized(myListeners) { - listeners = new ArrayList(myListeners.keySet()); - } - - for (SimpleSelectable listener : listeners) { - try { - listener.itemChanged(srcObject); - } catch(Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in listener " + listener, all); - } - } - } - - return !listeners.isEmpty(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/AdvertisementUtilities.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/AdvertisementUtilities.java deleted file mode 100644 index 128c3e87..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/AdvertisementUtilities.java +++ /dev/null @@ -1,608 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.TextElement; -import net.jxta.exception.JxtaException; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.PipeID; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleClassAdvertisement; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.ModuleSpecAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeAdvertisement; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.StringReader; -import java.io.StringWriter; -import java.net.URI; -import java.net.URISyntaxException; - - -/** - * @deprecated Will be deprecated soon. Do not use these methods. They contain - * a number of incorrect assumption that cannot be corrected while maintaining - * backwards compatibility with programs which already use them. - * THIS CLASS IS SCHEDULED TO BE REMOVED AFTER 2.5 - */ -@Deprecated -public final class AdvertisementUtilities { - - /** - * Logger - */ - // private static final transient Logger LOG = Logger.getLogger(AdvertisementUtilities.class.getName()); - - public static final StructuredTextDocument STANDARD_COMPATABILITY = (StructuredTextDocument) StructuredDocumentFactory.newStructuredDocument( - MimeMediaType.XMLUTF8, "Comp"); - public static final String STANDARD_URI = "http://www.jxta.org/download/jxta.jar"; - public static final String STANDARD_PROVIDER = "jxta.org"; - - static { - Element element = STANDARD_COMPATABILITY.createElement("Efmt", "JDK1.4.1"); - - STANDARD_COMPATABILITY.appendChild(element); - element = STANDARD_COMPATABILITY.createElement("Bind", "V2.0 Ref Impl"); - STANDARD_COMPATABILITY.appendChild(element); - } - - private AdvertisementUtilities() {} - - /** - * Read a JXTA Advertisement from a File - * - * @param fileName The file containing the Advertisement - * @return An polymorphic Advertisement object - * @throws JxtaException if Unable to parse the Advertisement - */ - public static Advertisement readAdvertisementFromFile(String fileName) throws JxtaException { - return readAdvertisementFromFile(new File(fileName)); - } - - /** - * Read a JXTA Advertisement from a File - * - * @param file The file containing the Advertisement - * @return An polymorphic Advertisement object - * @throws JxtaException if Unable to parse the Advertisement - */ - public static Advertisement readAdvertisementFromFile(File file) throws JxtaException { - FileInputStream in = null; - - try { - in = new FileInputStream(file); - - return AdvertisementFactory.newAdvertisement(MimeMediaType.XML_DEFAULTENCODING, in); - } catch (IOException e) { - throw new JxtaException("Advertisement Load Failed: " + file, e); - } catch (Exception e) { - throw new JxtaException("Advertisement Load Failed: " + file, e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException ignored) {// ignored - } - } - } - } - - /** - * Save a JXTA Advertisement as an XML Document to a File - * - * @param adv The Advertisement to be saved - * @param fileName The file to store the Advertisement - * @throws JxtaException if Unable to parse the Advertisement - */ - public static void saveAdvertisementToFile(Advertisement adv, String fileName) throws JxtaException { - saveAdvertisementToFile(adv, new File(fileName)); - } - - /** - * Save a JXTA Advertisement as an XML Document to a File - * - * @param adv The Advertisement to be saved - * @param file The file to store the Advertisement - * @throws JxtaException if Unable to parse the Advertisement - */ - public static void saveAdvertisementToFile(Advertisement adv, File file) throws JxtaException { - OutputStream out = null; - - try { - out = new FileOutputStream(file); - Document document = adv.getDocument(MimeMediaType.XML_DEFAULTENCODING); - - document.sendToStream(out); - } catch (IOException e) {} finally { - if (out != null) { - try { - out.close(); - } catch (IOException ignored) {// ignored - } - } - } - } - - /** - * Save a JXTA Advertisement as an XML Document to an array of bytes - * - * @param advertisement The Advertisement to be saved - * @throws JxtaException if Unable to parse the Advertisement - * @deprecated This method should not be used because it produces a result - * who's encoding is not predictable and may (will) differ from JVM to JVM. - */ - @Deprecated - public static byte[] advertisementToBytes(Advertisement advertisement) throws JxtaException { - try { - Document document = advertisement.getDocument(MimeMediaType.XML_DEFAULTENCODING); - ByteArrayOutputStream bo = new ByteArrayOutputStream(); - - document.sendToStream(bo); - - return bo.toByteArray(); - } catch (IOException e) { - throw new JxtaException("Error converting a document to bytes", e); - } - } - - /** - * Convert an array of bytes containing an XML encoded String to an JXTA Advertisement - * - * @param buf The source of the advertisement - * @return The Advertisement - * @deprecated This method should not be used because it interprets the - * input using the local default encoding which is not predictable and - * may (will) differ from JVM to JVM. - */ - @Deprecated - public static Advertisement bytesToAdvertisement(byte buf[]) { - try { - InputStream in = new ByteArrayInputStream(buf); - Advertisement advertisement = AdvertisementFactory.newAdvertisement(MimeMediaType.XML_DEFAULTENCODING, in); - - return advertisement; - } catch (IOException e) { - return null; - } // This will never be thrown - } - - /** - * Save a JXTA Advertisement to a String - * - * @param advertisement The Advertisement to be converted - * @param mimeType Type of document to be created - */ - public static String advertisementToText(Advertisement advertisement, String mimeType) { - try { - StructuredTextDocument doc = (StructuredTextDocument) advertisement.getDocument(new MimeMediaType(mimeType)); - StringWriter stringWriter = new StringWriter(); - - doc.sendToWriter(stringWriter); - - return stringWriter.toString(); - } catch (IOException e) { - return null; - } // This will never be thrown - } - - /** - * Save a JXTA Advertisement to a Plain Text String - * - * @param advertisement The Advertisement to be converted - */ - public static String advertisementToPlainText(Advertisement advertisement) { - return advertisementToText(advertisement, MimeMediaType.TEXT_DEFAULTENCODING.toString()); - } - - /** - * Save a JXTA Advertisement to an XML String - * - * @param advertisement The Advertisement to be converted - * @deprecated Equivalent to Advertisement.toString() - */ - @Deprecated - public static String advertisementToXmlText(Advertisement advertisement) { - return advertisementToText(advertisement, MimeMediaType.XMLUTF8.toString()); - } - - /** - * Convert an array of bytes containing an XML encoded String to an JXTA Advertisement - * - * @param xmlTextAsBytes The source of the advertisement - * @return The Advertisement - * @throws JxtaException if Unable to parse the Advertisement - * @deprecated This method should not be used because it produces a result - * who's encoding is not predictable and may (will) differ from JVM to JVM. - */ - @Deprecated - public static Advertisement newAdvertisementFromXml(byte xmlTextAsBytes[]) throws JxtaException { - try { - return AdvertisementFactory.newAdvertisement(MimeMediaType.XML_DEFAULTENCODING - , - new ByteArrayInputStream(xmlTextAsBytes)); - } catch (Exception e) { - throw new JxtaException("Unable to create Advertisement from the provided XML", e); - } - } - - /** - * Convert a String containing an XML encoded String to an JXTA Advertisement - * - * @param xmlText The source of the advertisement - * @return The Advertisement - * @throws JxtaException if Unable to parse the Advertisement - * @deprecated This method should not be used because it interprets the - * input using the local default encoding which is not precidcatable and - * may (will) differ from JVM to JVM. - */ - @Deprecated - public static Advertisement newAdvertisementFromXml(String xmlText) throws JxtaException { - try { - return AdvertisementFactory.newAdvertisement(MimeMediaType.XML_DEFAULTENCODING, new StringReader(xmlText)); - } catch (Exception e) { - throw new JxtaException("Unable to create Advertisement from the provided XML", e); - } - } - - /** - * Create a Pipe Advertisement - * - * @return A new Pipe Advertisement - */ - public static PipeAdvertisement createPipeAdvertisement() { - return (PipeAdvertisement) AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType()); - } - - /** - * Create a Pipe Advertisement - * - * @param pipeId The pipe ID - * @param pipeType The type of the Pipe - * @return A new Pipe Advertisement - */ - public static PipeAdvertisement createPipeAdvertisement(PipeID pipeId, String pipeType) { - PipeAdvertisement pipeAdvertisement = (PipeAdvertisement) AdvertisementFactory.newAdvertisement( - PipeAdvertisement.getAdvertisementType()); - - pipeAdvertisement.setPipeID(pipeId); - pipeAdvertisement.setType(pipeType); - return pipeAdvertisement; - } - - /** - * Create a Pipe Advertisement - * - * @param pipeIdText The pipe ID - * @param pipeType The type of the Pipe - * @return A new Pipe Advertisement - */ - public static PipeAdvertisement createPipeAdvertisement(String pipeIdText, String pipeType) throws JxtaException { - PipeID pipeId; - - try { - pipeId = (PipeID) IDFactory.fromURI(new URI(pipeIdText)); - } catch (URISyntaxException failed) { - IllegalArgumentException failure = new IllegalArgumentException("Bad pipe id"); - - failure.initCause(failed); - - throw failure; - } - PipeAdvertisement pipeAdvertisement = (PipeAdvertisement) AdvertisementFactory.newAdvertisement( - PipeAdvertisement.getAdvertisementType()); - - pipeAdvertisement.setPipeID(pipeId); - pipeAdvertisement.setType(pipeType); - return pipeAdvertisement; - } - - /** - * Create a Pipe Advertisement - * - * @param root Element containing a Pipe Advertisement - * @return A new Pipe Advertisement - */ - public static PipeAdvertisement createPipeAdvertisement(Element root) { - TextElement pipeAdvElement = (TextElement) DocumentUtilities.getChild(root, PipeAdvertisement.getAdvertisementType()); - - if (pipeAdvElement == null) { - return null; - } - - return (PipeAdvertisement) AdvertisementFactory.newAdvertisement(pipeAdvElement); - } - - /** - * Create a Pipe Advertisement - * - * @param peerGroup The peerGroup - * @param pipeType The pipeType - * @return A new Pipe Advertisement - */ - public static PipeAdvertisement createPipeAdvertisement(PeerGroup peerGroup, String pipeType) { - PipeID pipeID = IDFactory.newPipeID(peerGroup.getPeerGroupID()); - - return createPipeAdvertisement(pipeID, pipeType); - } - - /** - * Create a Pipe Advertisement - * - * @param pipeID The pipeID - * @param pipeType The pipeType - * @return A new Pipe Advertisement - */ - public static PipeAdvertisement createPipeAdvertisement(ID pipeID, String pipeType) { - PipeAdvertisement pipeAdvertisement = createPipeAdvertisement(); - - pipeAdvertisement.setPipeID(pipeID); - pipeAdvertisement.setType(pipeType); - return pipeAdvertisement; - } - - /** - * Create a Pipe Advertisement - * - * @param peerGroup The peerGroup - * @param pipeType The pipeType - * @param name The Pime Name - * @return A new Pipe Advertisement - */ - public static PipeAdvertisement createPipeAdvertisement(PeerGroup peerGroup, String sPipeID, String pipeType, String name) throws JxtaException { - PipeAdvertisement pipeAdvertisement = createPipeAdvertisement(peerGroup, pipeType); - PipeID pipeId; - - try { - pipeId = (PipeID) IDFactory.fromURI(new URI(sPipeID)); - } catch (URISyntaxException failed) { - IllegalArgumentException failure = new IllegalArgumentException("Bad pipe id"); - - failure.initCause(failed); - - throw failure; - } - pipeAdvertisement.setPipeID(pipeId); - if (name != null) { - pipeAdvertisement.setName(name); - } - - return pipeAdvertisement; - } - - /** - * Create a Pipe Advertisement - * - * @param root The Root element containing the Advertisement - * @return A new Pipe Advertisement - * @deprecated These utilities are too specialized for general use. - */ - @Deprecated - public static PipeAdvertisement getPipeAdvertisement(Element root) { - TextElement pipeAdvElement = (TextElement) DocumentUtilities.getChild(root, PipeAdvertisement.getAdvertisementType()); - - if (pipeAdvElement == null) { - return null; - } - - return (PipeAdvertisement) AdvertisementFactory.newAdvertisement(pipeAdvElement); - } - - /** - * Create a Peer Advertisement - * - * @param root The Root element containing the Advertisement - * @return A new Peer Advertisement - * @deprecated These utilities are too specialized for general use. - */ - @Deprecated - public static PeerAdvertisement getPeerAdvertisement(Element root) { - TextElement peerAdvElement = (TextElement) DocumentUtilities.getChild(root, PeerAdvertisement.getAdvertisementType()); - - if (peerAdvElement == null) { - return null; - } - - return (PeerAdvertisement) AdvertisementFactory.newAdvertisement(peerAdvElement); - } - - /** - * Create a ModuleClassAdvertisement - * - * @param name The name - * @param description The description - * @return An ModuleClassAdvertisement - */ - public static ModuleClassAdvertisement createModuleClassAdvertisement(String name, String description) { - String moduleClassAdvertisementType = ModuleClassAdvertisement.getAdvertisementType(); - ModuleClassAdvertisement moduleClassAdvertisement = (ModuleClassAdvertisement) AdvertisementFactory.newAdvertisement( - moduleClassAdvertisementType); - - moduleClassAdvertisement.setName(name); - moduleClassAdvertisement.setDescription(description); - - ModuleClassID mcID = IDFactory.newModuleClassID(); - - moduleClassAdvertisement.setModuleClassID(mcID); - return moduleClassAdvertisement; - } - - /** - * Create a ModuleSpecAdvertisement - * - * @param name The name - * @param param The param - * @return An ModuleSpecAdvertisement - * @deprecated This implementation incompletely initializes the module - * spec advertisement. Consider creating Module Spec Advertisements without - * this method. - */ - @Deprecated - public static ModuleSpecAdvertisement createModuleSpecAdvertisement(String name, StructuredDocument param) { - return createModuleSpecAdvertisement(name, null, param); - } - - /** - * Create a ModuleSpecAdvertisement - * - * @param name The name - * @param moduleClassAdvertisement The moduleClassAdvertisement - * @param param The param - * @return An ModuleSpecAdvertisement - * @deprecated This implementation incompletely initializes the module - * spec advertisement. Consider creating Module Spec Advertisements without - * this method. - */ - @Deprecated - public static ModuleSpecAdvertisement createModuleSpecAdvertisement(String name, ModuleClassAdvertisement moduleClassAdvertisement, StructuredDocument param) { - String moduleSpecAdvertisementType = ModuleSpecAdvertisement.getAdvertisementType(); - ModuleSpecAdvertisement moduleSpecAdvertisement = (ModuleSpecAdvertisement) AdvertisementFactory.newAdvertisement( - moduleSpecAdvertisementType); - - moduleSpecAdvertisement.setName(name); - moduleSpecAdvertisement.setVersion("Unknown"); - moduleSpecAdvertisement.setCreator("Unknown"); - - if (moduleClassAdvertisement != null) { - ModuleClassID moduleClassID = moduleClassAdvertisement.getModuleClassID(); - - moduleSpecAdvertisement.setModuleSpecID(IDFactory.newModuleSpecID(moduleClassID)); - } - - moduleSpecAdvertisement.setSpecURI("Unknown"); - - if (param != null) { - moduleSpecAdvertisement.setParam(param); - } - - return moduleSpecAdvertisement; - } - - /** - * Publish and advertisement to the Cache - * - * @param peerGroup The peerGroup - * @param peerAdvertisement The Advertisement - * @throws JxtaException if Unable to cache the Advertisement - */ - public static void cachePeerAdvertisement(PeerGroup peerGroup, PeerAdvertisement peerAdvertisement) throws JxtaException { - cachePeerAdvertisement(peerGroup, peerAdvertisement, DiscoveryService.DEFAULT_EXPIRATION - , - DiscoveryService.DEFAULT_EXPIRATION); - } - - private static void cachePeerAdvertisement(PeerGroup peerGroup, PeerAdvertisement peerAdvertisement, long lifetime, long lifetimeForOthers) throws JxtaException { - try { - DiscoveryService discoveryService = peerGroup.getDiscoveryService(); - - if (peerAdvertisement.getPeerID().equals(peerGroup.getPeerID())) { - return; - } // no reason to persist our own peer ID - - discoveryService.publish(peerAdvertisement, lifetime, lifetimeForOthers); - } catch (IOException e) { - throw new JxtaException("Unable to cache advertisement", e); - } - } - - /** - * Create a ModuleImplAdvertisement - * - * @param specID The specID - * @param code The code - * @param description the advertisement description - * @return An ModuleImplAdvertisement - * @deprecated This implementation initializes some fields of the - * resulting ModuleImplAdvertisement to constant values who's value may - * not be correct for all circumstances. Consider creating ModuleImpl - * Advertisements directly in your application. - */ - @Deprecated - public static ModuleImplAdvertisement createModuleImplAdvertisement(ModuleSpecID specID, String code, String description) { - - ModuleImplAdvertisement moduleImplAdvertisement = (ModuleImplAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleImplAdvertisement.getAdvertisementType()); - - moduleImplAdvertisement.setModuleSpecID(specID); - moduleImplAdvertisement.setCompat(STANDARD_COMPATABILITY); - moduleImplAdvertisement.setCode(code); - moduleImplAdvertisement.setUri(STANDARD_URI); - moduleImplAdvertisement.setProvider(STANDARD_PROVIDER); - moduleImplAdvertisement.setDescription(description); - return moduleImplAdvertisement; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/AwtUtils.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/AwtUtils.java deleted file mode 100644 index 9d9171f9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/AwtUtils.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.awt.Frame; - - -public class AwtUtils { - - // It is recommended to invoke this method at least once before - // making any other references to awt. This will force awt threads - // to always be daemon threads, thereby preserving the JVM's automatic - // termination model. - - public static void initAsDaemon() { - (new Thread() { - - @Override - public void run() { - try { - Frame f = new Frame(); - - f.dispose(); - } catch (Throwable t) {} - } - - public void doit() { - setDaemon(true); - setName("awt daemon initializer"); - start(); - try { - join(); - } catch (InterruptedException ie) {} - } - } - ).doit(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/ClassFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/ClassFactory.java deleted file mode 100644 index 7d6057f6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/ClassFactory.java +++ /dev/null @@ -1,367 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URI; -import java.net.URL; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.ResourceBundle; -import java.util.logging.Level; -import java.util.logging.Logger; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.List; -import java.util.MissingResourceException; -import java.util.NoSuchElementException; - -import net.jxta.logging.Logging; - - -/** - * This util class provides methods needed by class construction factories. - * - * @see net.jxta.document.StructuredDocumentFactory - * @see net.jxta.document.AdvertisementFactory - * @see net.jxta.id.IDFactory - * @see net.jxta.endpoint.WireFormatMessageFactory - */ -public abstract class ClassFactory { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(ClassFactory.class.getName()); - - /** - * Standard constructor. - */ - protected ClassFactory() {} - - /** - * Used by ClassFactory methods to get the mapping of keys to constructors. - * - * @return the map containing the mappings. - */ - protected abstract Map getAssocTable(); - - /** - * Used by ClassFactory methods to ensure that all keys used with the - * mapping are of the correct type. - * - * @return Class object of the key type. - */ - protected abstract Class getClassForKey(); - - /** - * Return all of the available keys for this factory. - * - * @return Iterator of all the available keys for this factory. - */ - public Iterator getAvailableKeys() { - return Collections.unmodifiableSet(getAssocTable().keySet()).iterator(); - } - - /** - * Returns an unmodifiable Set containing all of the associations - * stored in this ClassFactory. - * - * @return Set containing all of the available entries for this factory. - */ - public Set> getEntrySet() { - return Collections.unmodifiableSet(getAssocTable().entrySet()); - } - - /** - * Used by ClassFactory methods to ensure that all of the instance classes - * which register with this factory have the correct base class - * - * @return Class object of the "Factory" type. - */ - protected abstract Class getClassOfInstantiators(); - - /** - * Given a resource bundle identifier and a property name register instance - * classes. The property must be a string containing class names which must - * be found on the current class path. The class names are separated by - * spaces. - * - * @param resourceName name of the resource bundle - * @param propertyName name of the property. - * @return boolean true if at least one instance class could be registered - * with this factory. - * @exception MissingResourceException if the resource bundle or - * property cannot be located. - */ - protected boolean registerFromResources(String resourceName, String propertyName) throws MissingResourceException { - ResourceBundle jxtaRsrcs = ResourceBundle.getBundle(resourceName); - String fromProps = jxtaRsrcs.getString(propertyName).trim(); - - return registerFromString(fromProps); - } - - /** - * Register instance classes given a string containing class names which - * must be found on the current class path. The class names are separated - * by spaces. - * - * @param classNamesString The class name list - * @return boolean true if at least one of the instance classes could be - * registered otherwise false. - */ - protected boolean registerFromString(String classNamesString) { - boolean registeredSomething = false; - - if ((null == classNamesString) || (0 == classNamesString.length())) { - return false; - } - - // make sure the static initialisers for each instance class are called. - List instanceClasses = Arrays.asList(classNamesString.split("\\s")); - - for (String eachInstanceClass : instanceClasses) { - try { - registeredSomething |= registerAssoc(eachInstanceClass); - } catch (Exception allElse) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to register \'" + eachInstanceClass + "\'", allElse); - } - } - } - - return registeredSomething; - } - - /** - * Given an provider interface name register instance classes. The class - * path is searched for service provider lists as described by the JAR File - * specification for service providers - * - * @param interfaceName name of the implemented interface. - * @return boolean true if at least one instance class could be registered - * with this factory. - */ - protected boolean registerProviders(String interfaceName) { - ClassLoader loader = getClass().getClassLoader(); - boolean registeredSomething = false; - - try { - Enumeration providerLists = loader.getResources("META-INF/services/" + interfaceName); - - while (providerLists.hasMoreElements()) { - try { - URI providerList = providerLists.nextElement().toURI(); - - registeredSomething |= registerFromFile(providerList); - } catch (URISyntaxException badURI) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to convert service URI", badURI); - } - } - } - } catch (IOException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to locate provider lists", ex); - } - } - - return registeredSomething; - } - - /** - * Register instance classes given a URI to a file containing class names - * which must be found on the current class path. The class names are listed - * on separate lines. Comments are marked with a '#', the pound sign and - * any following text on any line in the file are ignored. - * - * @param providerList the URI to a file containing a list of providers - * @return boolean true if at least one of the instance classes could be - * registered otherwise false. - */ - protected boolean registerFromFile(URI providerList) { - boolean registeredSomething = false; - InputStream urlStream = null; - - try { - urlStream = providerList.toURL().openStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream, "UTF-8")); - - String provider; - - while ((provider = reader.readLine()) != null) { - int comment = provider.indexOf('#'); - - if (comment != -1) { - provider = provider.substring(0, comment); - } - - provider = provider.trim(); - - if (provider.length() > 0) { - try { - registeredSomething |= registerAssoc(provider); - } catch (Exception allElse) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to register \'" + provider + "\'", allElse); - } - } - } - } - } catch (IOException ex) { - LOG.log(Level.WARNING, "Failed to read provider list " + providerList, ex); - return false; - } finally { - if(null != urlStream) { - try { - urlStream.close(); - } catch(IOException ignored) { - - } - } - } - - return registeredSomething; - } - - /** - * Register a class with the factory from its class name. Since class name - * doesn't tell us much, we just load the class and hope that something - * happens as a result of the class loading. This class is often overridden - * in class factories to interogate the instance class before registering - * the instance class. - * - * @param className The class name which will be registered. - * @return boolean true if the class was registered otherwise false. - * @throws Exception when an error occurs. - */ - protected boolean registerAssoc(final String className) throws Exception { - - boolean registeredSomething = false; - - try { - /* - * This implementation skankily assumes that the class registers - * itself as part of class initialization. - */ - - Class ignored = Class.forName(className); - - registeredSomething = true; - } catch (ClassNotFoundException ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed to locate \'" + className + "\'"); - } - } catch (NoClassDefFoundError ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed to locate \'" + className + "\'"); - } - } - - return registeredSomething; - } - - /** - * Register a key and instance class with the factory. - * - * @param key The key to register. - * @param instantiator The instantiator object which will be registered for this key. - * @return boolean true if the key was successfully registered otherwise false. - */ - protected boolean registerAssoc(final K key, final I instantiator) { - - // Check the association table to make sure this key is not already present. - if (null != getAssocTable().get(key)) { - return false; - } - - getAssocTable().put(key, instantiator); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Factory : " + getClass().getName() + " Registered instantiator \'" + instantiator + "\' for \'" + key + "\'"); - } - - return true; - } - - /** - * Return the instantiator associated with the provided key. - * - * @param key The identifier for the Instantiator class to be returned. - * @return Instantiator Instantiator matching the provided key - * @throws NoSuchElementException if the key has not been registered. - */ - protected I getInstantiator(final K key) throws NoSuchElementException { - - // Get the constructors for this key. - I instantiator = getAssocTable().get(key); - - if (null == instantiator) { - throw new NoSuchElementException("key '" + key + "' not registered."); - } - - return instantiator; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/CountingInputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/CountingInputStream.java deleted file mode 100644 index 41ffcd2e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/CountingInputStream.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.*; - - -/** - * A filter input stream which counts the bytes read from the stream. A filter - * so that you don't have to count seperately from reading from the inoput - * - **/ -public class CountingInputStream extends FilterInputStream { - - /** - * For recursion detection to prevent overcounting. - **/ - private transient boolean alreadycounting; - - /** - * number of bytes which have been read on this stream - **/ - private long bytesRead = 0; - - /** - * Make a new Counting Input Stream - **/ - public CountingInputStream(InputStream in) { - super(in); - } - - /** - * {@inheritDoc} - * - *

      Debugging toString. - **/ - @Override - public String toString() { - if (null == in) { - return "closed/" + super.toString(); - } else { - return in.toString() + "/" + super.toString(); - } - } - - /** - * {@inheritDoc} - * - *

      Merely calls the super version. - **/ - @Override - public synchronized int read() throws IOException { - boolean wascounting = alreadycounting; - - alreadycounting = true; - int i = super.read(); - - alreadycounting = wascounting; - - if (!alreadycounting && (i != -1)) { - bytesRead++; - } - return i; - } - - /** - * {@inheritDoc} - * - *

      calls the super version of the same method. - **/ - @Override - public synchronized int read(byte[] b, int off, int len) throws IOException { - boolean wascounting = alreadycounting; - - alreadycounting = true; - - int i = super.read(b, off, len); - - alreadycounting = wascounting; - - if ((-1 != i) && !alreadycounting) { - bytesRead += i; - } - - return i; - } - - /** - * Returns the number of bytes read fromthe stream thus far. This and all - * the methods in this class are synchronized because bytesRead cannot be - * volatile. - * - * @return long containing the number of bytes read. - **/ - public synchronized long getBytesRead() { - return bytesRead; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/CountingOutputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/CountingOutputStream.java deleted file mode 100644 index f1b121d2..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/CountingOutputStream.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.OutputStream; -import java.io.IOException; - - -/** - * A filter output stream which counts the bytes sent to the stream. A filter - * so that you don't have to count seperately from writing to the output - * - **/ -public class CountingOutputStream extends java.io.FilterOutputStream { - - /** - * For recursion detection to prevent overcounting. - **/ - private transient boolean alreadycounting; - - /** - * number of bytes which have been written on this stream - **/ - private long bytesWritten; - - /** - * Creates a new instance of CountingOutputStream - **/ - public CountingOutputStream(OutputStream out) { - super(out); - bytesWritten = 0; - alreadycounting = false; - } - - /** - * {@inheritDoc} - * - *

      Debugging toString. - **/ - @Override - public String toString() { - if (null == out) { - return "closed/" + super.toString(); - } else { - return out.toString() + "/" + super.toString(); - } - } - - /** - * {@inheritDoc} - * - *

      Merely calls the super version. - **/ - @Override - public synchronized void write(int b) throws IOException { - boolean wascounting = alreadycounting; - - alreadycounting = true; - super.write(b); - alreadycounting = wascounting; - if (!alreadycounting) { - bytesWritten++; - } - } - - /** - * {@inheritDoc} - * - *

      calls the super version of the same method. - **/ - @Override - public synchronized void write(byte[] b, int off, int len) throws IOException { - boolean wascounting = alreadycounting; - - alreadycounting = true; - super.write(b, off, len); - alreadycounting = wascounting; - if (!alreadycounting) { - bytesWritten += len; - } - } - - /** - * Returns the number of bytes written to the stream thus far. This and all - * the methods in this class are synchronized because bytesWritten cannot be - * volatile. - * - * @return long containing the number of bytes written. - **/ - public synchronized long getBytesWritten() { - return bytesWritten; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/CountingWriter.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/CountingWriter.java deleted file mode 100644 index 6321ff5a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/CountingWriter.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.Writer; -import java.io.FilterWriter; - -import java.io.IOException; - - -/** - * A filter writer which counts the characters sent to the writer. A filter - * so that you don't have to count seperately from writing to the output. - **/ -public class CountingWriter extends FilterWriter { - - /** - * For recursion detection to prevent overcounting. - **/ - private transient boolean alreadycounting; - - /** - * number of chars which have been written on this stream - **/ - private long charsWritten; - - /** - * Creates a new instance of CountingWriter - **/ - public CountingWriter(Writer out) { - super(out); - charsWritten = 0; - alreadycounting = false; - } - - /** - * {@inheritDoc} - * - *

      Debugging toString. - **/ - @Override - public String toString() { - if (null == out) { - return "closed/" + super.toString(); - } else { - return out.toString() + "/" + super.toString(); - } - } - - /** - * {@inheritDoc} - * - *

      Calls the super version of the same method. - **/ - @Override - public synchronized void write(int b) throws IOException { - boolean wascounting = alreadycounting; - - alreadycounting = true; - super.write(b); - alreadycounting = wascounting; - if (!alreadycounting) { - charsWritten++; - } - } - - /** - * {@inheritDoc} - * - *

      Calls the super version of the same method. - **/ - @Override - public synchronized void write(char[] b, int off, int len) throws IOException { - boolean wascounting = alreadycounting; - - alreadycounting = true; - super.write(b, off, len); - alreadycounting = wascounting; - if (!alreadycounting) { - charsWritten += len; - } - } - - /** - * Returns the number of chars written to the stream thus far. This and all - * the methods in this class are synchronized because bytesWritten cannot be - * volatile. - * - * @return long containing the number of bytes written. - **/ - public synchronized long getCharsWritten() { - return charsWritten; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/DevNullOutputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/DevNullOutputStream.java deleted file mode 100644 index ca927c5c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/DevNullOutputStream.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.OutputStream; - - -/** - * An OutputStream which simply discards all data written to it. Useful when - * used with CountingOutputStream. - * - * This implementation just ignores everything you do it. - */ -public class DevNullOutputStream extends OutputStream { - - /** Creates a new instance of DevNullOutputStream */ - public DevNullOutputStream() {} - - /** - * {@inheritDoc} - * - *

      Does nothing.... - **/ - @Override - public void close() {} - - /** - * {@inheritDoc} - * - *

      Does nothing.... - **/ - @Override - public void flush() {} - - /** - * {@inheritDoc} - * - *

      Does nothing.... - **/ - @Override - public void write(byte b[]) {} - - /** - * {@inheritDoc} - * - *

      Does nothing.... - **/ - @Override - public void write(byte b[], int offset, int len) {} - - /** - * {@inheritDoc} - * - *

      Does nothing.... - **/ - @Override - public void write(int b) {} -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/DevNullWriter.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/DevNullWriter.java deleted file mode 100644 index 2f94f639..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/DevNullWriter.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.Writer; - - -/** - * An Writer which simply discards all data written to it. Useful when - * used with CountingWriter. - * - * This implementation just ignores everything you do it. - */ -public class DevNullWriter extends Writer { - - /** - * Creates a new instance of DevNullOutputStream - **/ - public DevNullWriter() { - ; - } - - /** - * {@inheritDoc} - * - *

      Does nothing.... - **/ - @Override - public void close() {} - - /** - * {@inheritDoc} - * - *

      Does nothing.... - **/ - @Override - public void flush() {} - - /** - * {@inheritDoc} - * - *

      Does nothing.... - **/ - @Override - public void write(char b[]) {} - - /** - * {@inheritDoc} - * - *

      Does nothing.... - **/ - @Override - public void write(char b[], int offset, int len) {} - - /** - * {@inheritDoc} - * - *

      Does nothing.... - **/ - @Override - public void write(String str, int offset, int len) {} -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/DocumentUtilities.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/DocumentUtilities.java deleted file mode 100644 index effe1f6e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/DocumentUtilities.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; -import net.jxta.exception.JxtaException; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.util.Enumeration; - - -/** - * @deprecated Will be removed soon. THIS CLASS IS SCHEDULED TO BE REMOVED AFTER 2.5 - */ -@Deprecated -public final class DocumentUtilities { - - private DocumentUtilities() {} - - public static StructuredTextDocument createStructuredXmlDocument(String rootTagName) throws JxtaException { - return (StructuredTextDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, rootTagName); - } - - public static StructuredTextDocument getStructuredXmlDocument(String buf) throws JxtaException { - try { - return (StructuredTextDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8 - , - new StringReader(buf)); - } catch (IOException e) { - throw new JxtaException("Error reading document", e); - } - } - - public static StructuredTextDocument getStructuredXmlDocument(byte buf[]) throws JxtaException { - return getStructuredXmlDocument(new ByteArrayInputStream(buf)); - } - - public static StructuredTextDocument getStructuredXmlDocument(InputStream in) throws JxtaException { - try { - return (StructuredTextDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, in); - } catch (IOException e) { - throw new JxtaException("Error reading document", e); - } - } - - public static StructuredDocument createParamDocument() { - return StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - } - - public static Element getChild(Element root, Object key) { - Enumeration e = root.getChildren(key); - - if (e == null) { - return null; - } - - return (Element) e.nextElement(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/IgnoreFlushFilterOutputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/IgnoreFlushFilterOutputStream.java deleted file mode 100644 index 962ff3b3..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/IgnoreFlushFilterOutputStream.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.OutputStream; -import java.io.IOException; - - -/** - * A filter output stream which ignores flush requests. - * - **/ -public class IgnoreFlushFilterOutputStream extends java.io.FilterOutputStream { - - /** Creates a new instance of CountingOutputStream */ - public IgnoreFlushFilterOutputStream(OutputStream out) { - super(out); - } - - @Override - public void flush() throws IOException {// do nothing - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/JxtaBiDiPipe.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/JxtaBiDiPipe.java deleted file mode 100644 index c6e2d584..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/JxtaBiDiPipe.java +++ /dev/null @@ -1,1284 +0,0 @@ -/* - * Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.util; - -import net.jxta.credential.Credential; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.ID; -import net.jxta.impl.endpoint.tcp.TcpMessenger; -import net.jxta.impl.util.pipe.reliable.Defs; -import net.jxta.impl.util.pipe.reliable.FixedFlowControl; -import net.jxta.impl.util.pipe.reliable.OutgoingMsgrAdaptor; -import net.jxta.impl.util.pipe.reliable.ReliableInputStream; -import net.jxta.impl.util.pipe.reliable.ReliableOutputStream; -import net.jxta.logging.Logging; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.OutputPipeEvent; -import net.jxta.pipe.OutputPipeListener; -import net.jxta.pipe.PipeID; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeAdvertisement; - -import java.io.IOException; -import java.io.InputStream; -import java.net.SocketTimeoutException; -import java.util.Collections; -import java.util.Iterator; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * JxtaBiDiPipe is a pair of UnicastPipe channels that implements a bidirectional pipe. - * By default, JxtaBiDiPipe operates in reliable mode, unless otherwise specified, - * in addition, messages must not exceed the Endpoint MTU size of 64K, exceed the - * MTU will lead to unexpected behavior. - *

      - * It highly recommended that an application message listener is specified, not doing so, may - * lead to message loss in the event the internal queue is overflowed. - *

      - * Sending messages vis {@link #sendMessage(Message)} from within a - * {@code PipeMsgListener} may result in a deadlock due to contention - * between the sending and receiving portions of BiDi pipes. - *

      - * JxtaBiDiPipe, whenever possible, will attempt to utilize direct tcp messengers, - * which leads to improved performance. - */ -public class JxtaBiDiPipe implements PipeMsgListener, OutputPipeListener, ReliableInputStream.MsgListener { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(JxtaBiDiPipe.class.getName()); - - private final static int MAXRETRYTIMEOUT = 120 * 1000; - private PipeAdvertisement remotePipeAdv; - private PeerAdvertisement remotePeerAdv; - protected int timeout = 15 * 1000; - protected int retryTimeout = 60 * 1000; - protected int maxRetryTimeout = MAXRETRYTIMEOUT; - protected int windowSize = 50; - - private ArrayBlockingQueue queue = new ArrayBlockingQueue(windowSize); - protected PeerGroup group; - protected PipeAdvertisement pipeAdv; - protected PipeAdvertisement myPipeAdv; - protected PipeService pipeSvc; - protected InputPipe inputPipe; - protected OutputPipe connectOutpipe; - protected Messenger msgr; - protected InputStream stream; - protected final Object closeLock = new Object(); - protected final Object acceptLock = new Object(); - protected final Object finalLock = new Object(); - protected boolean closed = false; - protected boolean bound = false; - protected boolean dequeued = false; - protected PipeMsgListener msgListener; - protected PipeEventListener eventListener; - protected PipeStateListener stateListener; - protected Credential credential = null; - protected boolean waiting; - - /** - * If {@code true} then we are using the underlying end-to-end ACK reliable - * layer to ensure that messages are received by the remote peer. - */ - protected boolean isReliable = false; - - protected ReliableInputStream ris = null; - protected ReliableOutputStream ros = null; - - /** - * If {@code true} then we are using a reliable direct messenger to the - * remote peer. We will assume that messages which are sent successfully - * will be received successfully. - */ - protected volatile boolean direct = false; - protected OutgoingMsgrAdaptor outgoing = null; - protected StructuredDocument credentialDoc = null; - - /** - * Pipe close Event - */ - public static final int PIPE_CLOSED_EVENT = 1; - - /** - * Creates a bidirectional pipe - * - * @param group group context - * @param msgr lightweight output pipe - * @param pipe PipeAdvertisement - * @param isReliable Whether the connection is reliable or not - * @param credDoc Credential StructuredDocument - * @param direct indicates a direct messenger pipe - * @throws IOException if an io error occurs - */ - protected JxtaBiDiPipe(PeerGroup group, Messenger msgr, PipeAdvertisement pipe, StructuredDocument credDoc, boolean isReliable, boolean direct) throws IOException { - if (msgr == null) { - throw new IOException("Null Messenger"); - } - this.direct = direct; - this.group = group; - this.pipeAdv = pipe; - this.credentialDoc = credDoc != null ? credDoc : getCredDoc(group); - this.pipeSvc = group.getPipeService(); - this.inputPipe = pipeSvc.createInputPipe(pipe, this); - this.msgr = msgr; - this.isReliable = isReliable; - if (!direct) { - createRLib(); - } - setBound(); - } - - /** - * Creates a new object with a default timeout of #timeout, and no reliability. - * - */ - public JxtaBiDiPipe() { - } - - /** - * Creates a bidirectional pipe. - * - * Attempts to create a bidirectional connection to remote peer within default - * timeout of #timeout. - * - * @param group group context - * @param pipeAd PipeAdvertisement - * @param msgListener application PipeMsgListener - * @throws IOException if an io error occurs - */ - public JxtaBiDiPipe(PeerGroup group, PipeAdvertisement pipeAd, PipeMsgListener msgListener) throws IOException { - connect(group, null, pipeAd, timeout, msgListener); - } - - /** - * Creates a bidirectional pipe. - * - * Attempts to create a bidirectional connection to remote peer within specified - * timeout of #timeout. - * - * @param group group context - * @param timeout The number of milliseconds within which the JxtaBiDiPipe must - * be successfully created. An exception will be thrown if the pipe - * cannot be created in the alotted time. A timeout value of {@code 0} - * (zero) specifies an infinite timeout. - * @param pipeAd PipeAdvertisement - * @param msgListener application PipeMsgListener - * @throws IOException if an io error occurs - */ - public JxtaBiDiPipe(PeerGroup group, PipeAdvertisement pipeAd, int timeout, PipeMsgListener msgListener) throws IOException { - connect(group, null, pipeAd, timeout, msgListener); - } - - /** - * attempts to create a bidirectional connection to remote peer - * - * @param group group context - * @param pipeAd PipeAdvertisement - * @param timeout The number of milliseconds within which the JxtaBiDiPipe must - * be successfully created. An exception will be thrown if the pipe - * cannot be created in the allotted time. A timeout value of {@code 0} - * (zero) specifies an infinite timeout. - * @param msgListener application PipeMsgListener - * @param reliable if true, the reliability is assumed - * @throws IOException if an io error occurs - */ - public JxtaBiDiPipe(PeerGroup group, PipeAdvertisement pipeAd, int timeout, PipeMsgListener msgListener, boolean reliable) throws IOException { - connect(group, null, pipeAd, timeout, msgListener, reliable); - } - - /** - * Connect to a JxtaServerPipe with default timeout - * - * @param group group context - * @param pipeAd PipeAdvertisement - * @throws IOException if an io error occurs - */ - public void connect(PeerGroup group, PipeAdvertisement pipeAd) throws IOException { - connect(group, pipeAd, timeout); - } - - /** - * Connects to a remote JxtaBiDiPipe - * - * @param group group context - * @param pipeAd PipeAdvertisement - * @param timeout timeout in ms, also reset object default timeout - * to that of timeout - * @throws IOException if an io error occurs - */ - public void connect(PeerGroup group, PipeAdvertisement pipeAd, int timeout) throws IOException { - connect(group, null, pipeAd, timeout, null); - } - - /** - * Connects to a remote JxtaServerPipe - * - * @param group group context - * @param peerid peer to connect to - * @param pipeAd PipeAdvertisement - * @param timeout timeout in ms, also reset object default timeout to that of timeout - * @param msgListener application PipeMsgListener - * @throws IOException if an io error occurs - */ - public void connect(PeerGroup group, PeerID peerid, PipeAdvertisement pipeAd, int timeout, PipeMsgListener msgListener) throws IOException { - connect(group, peerid, pipeAd, timeout, msgListener, isReliable); - } - - /** - * Connects to a remote JxtaServerPipe - * - * @param group group context - * @param peerid peer to connect to - * @param pipeAd PipeAdvertisement - * @param timeout timeout in ms, also reset object default timeout to that of timeout - * @param msgListener application PipeMsgListener - * @param reliable Reliable connection - * @throws IOException if an io error occurs - */ - public void connect(PeerGroup group, PeerID peerid, PipeAdvertisement pipeAd, int timeout, PipeMsgListener msgListener, boolean reliable) throws IOException { - if (isBound()) { - throw new IOException("Pipe already bound"); - } - if (timeout <= 0) { - throw new IllegalArgumentException("Invalid timeout :" + timeout); - } - - this.pipeAdv = pipeAd; - this.group = group; - this.msgListener = msgListener; - if (msgListener != null) { - dequeued = true; - } - this.isReliable = reliable; - pipeSvc = group.getPipeService(); - this.timeout = timeout; - myPipeAdv = JxtaServerPipe.newInputPipe(group, pipeAd); - this.inputPipe = pipeSvc.createInputPipe(myPipeAdv, this); - this.credentialDoc = credentialDoc != null ? credentialDoc : getCredDoc(group); - Message openMsg = createOpenMessage(group, myPipeAdv); - - // create the output pipe and send this message - if (peerid == null) { - pipeSvc.createOutputPipe(pipeAd, this); - } else { - pipeSvc.createOutputPipe(pipeAd, Collections.singleton(peerid), this); - } - try { - synchronized (acceptLock) { - // check connectOutpipe within lock to prevent a race with modification. - if (connectOutpipe == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Waiting for " + timeout + " msec"); - } - acceptLock.wait(timeout); - } - } - } catch (InterruptedException ie) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Interrupted", ie); - } - Thread.interrupted(); - IOException exp = new IOException("Interrupted"); - exp.initCause(ie); - throw exp; - } - if (connectOutpipe == null) { - throw new IOException("connection timeout"); - } - // send connect message - waiting = true; - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending a backchannel message"); - } - connectOutpipe.send(openMsg); - // wait for the second op - try { - synchronized (finalLock) { - if (waiting) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Waiting for " + timeout + " msec for back channel to be established"); - } - finalLock.wait(timeout); - // Need to check for creation - if (msgr == null) { - throw new IOException("connection timeout"); - } - } - } - } catch (InterruptedException ie) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Interrupted", ie); - } - Thread.interrupted(); - IOException exp = new IOException("Interrupted"); - exp.initCause(ie); - throw exp; - } - setBound(); - notifyListeners(PipeStateListener.PIPE_OPENED_EVENT); - } - - /** - * creates all the reliability objects - */ - private void createRLib() { - if (isReliable) { - if (outgoing == null) { - outgoing = new OutgoingMsgrAdaptor(msgr, retryTimeout); - } - if (ros == null) { - ros = new ReliableOutputStream(outgoing, new FixedFlowControl(windowSize)); - } - if (ris == null) { - ris = new ReliableInputStream(outgoing, retryTimeout, this); - } - } - } - - /** - * Toggles reliability - * - * @param reliable Toggles reliability to reliable - * @throws IOException if pipe is bound - */ - public void setReliable(boolean reliable) throws IOException { - if (isBound()) { - throw new IOException("Can not set reliability after pipe is bound"); - } - this.isReliable = reliable; - } - - /** - * Obtain the cred doc from the group object. - * - * @param group group context - * @return The credDoc value - */ - protected static StructuredDocument getCredDoc(PeerGroup group) { - try { - MembershipService membership = group.getMembershipService(); - Credential credential = membership.getDefaultCredential(); - - if (credential != null) { - return credential.getDocument(MimeMediaType.XMLUTF8); - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to get credential", e); - } - } - return null; - } - - /** - * get the remote credential doc - * - * @return Credential StructuredDocument - */ - public StructuredDocument getCredentialDoc() { - return credentialDoc; - } - - /** - * Sets the connection credential doc. - * If no credentials are set, the default group credential are used. - * - * @param doc Credential StructuredDocument - */ - public void setCredentialDoc(StructuredDocument doc) { - this.credentialDoc = doc; - } - - /** - * Creates a connection request message - * - * @param group group context - * @param pipeAd pipe advertisement - * @return the Message object - * @throws IOException if an io error occurs - */ - protected Message createOpenMessage(PeerGroup group, PipeAdvertisement pipeAd) throws IOException { - Message msg = new Message(); - PeerAdvertisement peerAdv = group.getPeerAdvertisement(); - - if (credentialDoc == null) { - credentialDoc = getCredDoc(group); - } - if (credentialDoc == null && pipeAd.getType().equals(PipeService.UnicastSecureType)) { - throw new IOException("No credentials established to initiate a secure connection"); - } - try { - if (credentialDoc != null) { - msg.addMessageElement(JxtaServerPipe.nameSpace, - new TextDocumentMessageElement(JxtaServerPipe.credTag, (XMLDocument) credentialDoc, null)); - } - msg.addMessageElement(JxtaServerPipe.nameSpace, - new TextDocumentMessageElement(JxtaServerPipe.reqPipeTag, - (XMLDocument) pipeAd.getDocument(MimeMediaType.XMLUTF8), null)); - - msg.addMessageElement(JxtaServerPipe.nameSpace, - new StringMessageElement(JxtaServerPipe.reliableTag, Boolean.toString(isReliable), null)); - - msg.addMessageElement(JxtaServerPipe.nameSpace, - new StringMessageElement(JxtaServerPipe.directSupportedTag, Boolean.toString(true), null)); - - msg.addMessageElement(JxtaServerPipe.nameSpace, - new TextDocumentMessageElement(JxtaServerPipe.remPeerTag, - (XMLDocument) peerAdv.getDocument(MimeMediaType.XMLUTF8), null)); - return msg; - } catch (Throwable t) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "error getting element stream", t); - } - return null; - } - } - - /** - * Sets the bound attribute of the JxtaServerPipe object - */ - void setBound() { - bound = true; - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Pipe Bound :true"); - } - } - - /** - * Returns the binding state of the JxtaServerPipe. - * - * @return true if the ServerSocket successfully bound to an address - */ - public boolean isBound() { - return bound; - } - - /** - * Returns an input stream for this socket. - * - * @return a stream for reading from this socket. - * @throws IOException if an I/O error occurs when creating the - * input stream. - */ - public InputPipe getInputPipe() throws IOException { - return inputPipe; - } - - /** - * Returns remote PeerAdvertisement - * - * @return remote PeerAdvertisement - */ - public PeerAdvertisement getRemotePeerAdvertisement() { - return remotePeerAdv; - } - - /** - * Returns remote PipeAdvertisement - * - * @return remote PipeAdvertisement - */ - public PipeAdvertisement getRemotePipeAdvertisement() { - return remotePipeAdv; - } - - /** - * Sets the remote PeerAdvertisement - * - * @param peer Remote PeerAdvertisement - */ - protected void setRemotePeerAdvertisement(PeerAdvertisement peer) { - this.remotePeerAdv = peer; - } - - /** - * Sets the remote PipeAdvertisement - * - * @param pipe PipeAdvertisement - */ - protected void setRemotePipeAdvertisement(PipeAdvertisement pipe) { - this.remotePipeAdv = pipe; - } - - /** - * Closes this pipe. - * - * @throws IOException if an I/O error occurs when closing this - * socket. - */ - public void close() throws IOException { - sendClose(); - closePipe(false); - bound = false; - } - - protected void closePipe(boolean fastClose) throws IOException { - // close both pipes - synchronized (closeLock) { - if (closed) { - return; - } - closed = true; - bound = false; - } - - if (!fastClose && isReliable && !direct) { - /* - * This implements linger! - */ - long quitAt = System.currentTimeMillis() + timeout; - while (true) { - //FIXME hamada this does not loop - if (ros == null || ros.getMaxAck() == ros.getSeqNumber()) { - // Nothing to worry about. - break; - } - - // By default wait forever. - long left = 0; - - // If timeout is not zero. Then compute the waiting time - // left. - if (timeout != 0) { - left = quitAt - System.currentTimeMillis(); - if (left < 0) { - // Too late - sendClose(); - throw new IOException("Close timeout"); - } - } - - try { - if (!ros.isQueueEmpty()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Waiting for Output stream queue event"); - } - ros.waitQueueEvent(left); - } - break; - } catch (InterruptedException ie) { - // give up, then. - throw new IOException("Close interrupted"); - } - } - - // We are initiating the close. We do not want to receive - // anything more. So we can close the ris right away. - ris.close(); - } - - if (isReliable && ros != null) { - ros.close(); - } - - // close the pipe - inputPipe.close(); - msgr.close(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Pipe close complete"); - } - notifyListeners(PIPE_CLOSED_EVENT); - } - - private void notifyListeners(int event) { - try { - if (eventListener != null) { - eventListener.pipeEvent(event); - } else if (stateListener != null) { - stateListener.stateEvent(this, event); - } - } catch (Throwable th) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "error during pipe event callback", th); - } - } - } - - /** - * Sets the inputPipe attribute of the JxtaBiDiPipe object - * - * @param inputPipe The new inputPipe value - */ - protected void setInputPipe(InputPipe inputPipe) { - this.inputPipe = inputPipe; - } - - /** - * {@inheritDoc} - */ - public void pipeMsgEvent(PipeMsgEvent event) { - Message message = event.getMessage(); - if (message == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Empty event"); - } - return; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Pipe message arrived"); - } - - MessageElement element; - if (!bound) { - // look for a remote pipe answer - element = message.getMessageElement(JxtaServerPipe.nameSpace, JxtaServerPipe.remPipeTag); - if (element != null) { - // connect response - try { - XMLDocument CredDoc = null; - XMLDocument remotePipeDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(element); - - remotePipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(remotePipeDoc); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Recevied a pipe Advertisement :" + remotePipeAdv.getName()); - } - - element = message.getMessageElement(JxtaServerPipe.nameSpace, JxtaServerPipe.remPeerTag); - if (element != null) { - XMLDocument remotePeerDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(element); - - remotePeerAdv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(remotePeerDoc); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Recevied an Peer Advertisement :" + remotePeerAdv.getName()); - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning(" BAD connect response"); - } - return; - } - - element = message.getMessageElement(JxtaServerPipe.nameSpace, JxtaServerPipe.credTag); - if (element != null) { - CredDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(element); - } - if (pipeAdv.getType().equals(PipeService.UnicastSecureType) && (CredDoc == null || !checkCred(CredDoc))) { - // we're done here - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Missing remote credential doc"); - } - return; - } - - element = message.getMessageElement(JxtaServerPipe.nameSpace, JxtaServerPipe.reliableTag); - if (element != null) { - isReliable = Boolean.valueOf(element.toString()); - } - - boolean directSupported = false; - element = message.getMessageElement(JxtaServerPipe.nameSpace, JxtaServerPipe.directSupportedTag); - if (element != null) { - directSupported = Boolean.valueOf(element.toString()); - } - - if (directSupported) { - msgr = getDirectMessenger(group, remotePipeAdv, remotePeerAdv); - if (msgr != null) { - this.direct = true; - } else { - msgr = lightweightOutputPipe(group, remotePipeAdv, remotePeerAdv); - } - } else { - msgr = lightweightOutputPipe(group, remotePipeAdv, remotePeerAdv); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Reliability set to :" + isReliable); - } - if (isReliable && !direct) { - createRLib(); - } - synchronized (finalLock) { - waiting = false; - finalLock.notifyAll(); - } - } catch (IOException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "failed to process response message", e); - } - } - return; - } - } - - if (isReliable && !direct) { - // let reliabilty deal with the message - receiveMessage(message); - return; - } - if (!hasClose(message)) { - push(event); - } - } - - private boolean hasClose(Message message) { - // look for close request - MessageElement element = message.getMessageElement(JxtaServerPipe.nameSpace, JxtaServerPipe.closeTag); - if (element != null) { - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Recevied a pipe close request, closing pipes"); - } - if (ros != null) { - ros.hardClose(); - } - closePipe(false); - } catch (IOException ie) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed during close", ie); - } - } - return true; - } - return false; - } - - private void receiveMessage(Message message) { - Iterator i = message.getMessageElements(Defs.NAMESPACE, Defs.MIME_TYPE_ACK); - - if (i.hasNext()) { - if (ros != null) { - ros.recv(message); - } - return; - } - - i = message.getMessageElements(Defs.NAMESPACE, Defs.MIME_TYPE_BLOCK); - if (i.hasNext()) { - - // It can happen that we receive messages for the input stream - // while we have not finished creating it. - try { - synchronized (finalLock) { - while (waiting) { - finalLock.wait(timeout); - } - } - } catch (InterruptedException ie) {// ignored - } - - if (ris != null) { - ris.recv(message); - } - } - } - - /** - * Gets the Maximum Retry Timeout of the reliability layer - * - * @return The maximum retry Timeout value - */ - public synchronized int getMaxRetryTimeout() { - return maxRetryTimeout; - } - - /** - * Gets the Maximum Retry Timeout of the reliability layer - * - * @param maxRetryTimeout The new maximum retry timeout value - * @throws IllegalArgumentException if maxRetryTimeout exceeds jxta platform maximum retry timeout - */ - public synchronized void setMaxRetryTimeout(int maxRetryTimeout) { - if (maxRetryTimeout <= 0 || maxRetryTimeout > MAXRETRYTIMEOUT) { - throw new IllegalArgumentException( - "Invalid Maximum retry timeout :" + maxRetryTimeout + " Exceed Global maximum retry timeout :" - + MAXRETRYTIMEOUT); - } - this.maxRetryTimeout = maxRetryTimeout; - } - - /** - * Gets the Retry Timeout of the reliability layer - * - * @return The retry Timeout value - */ - public synchronized int getRetryTimeout() { - return retryTimeout; - } - - /** - * Sets the Retry Timeout of the underlying reliability layer - * . - * In reliable mode it is possible for this call to block - * trying to obtain a lock on reliable input stream - * - * @param retryTimeout The new retry timeout value - * @throws IOException if an I/O error occurs - */ - public synchronized void setRetryTimeout(int retryTimeout) throws IOException { - if (timeout <= 0) { - throw new IllegalArgumentException("Invalid Socket timeout :" + retryTimeout); - } - this.retryTimeout = retryTimeout; - if (outgoing != null) { - outgoing.setTimeout(retryTimeout); - } - } - - /** - * When in reliable mode, gets the Reliable library window size - * - * @return The windowSize value - */ - public synchronized int getWindowSize() { - return windowSize; - } - - /** - * When in reliable mode, sets the Reliable library window size - * - * @param windowSize The new window size value - * @throws IOException if an I/O error occurs - */ - public synchronized void setWindowSize(int windowSize) throws IOException { - if (isBound()) { - throw new IOException("Socket bound. Can not change the window size"); - } - this.windowSize = windowSize; - } - - /** - * This method is invoked by the Reliablity library for each incoming data message - * - * @param message Incoming message - */ - public void processIncomingMessage(Message message) { - if (!hasClose(message)) { - PipeMsgEvent event = new PipeMsgEvent(this, message, (PipeID) inputPipe.getPipeID()); - push(event); - } - } - - private void push(PipeMsgEvent event) { - if (msgListener == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("push message onto queue"); - } - queue.offer(event); - } else { - dequeue(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("calling message listener"); - } - msgListener.pipeMsgEvent(event); - } - - } - - /** - * Send a message - *

      - * Messenger - * - * @param msg Message to send to the remote side - * @return true if message was successfully enqueued - * @throws IOException if the underlying messenger breaks, either due to - * a physical address change, reliability issue. - * @see net.jxta.endpoint.Message - */ - public boolean sendMessage(Message msg) throws IOException { - if (isReliable && !direct) { - int seqn = ros.send(msg); - return (seqn > 0); - } else { - try { - if (msgr instanceof TcpMessenger) { - ((TcpMessenger) msgr).sendMessageDirect(msg, null, null, true); - return true; - } else { - return msgr.sendMessage(msg, null, null); - } - } catch (SocketTimeoutException io) { - if (msgr instanceof TcpMessenger) { - ((TcpMessenger) msgr).sendMessageDirect(msg, null, null, true); - return true; - } else { - return msgr.sendMessage(msg, null, null); - } - } catch (IOException io) { - closePipe(true); - IOException exp = new IOException("IO error occured during sendMessage()"); - exp.initCause(io); - throw exp; - - } - } - } - - private void dequeue() { - if (!dequeued && (null != msgListener)) { - while (queue != null && !queue.isEmpty()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("dequeing messages onto message listener"); - } - try { - msgListener.pipeMsgEvent(queue.take()); - } catch (InterruptedException e) { - //ignored - } - } - dequeued = false; - } - } - - /** - * {@inheritDoc} - */ - public void outputPipeEvent(OutputPipeEvent event) { - OutputPipe op = event.getOutputPipe(); - - if (op.getAdvertisement() == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("The output pipe has no internal pipe advertisement. Continueing anyway."); - } - } - if (op.getAdvertisement() == null || pipeAdv.equals(op.getAdvertisement())) { - synchronized (acceptLock) { - // modify op within lock to prevent a race with the if. - if (connectOutpipe == null) { - connectOutpipe = op; - // set to null to avoid closure - op = null; - } - acceptLock.notifyAll(); - } - // Ooops one too many, we were too fast re-trying. - if (op != null) { - op.close(); - } - - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unexpected OutputPipe :" + op); - } - } - } - - /** - * A lightweight direct messenger output pipe constructor, note the return type - * Since all the info needed is available, there's no need for to - * use the pipe service to resolve the pipe we have all we need - * to construct a messenger. - * - * @param group group context - * @param pipeAdv Remote Pipe Advertisement - * @param peer Remote Peer advertisement - * @return Messenger - */ - protected static Messenger getDirectMessenger(PeerGroup group, PipeAdvertisement pipeAdv, PeerAdvertisement peer) { - // Get an endpoint messenger to that address - if (pipeAdv.getType().equals(PipeService.PropagateType)) { - throw new IllegalArgumentException("Invalid pipe type " + pipeAdv.getType()); - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Creating a Direct Messenger"); - } - - if (pipeAdv.getType().equals(PipeService.UnicastType)) { - EndpointService endpoint = group.getEndpointService(); - EndpointAddress pipeEndpoint = new EndpointAddress("jxta", - (peer.getPeerID().getUniqueValue()).toString(), - "PipeService", - pipeAdv.getPipeID().toString()); - return endpoint.getDirectMessenger(pipeEndpoint, peer, true); - } - return null; - } - - /** - * A lightweight output pipe constructor, note the return type - * Since all the info needed is available, there's no need for to - * use the pipe service to resolve the pipe we have all we need - * to construct a messenger. - * - * @param group group context - * @param pipeAdv Remote Pipe Advertisement - * @param peer Remote Peer advertisement - * @return Messenger - */ - protected static Messenger lightweightOutputPipe(PeerGroup group, PipeAdvertisement pipeAdv, PeerAdvertisement peer) { - - EndpointService endpoint = group.getEndpointService(); - ID opId = pipeAdv.getPipeID(); - String destPeer = (peer.getPeerID().getUniqueValue()).toString(); - - // Get an endpoint messenger to that address - EndpointAddress addr; - if (pipeAdv.getType().equals(PipeService.UnicastType)) { - addr = new EndpointAddress("jxta", destPeer, "PipeService", opId.toString()); - } else if (pipeAdv.getType().equals(PipeService.UnicastSecureType)) { - addr = new EndpointAddress("jxtatls", destPeer, "PipeService", opId.toString()); - } else { - // not a supported type - return null; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Creating a lightweightOutputPipe()"); - } - return endpoint.getMessenger(addr); - } - - /** - * Not implemented yet - * - * @param cred the credential document - * @return always returns true - */ - protected boolean checkCred(StructuredDocument cred) { - // FIXME need to check credentials - return true; - } - - /** - * Send a close message to the remote side - */ - private void sendClose() { - if (!direct && isReliable && ros.isClosed()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("ReliableOutputStream is already closed. Skipping close message"); - } - return; - } - - Message msg = new Message(); - msg.addMessageElement(JxtaServerPipe.nameSpace, new StringMessageElement(JxtaServerPipe.closeTag, "close", null)); - try { - sendMessage(msg); - // ros will not take any new message, now. - if (!direct && ros != null) { - ros.close(); - } - } catch (IOException ie) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.SEVERE, "failed during close", ie); - } - } - } - - /** - * Returns the message listener for this pipe - * - * @return PipeMsgListener - * @deprecated use getMessageListener instead - */ - @Deprecated - public PipeMsgListener getListener() { - return getMessageListener(); - } - - /** - * Returns the message listener for this pipe - * - * @return PipeMsgListener - */ - public PipeMsgListener getMessageListener() { - return msgListener; - } - - /** - * Sets message listener for a pipe spawned by the JxtaServerPipe. - * There is a window where a message could arrive prior to listener being - * registered therefore a message queue is created to queue messages, once - * a listener is registered these messages will be dequeued by calling the - * listener until the queue is empty - * - * @param msgListener New value of property listener. - * @deprecated use setMessageListener instead - */ - @Deprecated - public void setListener(PipeMsgListener msgListener) { - setMessageListener(msgListener); - } - - /** - * Sets message listener for a pipe spawned by the JxtaServerPipe. - * There is a window where a message could arrive prior to listener being - * registered therefore a message queue is created to queue messages, once - * a listener is registered these messages will be dequeued by calling the - * listener until the queue is empty. - *

      - * Sending messages vis {@link #sendMessage(Message)} from within a - * {@code PipeMsgListener} may result in a deadlock due to contention - * between the sending and receiving portions of BiDi pipes. - * - * @param msgListener New value of property listener. - */ - public void setMessageListener(PipeMsgListener msgListener) { - this.msgListener = msgListener; - // if there are messages enqueued then dequeue them onto the msgListener - dequeue(); - } - - /** - * Sets a Pipe event listener, set listener to null to unset the listener - * - * @param eventListener New value of property listener. - * @deprecated use setPipeEventListener instead - */ - @Deprecated - public void setListener(PipeEventListener eventListener) { - setPipeEventListener(eventListener); - } - - /** - * Sets a Pipe event listener, set listener to null to unset the listener - * - * @param eventListener New value of property listener. - */ - public void setPipeEventListener(PipeEventListener eventListener) { - this.eventListener = eventListener; - } - - /** - * Returns the Pipe event listener for this pipe - * - * @return PipeMsgListener - */ - public PipeEventListener getPipeEventListener() { - return eventListener; - } - - /** - * Sets a Pipe state listener, set listener to null to unset the listener - * - * @param stateListener New value of property listener. - */ - public void setPipeStateListener(PipeStateListener stateListener) { - this.stateListener = stateListener; - } - - /** - * Returns the Pipe state listener for this pipe - * - * @return PipeMsgListener - */ - public PipeStateListener getPipeStateListener() { - return stateListener; - } - - /** - * Gets a message from the queue. If no Object is immediately available, - * then wait the specified amount of time for a message to be inserted. - * - * @param timeout Amount of time to wait in milliseconds for an object to - * be available. Per Java convention, a timeout of zero (0) means wait an - * infinite amount of time. Negative values mean do not wait at all. - * @return The next message in the queue. if a listener is registered calls - * to this method will return null - * @throws InterruptedException if the operation is interrupted before - * the timeout interval is completed. - */ - public Message getMessage(int timeout) throws InterruptedException { - if (queue == null || msgListener != null) { - return null; - } else { - PipeMsgEvent ev = queue.poll(timeout, TimeUnit.MILLISECONDS); - if (ev != null) { - return ev.getMessage(); - } else { - return null; - } - } - } - - /** - * Returns the Assigned PipeAdvertisement - * - * @return the Assigned PipeAdvertisement - */ - public PipeAdvertisement getPipeAdvertisement() { - return pipeAdv; - } - - /** - * {@inheritDoc} - *

      - * Closes the JxtaBiDiPipe. - */ - @Override - protected synchronized void finalize() throws Throwable { - if (!closed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("JxtaBiDiPipe is being finalized without being previously closed. This is likely a users bug."); - } - close(); - } - super.finalize(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/JxtaServerPipe.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/JxtaServerPipe.java deleted file mode 100644 index 95c2ad77..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/JxtaServerPipe.java +++ /dev/null @@ -1,549 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.util; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.IDFactory; -import net.jxta.impl.endpoint.tcp.TcpMessenger; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeAdvertisement; - -import java.io.IOException; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * The server side of a JxtaBiDiPipe. The intent of this object is accept connection requests. - * JxtaServerPipe follows the same pattern as java.net.ServerSocket, without it no connection can be - * established. - * - */ -public class JxtaServerPipe implements PipeMsgListener { - - private static final Logger LOG = Logger.getLogger(JxtaServerPipe.class.getName()); - protected static final String nameSpace = "JXTABIP"; - protected static final String credTag = "Cred"; - protected static final String reqPipeTag = "reqPipe"; - protected static final String remPeerTag = "remPeer"; - protected static final String remPipeTag = "remPipe"; - protected static final String closeTag = "close"; - protected static final String reliableTag = "reliable"; - protected static final String directSupportedTag = "direct"; - private PeerGroup group; - private InputPipe serverPipe; - private PipeAdvertisement pipeadv; - private int backlog = 50; - private long timeout = 30 * 1000L; - private final Object closeLock = new Object(); - protected BlockingQueue connectionQueue = null; - private boolean bound = false; - private boolean closed = false; - protected StructuredDocument myCredentialDoc = null; - /** - * The exceutor service. - */ - private final ExecutorService executor; - - /** - * Default constructor for the JxtaServerPipe - *

      - * backlog default of 50 - *

      call to accept() for this ServerPipe will - * block for only this amount of time. If the timeout expires, - * a java.net.SocketTimeoutException is raised, though the ServerPipe is still valid. - *

      - * - * @param group JXTA PeerGroup - * @param pipeadv PipeAdvertisement on which pipe requests are accepted - * @throws IOException if an I/O error occurs - */ - public JxtaServerPipe(PeerGroup group, PipeAdvertisement pipeadv) throws IOException { - this(group, pipeadv, 50); - } - - /** - * Constructor for the JxtaServerPipe - * - * @param group JXTA PeerGroup - * @param pipeadv PipeAdvertisement on which pipe requests are accepted - * @param backlog the maximum length of the queue. - * @param timeout call to accept() for this ServerPipe will - * block for only this amount of time. If the timeout expires, - * a java.net.SocketTimeoutException is raised, though the ServerPipe is still valid. - * @throws IOException if an I/O error occurs - */ - public JxtaServerPipe(PeerGroup group, PipeAdvertisement pipeadv, int backlog, int timeout) throws IOException { - this(group, pipeadv, backlog); - this.timeout = timeout; - } - - /** - * Constructor for the JxtaServerPipe object - * - * @param group JXTA PeerGroup - * @param pipeadv PipeAdvertisement on which pipe requests are accepted - * @param backlog the maximum length of the queue. - * * @exception IOException if an I/O error occurs - * @throws IOException if an I/O error occurs - */ - public JxtaServerPipe(PeerGroup group, PipeAdvertisement pipeadv, int backlog) throws IOException { - this.group = group; - this.executor = Executors.newFixedThreadPool(3); - this.pipeadv = pipeadv; - this.backlog = backlog; - connectionQueue = new ArrayBlockingQueue(backlog); - PipeService pipeSvc = group.getPipeService(); - serverPipe = pipeSvc.createInputPipe(pipeadv, this); - setBound(); - } - - /** - * Binds the JxtaServerPipe to a specific pipe advertisement - * - * @param group JXTA PeerGroup - * @param pipeadv PipeAdvertisement on which pipe requests are accepted - * @throws IOException if an I/O error occurs - */ - public void bind(PeerGroup group, PipeAdvertisement pipeadv) throws IOException { - bind(group, pipeadv, backlog); - } - - /** - * Binds the JxtaServerPipe to a specific pipe advertisement - * - * @param group JXTA PeerGroup - * @param pipeadv PipeAdvertisement on which pipe requests are accepted - * @param backlog the maximum length of the queue. - * @throws IOException if an I/O error occurs - */ - public void bind(PeerGroup group, PipeAdvertisement pipeadv, int backlog) throws IOException { - this.backlog = backlog; - connectionQueue = new ArrayBlockingQueue(backlog); - this.group = group; - this.pipeadv = pipeadv; - PipeService pipeSvc = group.getPipeService(); - serverPipe = pipeSvc.createInputPipe(pipeadv, this); - setBound(); - } - - /** - * Listens for a connection to be made to this socket and accepts - * it. The method blocks until a connection is made. - * - * @return the connection accepted, null otherwise - * @throws IOException if an I/O error occurs - */ - public JxtaBiDiPipe accept() throws IOException { - if (isClosed()) { - throw new SocketException("JxtaServerPipe is closed"); - } - if (!isBound()) { - throw new SocketException("JxtaServerPipe is not bound yet"); - } - try { - JxtaBiDiPipe bidi = connectionQueue.poll(timeout, TimeUnit.MILLISECONDS); - if (bidi == null) { - throw new SocketTimeoutException("Timeout reached"); - } - return bidi; - } catch (InterruptedException ie) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Interrupted", ie); - } - throw new SocketException("interrupted"); - } - } - - /** - * Gets the group associated with this JxtaServerPipe - * - * @return The group value - */ - public PeerGroup getGroup() { - return group; - } - - /** - * Gets the PipeAdvertisement associated with this JxtaServerPipe - * - * @return The pipeAdv value - */ - public PipeAdvertisement getPipeAdv() { - return pipeadv; - } - - /** - * Closes this JxtaServerPipe (closes the underlying input pipe). - * - * @throws IOException if an I/O error occurs - */ - public void close() throws IOException { - synchronized (closeLock) { - if (isClosed()) { - return; - } - if (bound) { - // close all the pipe - serverPipe.close(); - connectionQueue.clear(); - executor.shutdownNow(); - bound = false; - } - closed = true; - } - } - - /** - * Sets the bound attribute of the JxtaServerPipe - */ - void setBound() { - bound = true; - } - - /** - * Gets the Timeout attribute of the JxtaServerPipe - * - * @return The soTimeout value - * @throws IOException if an I/O error occurs - */ - - public synchronized int getPipeTimeout() throws IOException { - if (isClosed()) { - throw new SocketException("Server Pipe is closed"); - } - if (timeout > Integer.MAX_VALUE) { - return 0; - } else { - return (int) timeout; - } - } - - /** - * Sets the Timeout attribute of the JxtaServerPipe a timeout of 0 blocks forever. - * - * @param timeout The new soTimeout value - * @throws SocketException if an I/O error occurs - */ - public synchronized void setPipeTimeout(int timeout) throws SocketException { - if (isClosed()) { - throw new SocketException("Server Pipe is closed"); - } - - if (timeout < 0) { - throw new IllegalArgumentException("Negative timeout values are not allowed."); - } - - if (0 == timeout) { - this.timeout = Long.MAX_VALUE; - } else { - this.timeout = (long) timeout; - } - } - - /** - * Returns the closed state of the JxtaServerPipe. - * - * @return true if the socket has been closed - */ - public boolean isClosed() { - synchronized (closeLock) { - return closed; - } - } - - /** - * Returns the binding state of the JxtaServerPipe. - * - * @return true if the ServerSocket successfully bound to an address - */ - public boolean isBound() { - return bound; - } - - /** - * {@inheritDoc} - */ - public void pipeMsgEvent(PipeMsgEvent event) { - Message message = event.getMessage(); - if (message == null) { - return; - } - ConnectionProcessor processor = new ConnectionProcessor(message); - executor.execute(processor); - } - - /** - * Method processMessage is the heart of this class. - *

      - * This takes new incoming connect messages and constructs the JxtaBiDiPipe - * to talk to the new client. - *

      - * The ResponseMessage is created and sent. - * - * @param msg The client connection request (assumed not null) - * @return JxtaBiDiPipe Which may be null if an error occurs. - */ - private JxtaBiDiPipe processMessage(Message msg) { - - PipeAdvertisement outputPipeAdv = null; - PeerAdvertisement peerAdv = null; - StructuredDocument credDoc = null; - try { - MessageElement el = msg.getMessageElement(nameSpace, credTag); - - if (el != null) { - credDoc = StructuredDocumentFactory.newStructuredDocument(el); - } - - el = msg.getMessageElement(nameSpace, reqPipeTag); - if (el != null) { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(el); - outputPipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(asDoc); - } - - el = msg.getMessageElement(nameSpace, remPeerTag); - if (el != null) { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(el); - peerAdv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(asDoc); - } - - el = msg.getMessageElement(nameSpace, reliableTag); - boolean isReliable = false; - if (el != null) { - isReliable = Boolean.valueOf((el.toString())); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Connection request [isReliable] :" + isReliable); - } - } - - el = msg.getMessageElement(nameSpace, directSupportedTag); - boolean directSupported = false; - if (el != null) { - directSupported = Boolean.valueOf((el.toString())); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Connection request [directSupported] :" + directSupported); - } - } - - Messenger msgr; - boolean direct = false; - if (directSupported) { - msgr = JxtaBiDiPipe.getDirectMessenger(group, outputPipeAdv, peerAdv); - if (msgr == null) { - msgr = JxtaBiDiPipe.lightweightOutputPipe(group, outputPipeAdv, peerAdv); - } else { - direct = true; - } - } else { - msgr = JxtaBiDiPipe.lightweightOutputPipe(group, outputPipeAdv, peerAdv); - } - - if (msgr != null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Reliability set to :" + isReliable); - } - PipeAdvertisement newpipe = newInputPipe(group, outputPipeAdv); - JxtaBiDiPipe pipe = new JxtaBiDiPipe(group, msgr, newpipe, credDoc, isReliable, direct); - - pipe.setRemotePeerAdvertisement(peerAdv); - pipe.setRemotePipeAdvertisement(outputPipeAdv); - sendResponseMessage(group, msgr, newpipe); - return pipe; - } - } catch (IOException e) { - // deal with the error - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "IOException occured", e); - } - } - return null; - } - - /** - * Method sendResponseMessage get the createResponseMessage and sends it. - * - * @param group the peer group - * @param msgr the remote node messenger - * @param pipeAd the pipe advertisement - * @throws IOException for failures sending the response message. - */ - protected void sendResponseMessage(PeerGroup group, Messenger msgr, PipeAdvertisement pipeAd) throws IOException { - - Message msg = new Message(); - PeerAdvertisement peerAdv = group.getPeerAdvertisement(); - - if (myCredentialDoc == null) { - myCredentialDoc = JxtaBiDiPipe.getCredDoc(group); - } - - if (myCredentialDoc != null) { - msg.addMessageElement(JxtaServerPipe.nameSpace, - new TextDocumentMessageElement(credTag, (XMLDocument) myCredentialDoc, null)); - } - - msg.addMessageElement(JxtaServerPipe.nameSpace, - new StringMessageElement(JxtaServerPipe.directSupportedTag, Boolean.toString(true), null)); - - msg.addMessageElement(JxtaServerPipe.nameSpace, - new TextDocumentMessageElement(remPipeTag, (XMLDocument) pipeAd.getDocument(MimeMediaType.XMLUTF8), null)); - - msg.addMessageElement(nameSpace, - new TextDocumentMessageElement(remPeerTag, (XMLDocument) peerAdv.getDocument(MimeMediaType.XMLUTF8), null)); - if (msgr instanceof TcpMessenger) { - ((TcpMessenger) msgr).sendMessageDirect(msg, null, null, true); - } else { - msgr.sendMessage(msg); - } - } - - /** - * Utility method newInputPipe is used to get new pipe advertisement (w/random pipe ID) from old one. - *

      - * Called by JxtaSocket to make pipe (name -> name.remote) for open message - *

      - * Called by JxtaServerSocket to make pipe (name.remote -> name.remote.remote) for response message - * - * @param group the peer group - * @param pipeadv to get the basename and type from - * @return PipeAdvertisement a new pipe advertisement - */ - protected static PipeAdvertisement newInputPipe(PeerGroup group, PipeAdvertisement pipeadv) { - PipeAdvertisement adv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType()); - adv.setPipeID(IDFactory.newPipeID(group.getPeerGroupID())); - adv.setName(pipeadv.getName()); - adv.setType(pipeadv.getType()); - return adv; - } - - /** - * get the credential doc - * - * @return Credential StructuredDocument - */ - public StructuredDocument getCredentialDoc() { - return myCredentialDoc; - } - - /** - * Sets the connection credential doc - * If no credentials are set, the default group credential will be used - * - * @param doc Credential StructuredDocument - */ - public void setCredentialDoc(StructuredDocument doc) { - this.myCredentialDoc = doc; - } - - /** - * {@inheritDoc} - *

      - * Closes the JxtaServerPipe. - */ - @Override - protected synchronized void finalize() throws Throwable { - if (!closed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("JxtaServerPipe is being finalized without being previously closed. This is likely a user's bug."); - } - } - close(); - super.finalize(); - } - /** - * A small class for processing individual messages. - */ - private class ConnectionProcessor implements Runnable { - - private Message message; - ConnectionProcessor(Message message) { - this.message = message; - } - - public void run() { - JxtaBiDiPipe bidi = processMessage(message); - // make sure we have a socket returning - if (bidi != null) { - try { - connectionQueue.offer(bidi, timeout, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - Thread.interrupted(); - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/LimitInputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/LimitInputStream.java deleted file mode 100644 index 8c738c75..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/LimitInputStream.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.ByteArrayInputStream; -import java.io.FilterInputStream; -import java.io.InputStream; - -import java.io.IOException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - - -/** - * Implements a bounds on the number of bytes which may be read from an - * InputStream. {link LimitInputStream.close() close()} does not close the - * underlying stream. - **/ -public class LimitInputStream extends FilterInputStream { - - /* - * Log4J Catagory - */ - private static final Logger LOG = Logger.getLogger(LimitInputStream.class.getName()); - - private transient long limit; - - private transient long read; - - private transient long mark; - - private transient boolean fatalUnderflow; - - private transient boolean alreadycounting; - - /** - * Creates a new instance of LimitInputStream - * - * @param in the stream which will be limited. - * @param limit the number of bytes which can be read from the stream. - **/ - public LimitInputStream(InputStream in, long limit) { - this(in, limit, false); - } - - /** - * Creates a new instance of LimitInputStream - * - * @param in the stream which will be limited. - * @param limit the number of bytes which can be read from the stream. - * @param underflowThrows if the underlying stream EOFs before limit then - * an IOException will be thrown. - **/ - public LimitInputStream(InputStream in, long limit, boolean underflowThrows) { - super(in); - this.limit = limit; - this.mark = -1; - this.read = 0; - this.fatalUnderflow = underflowThrows; - this.alreadycounting = false; - } - - /** - * {@inheritDoc} - * - *

      Debugging toString. - **/ - @Override - public String toString() { - if (null == in) { - return "closed/" + super.toString(); - } else { - if (in instanceof ByteArrayInputStream) { - // ByteArrayInputStream.toString() prints the entire stream! - return in.getClass().getName() + "@" + System.identityHashCode(in) + "/" + super.toString() + ":" + read + "-" - + limit; - } else { - return in.toString() + "/" + super.toString() + ":" + read + "-" + limit; - } - } - } - - /** - * Closes this input stream and releases any system resources - * associated with the stream. - *

      - * This method simply forgets the underlying stream. - * - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#in - */ - @Override - public void close() throws IOException { - in = null; - } - - /** - * Returns the number of bytes that can be read from this input - * stream without blocking. - *

      - * This method - * simply performs in.available(n) and - * returns the result. - * - * @return the number of bytes that can be read from the input stream - * without blocking. - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#in - */ - @Override - public int available() throws IOException { - if (null == in) { - throw new IOException("Stream has been closed."); - } - - return (int) Math.min(super.available(), (limit - read)); - } - - /** - * Marks the current position in this input stream. A subsequent - * call to the reset method repositions this stream at - * the last marked position so that subsequent reads re-read the same bytes. - *

      - * The readlimit argument tells this input stream to - * allow that many bytes to be read before the mark position gets - * invalidated. - *

      - * This method simply performs in.mark(readlimit). - * - * @param readlimit the maximum limit of bytes that can be read before - * the mark position becomes invalid. - * @see java.io.FilterInputStream#in - * @see java.io.FilterInputStream#reset() - */ - @Override - public void mark(int readlimit) { - if (null == in) { - return; - } // don't throw exception to be consistent with other impls. - - super.mark(readlimit); - mark = read; - } - - /** - * Repositions this stream to the position at the time the - * mark method was last called on this input stream. - *

      - * This method simply performs in.reset(). - *

      - * Stream marks are intended to be used in - * situations where you need to read ahead a little to see what's in - * the stream. Often this is most easily done by invoking some - * general parser. If the stream is of the type handled by the - * parse, it just chugs along happily. If the stream is not of - * that type, the parser should toss an exception when it fails. - * If this happens within readlimit bytes, it allows the outer - * code to reset the stream and try another parser. - * - * @exception IOException if the stream has not been marked or if the - * mark has been invalidated. - * @see java.io.FilterInputStream#in - * @see java.io.FilterInputStream#mark(int) - */ - @Override - public void reset() throws IOException { - if (null == in) { - throw new IOException("Stream has been closed."); - } - - if (-1 == mark) { - throw new IOException("reset() without mark(), or I dont know where mark is"); - } - - super.reset(); - - read = mark; - } - - /** - * Skips over and discards n bytes of data from the - * input stream. The skip method may, for a variety of - * reasons, end up skipping over some smaller number of bytes, - * possibly 0. The actual number of bytes skipped is - * returned. - *

      - * This method - * simply performs in.skip(n). - * - * @param n the number of bytes to be skipped. - * @return the actual number of bytes skipped. - * @exception IOException if an I/O error occurs. - */ - @Override - public synchronized long skip(long n) throws IOException { - if (null == in) { - throw new IOException("Stream has been closed."); - } - - long skipLen = Math.min(n, (limit - read)); - - boolean wascounting = alreadycounting; - - alreadycounting = true; - long result = super.skip(skipLen); - - alreadycounting = wascounting; - - if ((-1 != result) && !alreadycounting) { - read += result; - } - - return result; - } - - /** - * Reads the next byte of data from this input stream. The value - * byte is returned as an int in the range - * 0 to 255. If no byte is available - * because the end of the stream has been reached, the value - * -1 is returned. This method blocks until input data - * is available, the end of the stream is detected, or an exception - * is thrown. - *

      - * This method - * simply performs in.read() and returns the result. - * - * @return the next byte of data, or -1 if the end of the - * stream is reached. - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#in - */ - @Override - public synchronized int read() throws IOException { - if (null == in) { - throw new IOException("Stream has been closed."); - } - - if (read >= limit) { - return -1; - } - - boolean wascounting = alreadycounting; - - alreadycounting = true; - int result = super.read(); - - alreadycounting = wascounting; - - if (!alreadycounting) { - if (-1 != result) { - read++; - } else { - if (fatalUnderflow && (read != limit)) { - IOException failed = new IOException( - "Underflow in read, stream EOFed at " + read + " before limit of " + limit); - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, failed.getMessage(), failed); - } - throw failed; - } - } - } - - return result; - } - - /** - * Reads up to len bytes of data from this input stream - * into an array of bytes. This method blocks until some input is - * available. - *

      - * This method simply performs in.read(b, off, len) - * and returns the result. - * - * @param b the buffer into which the data is read. - * @param off the start offset of the data. - * @param len the maximum number of bytes read. - * @return the total number of bytes read into the buffer, or - * -1 if there is no more data because the end of - * the stream has been reached. - * @exception IOException if an I/O error occurs. - * @see java.io.FilterInputStream#in - */ - @Override - public synchronized int read(byte[] b, int off, int len) throws IOException { - if (null == in) { - throw new IOException("Stream has been closed."); - } - - if (read >= limit) { - return -1; - } - - int readLen = (int) Math.min(len, limit - read); - - boolean wascounting = alreadycounting; - - alreadycounting = true; - int result = super.read(b, off, readLen); - - alreadycounting = wascounting; - - if (!alreadycounting) { - if (-1 != result) { - read += result; - } else { - if (fatalUnderflow && (read != limit)) { - IOException failed = new IOException( - "Underflow while tring to read " + readLen + ", stream EOFed at " + read + " before limit of " + limit); - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, failed.getMessage(), failed); - } - throw failed; - - } - } - } - - return result; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/MarkProhibitedFilterStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/MarkProhibitedFilterStream.java deleted file mode 100644 index ca73a2a0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/MarkProhibitedFilterStream.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.FilterInputStream; -import java.io.InputStream; - -import java.io.IOException; - - -/** - * Implements a filter which disables the mark() feature of an input stream. - * Useful for when the stream is shared. - **/ -public class MarkProhibitedFilterStream extends FilterInputStream { - - /** - * Creates a new instance of MarkProhibitedFilterStream - * - * @param in the stream which will be limited. - */ - public MarkProhibitedFilterStream(InputStream in) { - super(in); - } - - /** - * {@inheritDoc} - * - *

      This method does nothing. - **/ - @Override - public void mark(int readlimit) {} - - /** - * {@inheritDoc} - * - *

      This implementation always throws IOException since mark is not - * supported. - */ - @Override - public void reset() throws IOException { - throw new IOException("reset() not supported"); - } - - /** - * {@inheritDoc} - * - *

      This method simply returns false. - **/ - @Override - public boolean markSupported() { - return false; - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/MessageUtilities.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/MessageUtilities.java deleted file mode 100644 index 85a7bb00..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/MessageUtilities.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All right reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; - - -/** - * @deprecated These utilities are unsupported and known to have problems. They - * are not recommended for use and will be removed in a future JXTA release - * THIS CLASS IS SCHEDULED TO BE REMOVED AFTER 2.5. - */ -@Deprecated -public final class MessageUtilities { - - private MessageUtilities() {} - - // Fix-Me: I didn't implement byte, short or float - // Fix-Me: I didn't implement arrays, ie addInt(Message message, String tagName, int values[]), etc - // Fix-Me: I didn't implement add DocumentSerializable yet - - public static void addInt(Message message, String tagName, int value) { - StringMessageElement stringMessageElement = new StringMessageElement(tagName, Integer.toString(value), null); - - message.addMessageElement(stringMessageElement); - } - - public static int getInt(Message message, String tagName, int defaultValue) { - StringMessageElement stringMessageElement = (StringMessageElement) message.getMessageElement(tagName); - - if (stringMessageElement != null) { - return Integer.parseInt(stringMessageElement.toString()); - } else { - return defaultValue; - } - } - - public static void addLong(Message message, String tagName, long value) { - StringMessageElement stringMessageElement = new StringMessageElement(tagName, Long.toString(value), null); - - message.addMessageElement(stringMessageElement); - } - - public static long getLong(Message message, String tagName, long defaultValue) { - StringMessageElement stringMessageElement = (StringMessageElement) message.getMessageElement(tagName); - - if (stringMessageElement != null) { - return Long.parseLong(stringMessageElement.toString()); - } else { - return defaultValue; - } - } - - public static void addDouble(Message message, String tagName, double value) { - StringMessageElement stringMessageElement = new StringMessageElement(tagName, Double.toString(value), null); - - message.addMessageElement(stringMessageElement); - } - - public static double getDouble(Message message, String tagName, double defaultValue) { - StringMessageElement stringMessageElement = (StringMessageElement) message.getMessageElement(tagName); - - if (stringMessageElement != null) { - return Double.parseDouble(stringMessageElement.toString()); - } else { - return defaultValue; - } - } - - public static void addBoolean(Message message, String tagName, boolean value) { - StringMessageElement stringMessageElement = new StringMessageElement(tagName, value ? "true" : "false", null); - - message.addMessageElement(stringMessageElement); - } - - public static boolean getBoolean(Message message, String tagName, boolean defaultValue) { - StringMessageElement stringMessageElement = (StringMessageElement) message.getMessageElement(tagName); - - if (stringMessageElement != null) { - return "true".equals(stringMessageElement.toString()); - } else { - return defaultValue; - } - } - - public static void addString(Message message, String tagName, String value) { - StringMessageElement stringMessageElement = new StringMessageElement(tagName, value, null); - - message.addMessageElement(stringMessageElement); - } - - public static String getString(Message message, String tagName, String defaultValue) { - MessageElement stringMessageElement = message.getMessageElement(tagName); - - if (stringMessageElement != null) { - return stringMessageElement.toString(); - } else { - return defaultValue; - } - } - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/PipeEventListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/PipeEventListener.java deleted file mode 100644 index 7bbb041b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/PipeEventListener.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.util.EventListener; - - -/** - * The listener interface for receiving JxtaBiDiPipe - * events. - * - * The following example illustrates how to implement a {@link net.jxta.util.PipeEventListener}: - *

      
      - * PipeEventListener myListener = new PipeEventListener() {
      - *
      - *   public void pipeEvent(int event) {
      - *        if (event == JxtaBiDiPipe.PIPE_CLOSED_EVENT) {
      - *          .....
      - *        }
      - *   }
      - * }
      - *
      - * InputPipe pipeIn = pipe.createInputPipe(pipeAdv, myListener);
      - * *
      - * - */ -public interface PipeEventListener extends EventListener { - - /** - * Called for each pipe message event that occurs. - * - * @param event The event being received. - */ - void pipeEvent(int event); - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/PipeStateListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/PipeStateListener.java deleted file mode 100644 index 28740206..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/PipeStateListener.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2006-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.util.EventListener; - - -/** - * The listener interface for receiving JxtaBiDiPipe - * events. - * - * The following example illustrates how to implement a {@link net.jxta.util.PipeStateListener}: - *
      
      - * PipeStateListener myListener = new PipeStateListener() {
      - *
      - *   public void pipeEvent(int event) {
      - *        if (event == PipeStateListener.PIPE_CLOSED_EVENT) {
      - *          .....
      - *        }
      - *   }
      - * }
      - *
      - * InputPipe pipeIn = pipe.createInputPipe(pipeAdv, myListener);
      - * 
      - * - */ -public interface PipeStateListener extends EventListener { - - /** - * Pipe close Event - */ - public static final int PIPE_CLOSED_EVENT = 1; - - /** - * Pipe opened Event - */ - public static final int PIPE_OPENED_EVENT = 2; - - /** - * Pipe failed Event - */ - public static final int PIPE_FAILED_EVENT = 4; - - /** - * Called for each pipe mode event that occurs. - * - * @param source the source of the event (JxtaBiDiPipe) - * @param event The event being received. - */ - void stateEvent(Object source, int event); - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/PipeUtilities.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/PipeUtilities.java deleted file mode 100644 index f6867665..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/PipeUtilities.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.net.URI; -import net.jxta.pipe.*; -import net.jxta.id.*; -import net.jxta.peergroup.*; -import net.jxta.endpoint.*; -import net.jxta.document.*; -import net.jxta.protocol.*; -import net.jxta.exception.*; - - -public final class PipeUtilities { - - private PipeUtilities() {} - - public static PipeAdvertisement createPipeAdvertisement() { - return (PipeAdvertisement) AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType()); - } - - public static PipeAdvertisement createPipeAdvertisement(PipeID pipeId, String pipeType) { - PipeAdvertisement pipeAdvertisement = createPipeAdvertisement(); - - pipeAdvertisement.setPipeID(pipeId); - pipeAdvertisement.setType(pipeType); - return pipeAdvertisement; - } - - public static PipeAdvertisement createPipeAdvertisement(String pipeIdText, String pipeType) throws JxtaException { - PipeID pipeId = (PipeID) ID.create(URI.create(pipeIdText)); - PipeAdvertisement pipeAdvertisement = (PipeAdvertisement) AdvertisementFactory.newAdvertisement( - PipeAdvertisement.getAdvertisementType()); - - pipeAdvertisement.setPipeID(pipeId); - pipeAdvertisement.setType(pipeType); - return pipeAdvertisement; - } - - public static PipeAdvertisement createPipeAdvertisement(Element root) { - TextElement pipeAdvElement = (TextElement) DocumentUtilities.getChild(root, PipeAdvertisement.getAdvertisementType()); - - if (pipeAdvElement == null) { - return null; - } - - return (PipeAdvertisement) AdvertisementFactory.newAdvertisement(pipeAdvElement); - } - - public static PipeAdvertisement createNewPipeAdvertisement(PeerGroup peerGroup, String pipeType) { - PipeAdvertisement pipeAdvertisement = createPipeAdvertisement(); - - PipeID pipeID = IDFactory.newPipeID(peerGroup.getPeerGroupID()); - - pipeAdvertisement.setPipeID(pipeID); - pipeAdvertisement.setType(pipeType); - return pipeAdvertisement; - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/SimpleSelectable.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/SimpleSelectable.java deleted file mode 100644 index 0fafb798..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/SimpleSelectable.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.util; - -/** - * This the interface that all selectable objects expose. - * - *

      - * Applications programmers should treat this API as temporary, for now. - * - *

      - * A SimpleSelectable object can register SimpleSelector objects so that - * they are notified whenever this object chooses to report a change. - * - *

      - * SimpleSelectors are SimpleSelectable, therefore selectors can be selected. - * - *

      - * The change notification interface used to notify a selector is actually - * specified in SimpleSelectable. As a result, certain implementations may also - * allow to register SimpleSelectables that are not Selectors. Selectors themselves do not allow that. - * - * @see SimpleSelector - * @see AbstractSimpleSelectable - */ -public interface SimpleSelectable { - - /** - * A simple reference object that can be put in a map instead of the one it refers to. - * SimpleSelectable object often need to be put in maps where distinct objects are to be treated - * as such, even if they are identical at a semantical level. However, some - * SimpleSelectable objects may have semantically equals() and hashCode() - * methods rather than the identity ones. - * - *

      - * For that reason, whenever a SimpleSelectable needs to be used as a map or set key, its identity - * reference should be used instead. All SimpleSelectable can return an identity reference. A given - * SimpleSelectable always provides the same IdentityReference object. IdentityReference never overloads - * hashCode() and equals() in a way that could make different objects be equal or that could provide - * different results from invocation to invocation. - */ - public static class IdentityReference { - private final SimpleSelectable object; - - /** - * Creates a new IdentityReference object - * - * @param object the selectable - */ - public IdentityReference(SimpleSelectable object) { - this.object = object; - } - - /** - * @return The object that this one refers to. - */ - public SimpleSelectable getObject() { - return object; - } - } - - /** - * @return A canonical IdentityReference for this object. - * A given SimpleSelectable always provides the same IdentityReference - * object. An IdentityReference must never overload hashCode() or equals() - * in a way that could make different objects be equal or that could provide - * different results from invocation to invocation. - */ - public IdentityReference getIdentityReference(); - - /** - * Registers the given selector with this selectable object. This always - * causes one change event for this object to be reported through the - * selector. As a result, when selecting for a condition, it is not - * necessary to verify whether it has already happened or not; the next call - * to select will be able to detect it. - * - * @param s The SimpleSelector to register - */ - public void register(SimpleSelector s); - - /** - * Unregisters the given selector, so that it is no-longer notified when - * this object changes. - * - * @param s The SimpleSelector to unregister - */ - public void unregister(SimpleSelector s); - - /** - * This method is invoked when the given selectable object has changed. This - * permits to cascade selectable objects, so that one reports a change when - * the other changes, without having to select it. This also permits - * implementation of this interface by delegating its implementation to a - * utility class. - *

      - * An implementation may do what it wants about it. For example, a - * {@link SimpleSelector} will report the change to - * {@link SimpleSelector#select} and invoke - * {@link AbstractSimpleSelectable#notifyChange()} thereby reporting its own - * change to cascaded selectors. Other implementations may only invoke - * {@link AbstractSimpleSelectable#notifyChange()} or may perform more - * complex tasks. - * - * @see AbstractSimpleSelectable - * - * @param changedObject the object that has changed. - */ - public void itemChanged(SimpleSelectable changedObject); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/SimpleSelector.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/SimpleSelector.java deleted file mode 100644 index 22baaedf..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/SimpleSelector.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.util.Set; -import java.util.Collection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; - - -/** - * A very primitive version of NIO's select mechanism. Applications should not - * code to this API yet. This is subject to change and for use only by internal - * mechanisms. This is only good at implementing efficient polling. Users must - * wait for a batch of state changes and then figure out which item's state - * changed to something interesting. The batch returned by simpleSelect is a set - * of the items which state did change since the previous time select returned. - * Since a batch is returned as soon as there is at least one item in it, most - * batches are very small, they will contain the first item that was added, plus - * whatever few could sneak in between then and when select wakes-up and grabs - * that batch. - * - *

      A simpleSelector It is not very usable by multiple threads at once, - * unless they all do the same thing. Items are removed from the current batch - * when select returns it. As a result, any state change occurring in-between - * two calls to select() is guaranteed to be reported by the next call. However, - * the new state may be observed before the next select call to select returns - * the corresponding event, which may then be viewed as redundant. So events are - * reported too much rather than too little. - */ -public final class SimpleSelector extends AbstractSimpleSelectable { - - /** - * The small set of items that changed since the last batch was returned - * by select. - **/ - private final Set currentBatch = new HashSet(2); - - /** - * Let it be newed for now. We need to find a place for a factory. - */ - public SimpleSelector() {} - - /** - * {@inheritDoc} - * - *

      This is invoked by registered items when their state changes. Records - * changes for the benefit of {@link #select()}, and performs notifyChange(), - * which will cause notification of cascaded selectors, if any. It is thus - * possible to register selectors with a selector and come to a particular - * one only when it has something to report. - **/ - public final void itemChanged(SimpleSelectable item) { - synchronized (currentBatch) { - currentBatch.add(item.getIdentityReference()); - currentBatch.notifyAll(); - } - notifyChange(); - } - - /** - * This blocks unless and until at least one of the selected items reports - * that it changed. Then the list of such items is returned. More than one - * item may be added to the list by the time it is returned to the invoker. - * - *

      Note: the result cannot be a set, otherwise we would be - * prevented from returning objects that overload hashCode/equals. Every - * item returned will be a distinct object. - * - *

      The invoker should never assume that all items in the result - * have indeed changed in any expected manner or even changed at all. The - * simple action of registering a selector may, and usually does, cause the - * selectable object to report a change. In some cases a selectable object - * may just be unable to prove that it has not changed, and thus report a - * change. It is up to the invoker to inspect the relevant item's state - * every time. - **/ - public Collection select() throws InterruptedException { - - IdentityReference[] refs; - - synchronized (currentBatch) { - int resLen = 0; - - while ((resLen = currentBatch.size()) == 0) { - currentBatch.wait(); - } - - refs = currentBatch.toArray(new IdentityReference[resLen]); - currentBatch.clear(); - } - - // Now we have to retrieve the real objects behind the identity references. - // Costly, but unavoidable. - Collection result = new ArrayList(refs.length); - - for (IdentityReference aRef : Arrays.asList(refs)) { - result.add(aRef.getObject()); - } - - return result; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/WatchedInputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/WatchedInputStream.java deleted file mode 100644 index df384c00..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/WatchedInputStream.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.*; -import java.util.Collection; - - -/** - * @deprecated This class is no longer used by the JXTA core and should not - * have been part of the public JXTA API. If you use it, copy it to your own - * source base. It will be deleted after June 2007 release. - */ -@Deprecated -public class WatchedInputStream extends FilterInputStream - implements WatchedStream { - - static final int DEFAULT_CHUNK_SIZE = 4096; - Collection watchList = null; - volatile boolean stalled = false; - volatile boolean idle = true; - boolean closed = false; - final int chunkSize; - InputStream in = null; - - public WatchedInputStream(InputStream in, int chunkSize) { - super(in); - this.in = in; - this.chunkSize = chunkSize; - } - - public WatchedInputStream(InputStream in) { - this(in, DEFAULT_CHUNK_SIZE); - } - - /** - * {@inheritDoc} - *

      - *

      Debugging toString. - */ - @Override - public String toString() { - if (null == in) { - return "closed/" + super.toString(); - } else { - if (in instanceof ByteArrayInputStream) { - // ByteArrayInputStream.toString() prints the entire stream! - return in.getClass().getName() + "@" + System.identityHashCode(in) + "/" + super.toString(); - } else { - return in.toString() + "/" + super.toString(); - } - } - } - - /** - * Sets the watcher list onto which this stream must register - * when it is not idle (so that it can be watched). - * This implementation may or may not remain registered while idle. - * This may affect performance but not functionality. - * It is assumed that that list is monitored by a watcher task that - * invokes the watch method as often as needed to monitor progress - * to its satisfaction. - * - * @param watchList The watchList to register with. Must be a - * Synchronized Collection. - */ - public synchronized void setWatchList(Collection watchList) { - if (this.watchList != null) { - this.watchList.remove(this); - } - this.watchList = watchList; - watchList.add(this); - } - - // This routine may be invoked as often as progress needs to be asserted. - // After at most two watch cycles stalling is detected. - public void watch() { - - if (idle) { - return; - } - - if (!stalled) { - stalled = true; // challenge a write method to clear that flag. - return; - } - - // It's stalled. The last time around it was not idle, so we set the - // stalled flag. Now, it is still not idle and the flag is still there. - // break the stream. - try { - close(); - } catch (IOException ioe) { - ; - } - } - - @Override - public void close() throws IOException { - idle = true; - synchronized (this) { - if (watchList != null) { - watchList.remove(this); - watchList = null; - } - - // Avoid calling close redundantly; some OSes seem to have - // deadlock capabilities when doing that. - - if (closed) { - return; - } - closed = true; - } - super.close(); - } - - @Override - public int read() throws IOException { - stalled = false; - idle = false; - try { - return in.read(); - } finally { - idle = true; - } - } - - // We overload it; not trusting that the base classes method does - // call read(byte[], int, int) in the future. - @Override - public int read(byte[] b) throws IOException { - return read(b, 0, b.length); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - - // Apply the standard checks here; we will call in.read repeatedly - // which means that errors could be discovered too late per read's - // contract. - - if ((off < 0) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { - - throw new IndexOutOfBoundsException(); - - } - - stalled = false; - idle = false; - int left = len; - - try { - int i; - - while (left > chunkSize) { - i = in.read(b, off, chunkSize); - stalled = false; - if (i <= 0) { - if (left == len) { - return i; - } - return len - left; - } - off += i; - left -= i; - - // Must check available only after firt read. - // first read must wait for at least one byte. - - if (in.available() == 0) { - return len - left; - } - } - - // Read the left over now. If this is not the first read, - // available has been checked in the loop above. - i = in.read(b, off, left); - if (i <= 0) { - if (left == len) { - return i; - } - return len - left; - } - - return len - left + i; - - } finally { - idle = true; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/WatchedOutputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/WatchedOutputStream.java deleted file mode 100644 index c80de5ef..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/WatchedOutputStream.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.ByteArrayOutputStream; -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Collection; - - -/** - * @deprecated This class is no longer used by the JXTA core and should not - * have been part of the public JXTA API. If you use it, copy it to your own - * source base. It will be deleted after June 2007 release. - */ -@Deprecated -public class WatchedOutputStream extends FilterOutputStream - implements WatchedStream { - - static final int DEFAULT_CHUNK_SIZE = 4096; - transient Collection watchList = null; - transient volatile boolean stalled = false; - transient volatile boolean idle = true; - transient boolean closed = false; - transient final int chunkSize; - transient OutputStream out = null; - - public WatchedOutputStream(OutputStream out, int chunkSize) { - super(out); - this.out = out; - this.chunkSize = chunkSize; - } - - public WatchedOutputStream(OutputStream out) { - this(out, DEFAULT_CHUNK_SIZE); - } - - /** - * {@inheritDoc} - *

      - *

      Debugging toString. - */ - @Override - public String toString() { - - if (null == out) { - return "closed/" + super.toString(); - } else { - if (out instanceof ByteArrayOutputStream) { - // ByteArrayInputStream.toString() prints the entire stream! - return out.getClass().getName() + "@" + System.identityHashCode(out) + "/" + super.toString(); - } else { - return out.toString() + "/" + super.toString(); - } - } - } - - /** - * Sets the watcher list onto which this stream must register - * when it is not idle (so that it can be watched). - * This implementation may or may not remain registered while idle. - * This may affect performance but not functionality. - * It is assumed that that list is monitored by a watcher task that - * invokes the watch method as often as needed to monitor progress - * to its satisfaction. - * - * @param watchList The watchList to register with. Must be a - * Synchronized Collection. - */ - public synchronized void setWatchList(Collection watchList) { - if (this.watchList != null) { - this.watchList.remove(this); - } - this.watchList = watchList; - watchList.add(this); - } - - // This routine may be invoked as often as progress needs to be asserted. - // After at most two watch cycles stalling is detected. - public void watch() { - - if (idle) { - return; - } - - if (!stalled) { - stalled = true; // challenge a write method to clear that flag. - return; - } - - // It's stalled. The last time around it was not idle, so we set the - // stalled flag. Now, it is still not idle and the flag is still there. - // break the stream. - try { - close(); - } catch (IOException ioe) { - ; - } - } - - @Override - public void close() throws IOException { - idle = true; - synchronized (this) { - if (watchList != null) { - watchList.remove(this); - watchList = null; - } - - // Avoid calling close redundantly; some OSes seem to have - // deadlock capabilities when doing that. - - if (closed) { - return; - } - closed = true; - } - super.close(); - } - - @Override - public void flush() throws IOException { - stalled = false; - idle = false; - try { - out.flush(); - } finally { - idle = true; - } - } - - @Override - public void write(int b) throws IOException { - stalled = false; - idle = false; - try { - out.write(b); - } finally { - idle = true; - } - } - - // We overload it; not trusting that the base classe's method does - // call write(byte[], int, int) in the future. - @Override - public void write(byte[] b) throws IOException { - write(b, 0, b.length); - } - - // We overload it; not wanting the base classe's method to - // call write(int). - @Override - public void write(byte[] b, int off, int len) throws IOException { - - // Do the standard checks here. Since we will be calling write - // repeatedly, errors could be discovered too late per write's - // contract. - - if ((off < 0) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { - - throw new IndexOutOfBoundsException(); - - } else if (len == 0) { - return; - } - - stalled = false; - idle = false; - try { - while (len > chunkSize) { - out.write(b, off, chunkSize); - stalled = false; - off += chunkSize; - len -= chunkSize; - } - if (len > 0) { - out.write(b, off, len); - } - } finally { - idle = true; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/WatchedStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/WatchedStream.java deleted file mode 100644 index 7fb109e9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/WatchedStream.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util; - - -import java.io.*; -import java.util.Collection; - - -/** - * @deprecated This class is no longer used by the JXTA core and should not - * have been part of the public JXTA API. If you use it, copy it to your own - * source base. It will be deleted after June 2007 release. - */ -@Deprecated -public interface WatchedStream { - - /** - * Sets the watcher list onto which this stream must register - * when it is not idle (so that it can be watched). - * This implementation may or may not remain registered while idle. - * This may affect performance but not functionality. - * It is assumed that that list is monitored by a watcher task that - * invokes the watch method as often as needed to monitor progress - * to its satisfaction. - * - * @param watchList The watchList to register with. Must be a - * Synchronized Collection. - */ - public void setWatchList(Collection watchList); - - /** - * This routine may be invoked as often as progress needs to be asserted. - * After at most two watch cycles stalling is detected. - */ - public void watch(); - - /** - * In case we want to close a watchStream regardless of its making - * progress. - * - * @throws java.io.IOException if an io error occurs - */ - public void close() throws IOException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/documentSerializable/DocumentSerializable.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/documentSerializable/DocumentSerializable.java deleted file mode 100644 index f02363ff..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/documentSerializable/DocumentSerializable.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util.documentSerializable; - - -import net.jxta.document.*; - - -/** - **/ -public interface DocumentSerializable { - public void initializeFrom(Element element) throws DocumentSerializationException; - public void serializeTo(Element element) throws DocumentSerializationException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/documentSerializable/DocumentSerializableUtilities.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/documentSerializable/DocumentSerializableUtilities.java deleted file mode 100644 index f32e88dd..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/documentSerializable/DocumentSerializableUtilities.java +++ /dev/null @@ -1,570 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util.documentSerializable; - - -import net.jxta.document.*; -import net.jxta.exception.*; -import net.jxta.util.*; - -import java.util.*; -import java.io.*; - - -/** - **/ -public class DocumentSerializableUtilities { - // Fix-Me: I didn't implement byte, short or float - // Fix-Me: I didn't implement arrays, ie addInt(Element element, String tagName, int values[]), etc - - /** - * Creates a Structured XML Document containing the serialized object - * - * @return The created Document - * @throws DocumentSerializationException if Unable to parse the serialized object. - */ - public static XMLDocument createStructuredXmlDocument(String docType, DocumentSerializable documentSerializable) throws DocumentSerializationException { - XMLDocument xmlDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, docType); - - documentSerializable.serializeTo(xmlDoc); - return xmlDoc; - } - - /** - * Deeply copy an element into another element - * - * @param toElement The target Element - * @param fromElement The source Element - */ - public static void copyChildren(Element toElement, Element fromElement) { - // for now ... a quicky use of another utility - - StructuredDocument intoDoc = toElement.getRoot(); - - StructuredDocumentUtils.copyChildren(intoDoc, toElement, fromElement); - } - - /** - * Add an Element with the specified tagname and value (converted to a String) - * - * @param element Parent Element that the new child element will be added to - * @param tagName TagName to be used for the created Child Element - * @param documentSerializable This value will be serialized into the created child element - \ * @throws DocumentSerializationException if Unable to serialized object. - **/ - public static void addDocumentSerializable(Element element, String tagName, DocumentSerializable documentSerializable) throws DocumentSerializationException { - StructuredDocument structuredDocument = element.getRoot(); - Element childElement = structuredDocument.createElement(tagName); - - element.appendChild(childElement); - documentSerializable.serializeTo(childElement); - } - - /** - * Create an object from its Document Serialized components - * - * @param element The relative root element of a Document Serialized Object - * @param clazz The Class of the resurrected object (must implement DocumentSerializable and have a public no-arg constructor) - * @return An object of type 'clazz' - * @throws DocumentSerializationException if Unable to parse the serialized object. - **/ - public static DocumentSerializable getDocumentSerializable(Element element, Class clazz) throws DocumentSerializationException { - try { - return getDocumentSerializable(element, (DocumentSerializable) clazz.newInstance()); - } catch (DocumentSerializationException e) { - throw e; - } catch (Exception e) { - throw new DocumentSerializationException("Class must have a public no-arg constructor", e); - } - } - - /** - * Initialize an object from its Document Serialized components - * - * @param element The relative root element of a Document Serialized Object - * @param documentSerializable The object that will be populated from the Element - * @return The same parameter passed to it 'documentSerializable' - * @throws DocumentSerializationException if Unable to parse the serialized object. - **/ - public static DocumentSerializable getDocumentSerializable(Element element, DocumentSerializable documentSerializable) throws DocumentSerializationException { - documentSerializable.initializeFrom(element); - return documentSerializable; - } - - /** - * Create an object from its Document Serialized components - * - * @param element The Parent element which has a child Element with the serialized value - * @param tagName The tagname of the element that contains the relative root element of a Document Serialized Object - * @param clazz The Class of the resurrected object (must implement DocumentSerializable and have a public no-arg constructor) - * @return An object of type 'clazz' - * @throws DocumentSerializationException if Unable to parse the serialized object. - **/ - public static DocumentSerializable getDocumentSerializable(Element element, String tagName, Class clazz) throws DocumentSerializationException { - Element childElement = getChildElement(element, tagName); - - if (childElement != null) { - return getDocumentSerializable(childElement, clazz); - } else { - return null; - } - } - - /** - * Create a copy of any Document Serializable object. - * - * This is done by serializing and then deserializing the object (ie not very efficient) - * - * @param documentSerializable The Object to be copied - * @return An copy of the presented object - * @throws DocumentSerializationException if Unable to serialize or parse object. - **/ - public static DocumentSerializable copyDocumentSerializable(DocumentSerializable documentSerializable) throws DocumentSerializationException { - StructuredDocument structuredDocument = createStructuredXmlDocument("temp", documentSerializable); - - return getDocumentSerializable(structuredDocument, documentSerializable.getClass()); - } - - /** - * Create a child element of the specified tagName - * - * This is done by serializing and then deserializing the object (ie not very efficient) - * - * @param element The Parent Element - * @param tagName The Tag Name for the new Element - * @return The created Element - **/ - public static Element createChildElement(Element element, String tagName) { - StructuredDocument structuredDocument = element.getRoot(); - Element childElement = structuredDocument.createElement(tagName); - - element.appendChild(childElement); - return childElement; - } - - /** - * Get a child element of the specified tagName - * - * This is done by serializing and then deserializing the object (ie not very efficient) - * - * @param element The Parent Element - * @param tagName The Tag Name for the new Element - * @return The found Element - **/ - public static Element getChildElement(Element element, String tagName) { - Enumeration e = element.getChildren(tagName); - - if (e.hasMoreElements()) { - return (Element) e.nextElement(); - } else { - return null; - } - } - - /** - * Add an Element with the specified tagname and value (converted to a String) - * - * @param element Parent Element that the new element will be added to - * @param tagName TagName to be used for the created Child Element - * @param value The value that will be stored in the Element as a String - **/ - public static void addInt(Element element, String tagName, int value) { - StructuredDocument structuredDocument = element.getRoot(); - Element childElement = structuredDocument.createElement(tagName, Integer.toString(value)); - - element.appendChild(childElement); - } - - /** - * Get the value of an element converted from a String - * - * @param element Element that contains the value - * @return the value converted from a String - **/ - public static int getInt(Element element) { - return Integer.parseInt((String) element.getValue()); - } - - /** - * Get the value of a Child Element - * - * @param element The Parant Element - * @param tagName The Tag Name of the Child Element that will contain the value - * @param defaultValue The return value if there is no Child Element with that Tag Name - * @return the value converted from a String - **/ - public static int getInt(Element element, String tagName, int defaultValue) { - Element childElement = getChildElement(element, tagName); - - if (childElement != null) { - return getInt(childElement); - } else { - return defaultValue; - } - } - - /** - * Add an Element with the specified tagname and value (converted to a String) - * - * @param element Parent Element that the new element will be added to - * @param tagName TagName to be used for the created Child Element - * @param value The value that will be stored in the Element as a String - **/ - public static void addLong(Element element, String tagName, long value) { - StructuredDocument structuredDocument = element.getRoot(); - Element childElement = structuredDocument.createElement(tagName, Long.toString(value)); - - element.appendChild(childElement); - } - - /** - * Get the value of an element converted from a String - * - * @param element Element that contains the value - * @return the value converted from a String - **/ - public static long getLong(Element element) { - return Long.parseLong((String) element.getValue()); - } - - /** - * Get the value of a Child Element - * - * @param element The Parant Element - * @param tagName The Tag Name of the Child Element that will contain the value - * @param defaultValue The return value if there is no Child Element with that Tag Name - * @return the value converted from a String - **/ - public static long getLong(Element element, String tagName, long defaultValue) { - Element childElement = getChildElement(element, tagName); - - if (childElement != null) { - return getLong(childElement); - } else { - return defaultValue; - } - } - - /** - * Add an Element with the specified tagname and value (converted to a String) - * - * @param element Parent Element that the new element will be added to - * @param tagName TagName to be used for the created Child Element - * @param value The value that will be stored in the Element as a String - **/ - public static void addDouble(Element element, String tagName, double value) { - StructuredDocument structuredDocument = element.getRoot(); - Element childElement = structuredDocument.createElement(tagName, Double.toString(value)); - - element.appendChild(childElement); - } - - /** - * Get the value of an element converted from a String - * - * @param element Element that contains the value - * @return the value converted from a String - **/ - public static double getDouble(Element element) { - return Double.parseDouble((String) element.getValue()); - } - - /** - * Get the value of a Child Element - * - * @param element The Parant Element - * @param tagName The Tag Name of the Child Element that will contain the value - * @param defaultValue The return value if there is no Child Element with that Tag Name - * @return the value converted from a String - **/ - public static double getDouble(Element element, String tagName, double defaultValue) { - Element childElement = getChildElement(element, tagName); - - if (childElement != null) { - return getDouble(childElement); - } else { - return defaultValue; - } - } - - /** - * Add an Element with the specified tagname and value (converted to a String) - * - * @param element Parent Element that the new element will be added to - * @param tagName TagName to be used for the created Child Element - * @param value The value that will be stored in the Element as a String - **/ - public static void addBoolean(Element element, String tagName, boolean value) { - StructuredDocument structuredDocument = element.getRoot(); - Element childElement = structuredDocument.createElement(tagName, value ? "true" : "false"); - - element.appendChild(childElement); - } - - /** - * Get the value of an element converted from a String ("true" or "false") - * - * @param element Element that contains the value - * @return the value converted from a String - **/ - public static boolean getBoolean(Element element) { - return "true".equals((String) element.getValue()); - } - - /** - * Get the value of a Child Element - * - * @param element The Parant Element - * @param tagName The Tag Name of the Child Element that will contain the value - * @param defaultValue The return value if there is no Child Element with that Tag Name - * @return the value converted from a String - **/ - public static boolean getBoolean(Element element, String tagName, boolean defaultValue) { - Element childElement = getChildElement(element, tagName); - - if (childElement != null) { - return getBoolean(childElement); - } else { - return defaultValue; - } - } - - /** - * Add an Element with the specified tagname and value - * - * @param element Parent Element that the new element will be added to - * @param tagName TagName to be used for the created Child Element - * @param value The value that will be stored in the Element - **/ - public static void addString(Element element, String tagName, String value) { - StructuredDocument structuredDocument = element.getRoot(); - Element childElement = structuredDocument.createElement(tagName, value); - - element.appendChild(childElement); - } - - /** - * Get the value of an element as a String - * - * @param element Element that contains the value - * @return the value converted from a String - **/ - public static String getString(Element element) { - return (String) element.getValue(); - } - - /** - * Get the value of a Child Element - * - * @param element The Parant Element - * @param tagName The Tag Name of the Child Element that will contain the value - * @param defaultValue The return value if there is no Child Element with that Tag Name - * @return The value found in the Element - **/ - public static String getString(Element element, String tagName, String defaultValue) { - Element childElement = getChildElement(element, tagName); - - if (childElement != null) { - return getString(childElement); - } else { - return defaultValue; - } - } - - /** - * Convert a DocumentSerializable object to its XML representation as a String - * - * The Root TagName will be 'documentSerializable' by default - * - * @param documentSerializable The Object to be converted to an XML Document - * @return The String representation of an XML Document - * @throws DocumentSerializationException if Unable to serialize object. - **/ - public static String toXmlString(DocumentSerializable documentSerializable) throws DocumentSerializationException { - return toXmlString(documentSerializable, "documentSerializable"); - } - - /** - * Convert a DocumentSerializable object to its XML representation as a String - * - * The Root TagName will be 'documentSerializable' by default - * - * @param documentSerializable The Object to be converted to an XML Document - * @param rootTagName The Root tagName for the XML Document - * @return The String representation of an XML Document - * @throws DocumentSerializationException if Unable to serialize object. - **/ - public static String toXmlString(DocumentSerializable documentSerializable, String rootTagName) throws DocumentSerializationException { - try { - StringWriter bout = new StringWriter(); - XMLDocument document = DocumentSerializableUtilities.createStructuredXmlDocument(rootTagName, documentSerializable); - - document.sendToWriter(bout); - bout.close(); - - return bout.toString(); - } catch (IOException e) { - throw new DocumentSerializationException("Error converting to String", e); - } - } - - /** - * Write a DocumentSerializable object as an XML Document to a Stream - * - * The Root TagName will be 'documentSerializable' by default - * - * @param out The Stream to write the document to - * @param documentSerializable The Object to be converted to an XML Document - * @throws DocumentSerializationException if Unable to serialize object. - * @throws IOException if I/O error while writing - **/ - public static void writeAsXmlString(OutputStream out, DocumentSerializable documentSerializable) throws IOException, DocumentSerializationException { - writeAsXmlString(out, documentSerializable, "documentSerializable"); - } - - /** - * Write a DocumentSerializable object as an XML Document to a Stream - * - * The Root TagName will be 'documentSerializable' by default - * - * @param out The Stream to write the document to - * @param rootTagName The Root tagName for the XML Document - * @param documentSerializable The Object to be converted to an XML Document - * @throws DocumentSerializationException if Unable to serialize object. - * @throws IOException if I/O error while writing - **/ - public static void writeAsXmlString(OutputStream out, DocumentSerializable documentSerializable, String rootTagName) throws IOException, DocumentSerializationException { - StructuredDocument document = DocumentSerializableUtilities.createStructuredXmlDocument(rootTagName, documentSerializable); - - document.sendToStream(out); - } - - /** - * Write a DocumentSerializable object as an XML Document to StdErr - * - * The Root TagName will be 'documentSerializable' by default - * - * @param documentSerializable The DocumentSerializable to be printed. - **/ - public static void printAsXmlString(DocumentSerializable documentSerializable) { - try { - if (documentSerializable == null) { - System.err.println(""); - } else { - writeAsXmlString(System.err, documentSerializable); - } - } catch (Exception e) { - System.err.println(" for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.util.documentSerializable; - - -import net.jxta.exception.JxtaException; - - -/** - **/ -public class DocumentSerializationException extends JxtaException { - public DocumentSerializationException(String message) { - super(message); - } - - public DocumentSerializationException(String message, Exception exception) { - super(message, exception); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/package.html deleted file mode 100644 index c4c1b99d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/net/jxta/util/package.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - A collection of utility classes used by the JXTA implementation and/or - useful to users of the JXTA API. - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/sun/net/www/protocol/urn/Handler.java b/p2pproxy/dependencies-src/jxse-src-2.5/api/src/sun/net/www/protocol/urn/Handler.java deleted file mode 100644 index d665d805..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/api/src/sun/net/www/protocol/urn/Handler.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package sun.net.www.protocol.urn; - - -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; - -import java.io.IOException; - - -/** - * Handler for URN - * - * @deprecated Use the URI interfaces for JXTA IDs instead of the URLs. - */ -@Deprecated -public final class Handler extends URLStreamHandler { - - public static Handler handler = new Handler(); - - /** - * Creates new Handler - **/ - public Handler() {} - - /** - * - **/ - @Override - public URLConnection openConnection(URL connect) throws - IOException { - return null; - } - - /** - * - * Private replacement for toHexString since we need the leading 0 digits. - * Returns a String containing byte value encoded as 2 hex characters. - * - * @param theByte a byte containing the value to be encoded. - * @return String containing byte value encoded as 2 hex characters. - */ - private static String toHexDigits(byte theByte) { - final char[] HEXDIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - StringBuilder result = new StringBuilder(2); - - result.append(HEXDIGITS[(theByte >>> 4) & 15]); - result.append(HEXDIGITS[theByte & 15]); - - return result.toString(); - } - - /** - * - * 2.4 of RFC2141 says we have to encode these chars. - * - **/ - static final String needsEncoding = "%/?#" + "\\\"&<>[]^`{|}~"; - - /** - * - * The byte values of the chars we have to encode. - * - **/ - static final byte[] encodesTo = new byte[] { - 0x25, 0x2F, 0x3F, 0x23, 0x5c, 0x22, 0x26, 0x3C, 0x3E, 0x5B, 0x5D, 0x5E, 0x60, 0x7B, 0x7C, 0x7D, 0x7E - }; - - /** - * Encode a string such that it is in a form acceptable for presentation - * as a URN. First the string is encoded as UTF8 so that any high byte - * unicode chars are ascii representable. Then any special characters in - * the string are escaped using the URN % syntax. - * - * @param source the string to encode - * @return String containing the URN acceptable presentation form. - **/ - public static String encodeURN(String source) { - String asISO8559_1 = null; - - try { - // first we get its bytes using UTF to encode its characters. - byte[] asBytes = source.getBytes("UTF8"); - - // then read it back in as ISO-8859-1. This allows us to see the - // bytes with no translation. This string will have chars in the - // range 0-255 only. - asISO8559_1 = new String(asBytes, "ISO-8859-1"); - } catch (java.io.UnsupportedEncodingException never) { - // these 2 encodings are required by all java implementations - // so this exception will never happen. - ; - } - - StringBuilder result = new StringBuilder(asISO8559_1.length()); - - // now do the % encoding for all chars which need it. - for (int eachChar = 0; eachChar < asISO8559_1.length(); eachChar++) { - char aChar = asISO8559_1.charAt(eachChar); - - // null char is bad - if (0 == aChar) { - throw new IllegalArgumentException("URN string cannot contain null char"); - } - - // in the excluded range - if ((aChar <= 32) || (aChar >= 127)) { - result.append('%'); - result.append(toHexDigits((byte) aChar)); - } else { - int inSpecials = needsEncoding.indexOf(aChar); - - // one of the special chars which must be encoded? - if (-1 != inSpecials) { - result.append('%'); - result.append(toHexDigits(encodesTo[inSpecials])); - } else { - result.append(aChar); - } // needed no encoding - } - } - - return result.toString(); - } - - /** - * Converts a string which was previously conveted to URN format back into - * the unencoded format. - * - * @param source the string to decode - * @return String containing the decoded form of the URN. - **/ - public static String decodeURN(String source) { - StringBuilder result = new StringBuilder(source.length()); - - // remove the % encoding for all chars which needed it. - for (int eachChar = 0; eachChar < source.length(); eachChar++) { - char aChar = source.charAt(eachChar); - - if ('%' != aChar) { - result.append(aChar); - } else { - String twoChars = source.substring(eachChar + 1, eachChar + 3); - - result.append((char) Integer.parseInt(twoChars, 16)); - eachChar += 2; - } - } - String fromUTF8 = null; - - try { - // first we get its bytes using ISO-8859-1 to encode its characters. - // ISO-8859-1 does no mapping. Each byte is the same as the character. - byte[] asBytes = result.toString().getBytes("ISO-8859-1"); - - // then read it back in as UTF8. This gets us any high byte chars back - fromUTF8 = new String(asBytes, "UTF8"); - } catch (java.io.UnsupportedEncodingException never) { - // these 2 encodings are required so this exception will never happen - ; - } - return fromUTF8; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.document.Advertisement b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.document.Advertisement deleted file mode 100644 index 1efce7a4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.document.Advertisement +++ /dev/null @@ -1,23 +0,0 @@ -# The list of Advertisement Instance Classes included with this distribution. -# Used by AdvertisementFactory -net.jxta.impl.protocol.PeerAdv -net.jxta.impl.protocol.PlatformConfig -net.jxta.impl.protocol.PeerGroupAdv -net.jxta.impl.protocol.PeerGroupConfigAdv -net.jxta.impl.protocol.TCPAdv -net.jxta.impl.protocol.HTTPAdv -net.jxta.impl.protocol.PSEConfigAdv -net.jxta.impl.protocol.RdvConfigAdv -net.jxta.impl.protocol.DiscoveryConfigAdv -net.jxta.impl.protocol.PipeAdv -net.jxta.impl.protocol.RelayConfigAdv -net.jxta.impl.protocol.RdvAdv -net.jxta.impl.protocol.ModuleImplAdv -net.jxta.impl.protocol.ModuleSpecAdv -net.jxta.impl.protocol.ModuleClassAdv -net.jxta.impl.protocol.RouteAdv -net.jxta.impl.protocol.AccessPointAdv -net.jxta.impl.protocol.SignedAdv -net.jxta.impl.protocol.GroupConfig - -org.linphone.p2pproxy.core.P2pUserProfileAdvertisement \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.document.StructuredDocument b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.document.StructuredDocument deleted file mode 100644 index 443209e1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.document.StructuredDocument +++ /dev/null @@ -1,4 +0,0 @@ -# The list of StructuredDocument Instance Classes included in this distribution. -# Used by StructuredDocumentFactory. -net.jxta.impl.document.PlainTextDocument -net.jxta.impl.document.LiteXMLDocument diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.endpoint.WireFormatMessage b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.endpoint.WireFormatMessage deleted file mode 100644 index d056a120..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.endpoint.WireFormatMessage +++ /dev/null @@ -1,3 +0,0 @@ -# The list of MessageWireFormat Instance Classes included in this distribution. -# Used by MessageWireFormatFactory. -net.jxta.impl.endpoint.WireFormatMessageBinary diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.id.ID b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.id.ID deleted file mode 100644 index 0b61d945..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.id.ID +++ /dev/null @@ -1,4 +0,0 @@ -# List of ID types supported. -net.jxta.impl.id.UUID.IDFormat -net.jxta.impl.id.CBID.IDFormat -net.jxta.impl.id.binaryID.IDFormat diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.platform.Module b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.platform.Module deleted file mode 100644 index 1cd8292e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/META-INF/services/net.jxta.platform.Module +++ /dev/null @@ -1,31 +0,0 @@ -# The list of Builtin Module Implementation Classes included with this distribution. -# Used by PeerGroup Implementation. - -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000020106 net.jxta.impl.resolver.ResolverServiceImpl Reference Implementation of the Resolver service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000030106 net.jxta.impl.discovery.DiscoveryServiceImpl Reference Implementation of the Discovery service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000040106 net.jxta.impl.pipe.PipeServiceImpl Reference Implementation of the Pipe Service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000050106 net.jxta.impl.membership.none.NoneMembershipService None Membership Service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000050206 net.jxta.impl.membership.passwd.PasswdMembershipService Password Membership Service. -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000050306 net.jxta.impl.membership.pse.PSEMembershipService PSE Membership Service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000060106 net.jxta.impl.rendezvous.RendezVousServiceImpl Reference Implementation of the Rendezvous Service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000070106 net.jxta.impl.peer.PeerInfoServiceImpl Reference Implementation of the Peerinfo Service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000080106 net.jxta.impl.endpoint.EndpointServiceImpl Reference Implementation of the Endpoint service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000090106 net.jxta.impl.endpoint.tcp.TcpTransport Reference Implementation of the TCP Message Transport -urn:jxta:uuid-deadbeefdeafbabafeedbabe0000000A0106 net.jxta.impl.endpoint.servlethttp.ServletHttpTransport Reference Implementation of the HTTP Message Transport -urn:jxta:uuid-deadbeefdeafbabafeedbabe0000000B0106 net.jxta.impl.endpoint.router.EndpointRouter Reference Implementation of the Router Message Transport -urn:jxta:uuid-deadbeefdeafbabafeedbabe0000000D0106 net.jxta.impl.endpoint.tls.TlsTransport Reference Implementation of the TLS Message Transport -urn:jxta:uuid-deadbeefdeafbabafeedbabe0000000E0106 net.jxta.impl.proxy.ProxyService Reference Implementation of the JXME Proxy Service -urn:jxta:uuid-deadbeefdeafbabafeedbabe0000000F0106 net.jxta.impl.endpoint.relay.RelayTransport Reference Implementation of the Relay Message Transport -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000100106 net.jxta.impl.access.always.AlwaysAccessService Always Access Service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000100206 net.jxta.impl.access.simpleACL.SimpleACLAccessService Simple ACL Access Service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000100306 net.jxta.impl.access.pse.PSEAccessService PSE Access Service -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000110106 net.jxta.impl.endpoint.cbjx.CbJxTransport Reference Implementation of the Cryptobased-ID Message Transport -urn:jxta:uuid-0C801F65D38F421C9884D706B337B8110106 net.jxta.impl.endpoint.mcast.McastTransport Reference Implementation of the IP Multicast Message Transport - -# Since the peer groups refer to other modules in their ModuleImplAdvertisements it's necessary to load them last. - -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000010106 net.jxta.impl.peergroup.Platform Standard World PeerGroup Reference Implementation -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000010206 net.jxta.impl.peergroup.ShadowPeerGroup Default Network PeerGroup Reference Implementation -urn:jxta:uuid-deadbeefdeafbabafeedbabe000000010306 net.jxta.impl.peergroup.StdPeerGroup General Purpose Peer Group Implementation - - \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/Version.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/Version.java deleted file mode 100644 index 1762978f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/Version.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * - * ==================================================================== - * - * Copyright (c) 2001 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl; - -import java.lang.Package; - -/** - * Provides easy access to Java Package information for the JXSE Implementation. - */ -public final class Version { - - /** - * Returns the package. - * - * @return The specification title. - */ - public static Package getPackage() { - return Version.class.getPackage(); - } - - /** - * Returns the specification title. - * - * @return The specification title. - */ - public static String getSpecTitle() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getSpecificationTitle(); - } - - /** - * Returns the specification vendor. - * - * @return The specification vendor. - */ - public static String getSpecVendor() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getSpecificationVendor(); - } - - /** - * Returns the specification version. - * - * @return The specification version. - */ - public static String getSpecVersion() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getSpecificationVersion(); - } - - /** - * Returns the specification title. - * - * @return The specification title. - */ - public static String getImplTitle() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getImplementationTitle(); - } - - /** - * Returns the specification vendor. - * - * @return The specification vendor. - */ - public static String getImplVendor() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getImplementationVendor(); - } - - /** - * Returns the specification version. - * - * @return The specification version. - */ - public static String getImplVersion() { - Package versionPackage = Version.class.getPackage(); - - return versionPackage.getImplementationVersion(); - } - - /** - * This class is a singleton. - */ - private Version() { - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/AccessList.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/AccessList.java deleted file mode 100644 index 2ffec1b6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/AccessList.java +++ /dev/null @@ -1,563 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.access; - - -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLElement; -import net.jxta.document.XMLDocument; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.UndeclaredThrowableException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - - -/** - * Manages Access Permissions. - */ -public class AccessList { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(AccessList.class.getName()); - - private final static String PEER_TAG = "peer"; - private final static String NAME_TAG = "name"; - private final static String DESCRIPTION_TAG = "description"; - private final static String GRANTALL_TAG = "grantAll"; - private final static String ACCESS_TAG = "access"; - private final static String ACCESS_TAG_DENY_VALUE = "deny"; - private final static String ACCESS_TAG_GRANT_VALUE = "grant"; - - protected final Map accessMap = new HashMap(); - - String description = null; - boolean grantAll = false; - - /** - * Default Constructor - */ - public AccessList() {} - - /** - * Initialize access list from an InputStream - * - * @param stream the input stream - * @throws java.io.IOException if an io error occurs - */ - public AccessList(InputStream stream) throws IOException { - init(stream); - } - - /** - * Initialize access list from a URI - *

      - * e.g. file:/export/dist/acl.xml, e.g. http://configserver.net/edge.acl - * - * @param uri the URI to the access control list - * @throws IOException if an i/o error occurs - */ - public AccessList(URI uri) throws IOException { - init(uri); - } - - /** - * Initialize the access list from a URI - * - * @param uri the refresh URI - * @throws IOException if an io error occurs - */ - public void init(URI uri) throws IOException { - InputStream input = getInputStream(uri); - - init(input); - input.close(); - } - - /** - * Initialize access list from a file - * - * @param fromFile file to init from - * @throws IOException if an io error occurs - */ - public void init(File fromFile) throws IOException { - InputStream is = new FileInputStream(fromFile); - - init(is); - is.close(); - } - - /** - * Refresh access list from a file - * - * @param file file to refresh from - * @deprecated use URI variant - */ - @Deprecated - public void refresh(File file) { - if (file.exists()) { - try { - InputStream is = new FileInputStream(file); - - refresh(is); - is.close(); - } catch (IOException io) {// bad input - } - } - } - - /** - * refresh the access list from a stream - * - * @param stream the input stream - * @throws IOException if an io error occurs - */ - public void refresh(InputStream stream) throws IOException { - AccessList tmp = new AccessList(stream); - - refresh(tmp); - } - - /** - * refresh the access list from a URI - * - * @param uri the refresh URI - * @throws IOException if an io error occurs - */ - public void refresh(URI uri) throws IOException { - InputStream input = getInputStream(uri); - AccessList tmp = new AccessList(input); - - refresh(tmp); - input.close(); - } - - private InputStream getInputStream(URI uri) throws IOException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Loading ACL : " + uri.toString()); - } - - URL url = uri.toURL(); - - URLConnection connection = url.openConnection(); - - connection.setDoInput(true); - return connection.getInputStream(); - } - - private void init(InputStream stream) throws IOException { - XMLDocument doc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, stream); - - initialize(doc); - } - - /** - * @param map The map of addresses and permissions. - */ - public AccessList(Map map) { - this.accessMap.clear(); - this.accessMap.putAll(map); - } - - /** - * Construct from a StructuredDocument - * - * @param root root element - */ - public AccessList(Element root) { - if (!(root instanceof XMLElement)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - - if (!getAdvertisementType().equals(doc.getName())) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - initialize(doc); - } - - /** - * gets the description of this access control - * - * @return the document description - */ - public String getDescrption() { - return description; - } - - /** - * Determine if all access is granted. - * - * @return If {@code true} then all access requests will be granted. - */ - public boolean getGrantAll() { - return grantAll; - } - - /** - * Allows/denies all access - * - * @param grantAll If {@code true} then all access requests will be granted. - */ - public void setGrantAll(boolean grantAll) { - this.grantAll = grantAll; - } - - /** - * sets the ACL description - * - * @param description The new description - */ - public void setDescrption(String description) { - this.description = description; - } - - /** - * sets the entries list - * - * @param map The new access map - */ - protected void setEntries(Map map) { - accessMap.clear(); - accessMap.putAll(map); - } - - /** - * Refreshes the access list - * - * @param acl The access list to refresh from - */ - private void refresh(AccessList acl) { - grantAll = acl.grantAll; - description = acl.description; - accessMap.clear(); - accessMap.putAll(acl.accessMap); - } - - /** - * Adds an ACL entry - * - * @param entry the entry to add - */ - public void add(Entry entry) { - if (!accessMap.containsKey(entry.id)) { - accessMap.put(entry.id, entry); - } - } - - /** - * Removes an ACL entry - * - * @param entry the entry to remove - */ - public void remove(Entry entry) { - if (accessMap.containsKey(entry.id)) { - accessMap.remove(entry.id); - } - } - - /** - * Determines if an entry has access - * - * @param id the PeerID - * @return ture if access is allowed, always true if grantAll is set - */ - public boolean isAllowed(ID id) { - if (grantAll) { - return true; - } else if (accessMap.containsKey(id)) { - Entry entry = accessMap.get(id); - - return entry.access; - } else { - return false; - } - } - - /** - * gets the entries list - * - * @return List The List containing Entries - */ - public Map getAccessMap() { - return accessMap; - } - - /** - * Returns the Document - * - * @param asMimeType mime type encoding - * @return The document value - */ - public Document getDocument(MimeMediaType asMimeType) { - StructuredDocument adv = StructuredDocumentFactory.newStructuredDocument(asMimeType, getAdvertisementType()); - - if (adv instanceof XMLDocument) { - ((XMLDocument) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - Element e; - - if (grantAll) { - e = adv.createElement(GRANTALL_TAG, Boolean.valueOf(grantAll).toString()); - adv.appendChild(e); - } - - if (description != null) { - e = adv.createElement(DESCRIPTION_TAG, description); - adv.appendChild(e); - } - - for (Object o : accessMap.values()) { - Entry entry = (Entry) o; - - if (entry.id == null && entry.name == null) { - // skip bad entries - continue; - } - e = adv.createElement(PEER_TAG, entry.id.toString()); - adv.appendChild(e); - ((Attributable) e).addAttribute(NAME_TAG, entry.name); - if (entry.access) { - ((Attributable) e).addAttribute(ACCESS_TAG, ACCESS_TAG_GRANT_VALUE); - } else { - ((Attributable) e).addAttribute(ACCESS_TAG, ACCESS_TAG_DENY_VALUE); - } - } - return adv; - } - - /** - * Process an individual element from the document. - * - * @param doc the element - */ - protected void initialize(XMLElement doc) { - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (GRANTALL_TAG.equals(elem.getName())) { - grantAll = Boolean.getBoolean(elem.getTextValue()); - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Grant all access = [ " + grantAll + " ]"); - } - - continue; - } - - if (DESCRIPTION_TAG.equals(elem.getName())) { - description = elem.getTextValue(); - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Loading [ " + description + " ] access list :"); - } - - continue; - } - - if (PEER_TAG.equals(elem.getName())) { - String name = "NA"; - Attribute nameAttr = elem.getAttribute(NAME_TAG); - - if (nameAttr != null) { - name = nameAttr.getValue(); - } - String access = ACCESS_TAG_GRANT_VALUE; - Attribute accessAttr = elem.getAttribute(ACCESS_TAG); - - if (accessAttr != null) { - access = accessAttr.getValue(); - } - boolean acl = ACCESS_TAG_GRANT_VALUE.equalsIgnoreCase(access); - - ID pid; - - try { - URI id = new URI(elem.getTextValue().trim()); - - pid = IDFactory.fromURI(id); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("unknown ID format in advertisement: " + elem.getTextValue()); - } - - Entry entry = new Entry(pid, name, acl); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Adding entry to access list :" + entry); - } - - accessMap.put(entry.id, entry); - - continue; - } - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unrecognized tag : " + elem.getName()); - } - } - } - - /** - * returns the document string representation of this object - * - * @return String representation of the of this message type - */ - @Override - public String toString() { - - try { - XMLDocument doc = (XMLDocument) getDocument(MimeMediaType.XMLUTF8); - - return doc.toString(); - } catch (Throwable e) { - if (e instanceof Error) { - throw (Error) e; - } else if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new UndeclaredThrowableException(e); - } - } - } - - /** - * All messages have a type (in xml this is !doctype) which - * identifies the message - * - * @return String "jxta:XACL" - */ - public static String getAdvertisementType() { - return "jxta:XACL"; - } - - /** - * Entries class - */ - public final static class Entry { - - /** - * Entry ID entry id - */ - public final ID id; - - /** - * Entry name - */ - public final String name; - - /** - * Entry name - */ - public final boolean access; - - /** - * Creates a Entry with id and name - * - * @param id id - * @param name node name - * @param access access control - */ - - public Entry(ID id, String name, boolean access) { - this.id = id; - this.name = name; - this.access = access; - } - - @Override - public String toString() { - return "[" + name + " access = " + access + " : " + id.toString() + "]"; - } - - @Override - public boolean equals(Object obj) { - return this == obj || (obj != null && id.equals(((Entry) obj).id)); - } - - @Override - public int hashCode() { - return id.hashCode(); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/always/AlwaysAccessService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/always/AlwaysAccessService.java deleted file mode 100644 index 0f7e55fb..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/always/AlwaysAccessService.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.access.always; - - -import java.net.URI; -import java.util.Enumeration; - -import java.net.URISyntaxException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.access.AccessService; -import net.jxta.credential.Credential; -import net.jxta.credential.PrivilegedOperation; -import net.jxta.document.Advertisement; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.TextElement; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.service.Service; - - -/** - * A minimal {@link net.jxta.access.AccessService} implementation. - * - *

      doAccessCheck will return PERMITTED to all - * queries when provided any valid credential and operation. - * - *

      If the subject of the Credential or the operation is equivalent to the - * String "DENY" then the operation will be DISALLOWED. - * - * @see net.jxta.access.AccessService - **/ -public class AlwaysAccessService implements AccessService { - - /** - * log4J Logger - **/ - private final static Logger LOG = Logger.getLogger(AlwaysAccessService.class.getName()); - - /** - * Operation for the Always Access Service. - **/ - private static class AlwaysOperation implements PrivilegedOperation { - - AlwaysAccessService source; - - String op; - - Credential offerer; - - protected AlwaysOperation(AlwaysAccessService source, String op, Credential offerer) { - this.source = source; - this.op = op; - this.offerer = offerer; - } - - protected AlwaysOperation(AlwaysAccessService source, Element root) { - this.source = source; - initialize(root); - } - - /** - * {@inheritDoc} - **/ - public ID getPeerGroupID() { - return source.getPeerGroup().getPeerGroupID(); - } - - /** - * {@inheritDoc} - **/ - public ID getPeerID() { - return null; - } - - /** - * {@inheritDoc} - * - *

      AlwaysOperation are always valid. - **/ - public boolean isExpired() { - return false; - } - - /** - * {@inheritDoc} - * - *

      AlwaysOperation are always valid. - **/ - public boolean isValid() { - return true; - } - - /** - * {@inheritDoc} - **/ - public Object getSubject() { - return op; - } - - /** - * {@inheritDoc} - **/ - public Service getSourceService() { - return source; - } - - /** - * {@inheritDoc} - **/ - public StructuredDocument getDocument(MimeMediaType as) throws Exception { - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(as, "jxta:Cred"); - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - ((Attributable) doc).addAttribute("xml:space", "preserve"); - ((Attributable) doc).addAttribute("type", "jxta:AlwaysOp"); - } - - Element e = doc.createElement("PeerGroupID", getPeerGroupID().toString()); - - doc.appendChild(e); - - e = doc.createElement("Operation", op); - doc.appendChild(e); - - StructuredDocumentUtils.copyElements(doc, doc, offerer.getDocument(as), "Offerer"); - - return doc; - } - - /** - * {@inheritDoc} - **/ - public Credential getOfferer() { - return offerer; - } - - /** - * Process an individual element from the document. - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - **/ - protected boolean handleElement(TextElement elem) { - if (elem.getName().equals("PeerGroupID")) { - try { - URI gID = new URI(elem.getTextValue().trim()); - ID pgid = IDFactory.fromURI(gID); - - if (!pgid.equals(getPeerGroupID())) { - throw new IllegalArgumentException( - "Operation is from a different group. " + pgid + " != " + getPeerGroupID()); - } - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad ID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a group id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("Operation")) { - op = elem.getTextValue(); - return true; - } - - if (elem.getName().equals("Offerer")) { - try { - offerer = source.getPeerGroup().getMembershipService().makeCredential(elem); - } catch (Throwable failed) { - throw new IllegalArgumentException("Offerer credential could not be constructed" + failed); - } - return true; - } - - // element was not handled - return false; - } - - /** - * Initialize from a portion of a structured document. - **/ - protected void initialize(Element root) { - - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports TextElement"); - } - - TextElement doc = (TextElement) root; - - String typedoctype = ""; - - if (root instanceof Attributable) { - Attribute itsType = ((Attributable) root).getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - } - - String doctype = doc.getName(); - - if (!doctype.equals("jxta:AlwaysOp") && !doctype.equals("jxta:Cred") || !"jxta:AlwaysOp".equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - TextElement elem = (TextElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandleded element \'" + elem.getName() + "\' in " + doc.getName()); - } - } - } - - // sanity check time! - - if (null == op) { - throw new IllegalArgumentException("operation was never initialized."); - } - - if (null == offerer) { - throw new IllegalArgumentException("offerer was never initialized."); - } - } - } - - PeerGroup group; - - ModuleImplAdvertisement implAdvertisement; - - /** - * Default Constructor - **/ - public AlwaysAccessService() {} - - /** - * {@inheritDoc} - **/ - public void init(PeerGroup group, ID assignedID, Advertisement implAdv) throws PeerGroupException { - implAdvertisement = (ModuleImplAdvertisement) implAdv; - this.group = group; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Always Access Service : " + assignedID); - - configInfo.append("\n\tImplementation:"); - configInfo.append("\n\t\tModule Spec ID: " + implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description: " + implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : " + implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : " + implAdvertisement.getCode()); - configInfo.append("\n\tGroup Params:"); - configInfo.append("\n\t\tGroup: " + group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID: " + group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID: " + group.getPeerID()); - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - **/ - public int startApp(String[] args) { - return 0; - } - - /** - * {@inheritDoc} - **/ - public void stopApp() {} - - /** - * {@inheritDoc} - **/ - public ModuleImplAdvertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * {@inheritDoc} - **/ - public AlwaysAccessService getInterface() { - return this; - } - - /** - * {@inheritDoc} - **/ - PeerGroup getPeerGroup() { - return group; - } - - /** - * {@inheritDoc} - **/ - public AccessResult doAccessCheck(PrivilegedOperation op, Credential cred) { - if (null == cred) { - return (null == op) - ? AccessResult.PERMITTED - : ("DENY".equals(op.getSubject()) ? AccessResult.DISALLOWED : AccessResult.PERMITTED); - } - - if (!cred.isValid()) { - return AccessResult.DISALLOWED; - } - - if ("DENY".equals(cred.getSubject())) { - return AccessResult.DISALLOWED; - } - - if (null == op) { - return AccessResult.PERMITTED; - } - - if (!op.isValid()) { - return AccessResult.DISALLOWED; - } - - return "DENY".equals(op.getSubject()) ? AccessResult.DISALLOWED : AccessResult.PERMITTED; - } - - /** - * {@inheritDoc} - **/ - public PrivilegedOperation newPrivilegedOperation(Object subject, Credential offerer) { - if (!(subject instanceof String)) { - throw new IllegalArgumentException(getClass().getName() + " only supports String subjects."); - } - - if (!offerer.isValid()) { - throw new IllegalArgumentException("offerer is not a valid credential"); - } - - return new AlwaysOperation(this, (String) subject, offerer); - } - - /** - * {@inheritDoc} - **/ - public PrivilegedOperation newPrivilegedOperation(Element source) { - return new AlwaysOperation(this, source); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/always/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/always/package.html deleted file mode 100644 index f66f65a2..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/always/package.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.access.AccessService} implementation which - provides minimal Access Service functionality. This implementation allows - all operations involving valid operations and credentials to succeed with - the exception of a single special value used for testing. - - @see net.jxta.access.AccessService - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/pse/PSEAccessService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/pse/PSEAccessService.java deleted file mode 100644 index 4140ad2a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/pse/PSEAccessService.java +++ /dev/null @@ -1,495 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.access.pse; - - -import java.net.URI; -import java.security.cert.CertPath; -import java.security.cert.CertPathValidator; -import java.security.cert.TrustAnchor; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; - -import java.net.URISyntaxException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.access.AccessService; -import net.jxta.credential.Credential; -import net.jxta.credential.PrivilegedOperation; -import net.jxta.document.Advertisement; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.TextElement; -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.JxtaError; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.membership.MembershipService; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.ModuleSpecID; -import net.jxta.platform.Module; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.service.Service; - -import net.jxta.impl.membership.pse.PSECredential; -import net.jxta.impl.membership.pse.PSEMembershipService; - - -/** - * Implements the {@link net.jxta.access.AccessService} using PKIX validation. - * - * FIXME 20060409 bondolo THIS IS AN EARLY DEVELOPMENT RELEASE FOR INVESTIGATING - * THE API. IT IS *NOT* SECURE! DO NOT SHIP THIS CODE (IN IT'S CURRENT FORM) IN - * A REAL PRODUCT. - * - * @see net.jxta.access.AccessService - * @see net.jxta.impl.membership.pse.PSEMembershipService - */ -public class PSEAccessService implements AccessService { - - /** - * Logger. - */ - private final static Logger LOG = Logger.getLogger(PSEAccessService.class.getName()); - - /** - * Well known access specification identifier: the pse access service - */ - public final static ModuleSpecID PSE_ACCESS_SPEC_ID = (ModuleSpecID) - ID.create(URI.create("urn:jxta:uuid-DeadBeefDeafBabaFeedBabe000000100306")); - - /** - * Operation for the PSE Access Service. - */ - private static class PSEOperation implements PrivilegedOperation { - - final PSEAccessService source; - - PSECredential op; - - protected PSEOperation(PSEAccessService source, PSECredential op) { - this.source = source; - this.op = op; - } - - protected PSEOperation(PSEAccessService source, Element root) { - this.source = source; - initialize(root); - } - - /** - * {@inheritDoc} - */ - public ID getPeerGroupID() { - return source.getPeerGroup().getPeerGroupID(); - } - - /** - * {@inheritDoc} - */ - public ID getPeerID() { - return null; - } - - /** - * {@inheritDoc} - * - *

      AlwaysOperation are always valid. - */ - public boolean isExpired() { - return false; - } - - /** - * {@inheritDoc} - * - *

      AlwaysOperation are always valid. - */ - public boolean isValid() { - return true; - } - - /** - * {@inheritDoc} - */ - public PSECredential getSubject() { - return op; - } - - /** - * {@inheritDoc} - */ - public Service getSourceService() { - return source; - } - - /** - * {@inheritDoc} - * - * FIXME 20060317 bondolo This implementation is not secure. The - * operation should be signed by the offerer. - */ - public StructuredDocument getDocument(MimeMediaType as) throws Exception { - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(as, "jxta:Cred"); - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - ((Attributable) doc).addAttribute("xml:space", "preserve"); - ((Attributable) doc).addAttribute("type", "jxta:PSEOp"); - } - - Element e = doc.createElement("PeerGroupID", getPeerGroupID().toString()); - - doc.appendChild(e); - - e = doc.createElement("Operation", op); - doc.appendChild(e); - - return doc; - } - - /** - * {@inheritDoc} - */ - public PSECredential getOfferer() { - return null; - } - - /** - * Process an individual element from the document. - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - */ - protected boolean handleElement(TextElement elem) { - if (elem.getName().equals("PeerGroupID")) { - try { - URI gID = new URI(elem.getTextValue().trim()); - ID pgid = IDFactory.fromURI(gID); - - if (!pgid.equals(getPeerGroupID())) { - throw new IllegalArgumentException( - "Operation is from a different group. " + pgid + " != " + getPeerGroupID()); - } - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Unusable ID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a group id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("Operation")) { - op = (PSECredential) source.pseMembership.makeCredential(elem); - - return true; - } - - // element was not handled - return false; - } - - /** - * Intialize from a portion of a structured document. - */ - protected void initialize(Element root) { - - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports TextElement"); - } - - TextElement doc = (TextElement) root; - - String typedoctype = ""; - - if (root instanceof Attributable) { - Attribute itsType = ((Attributable) root).getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - } - - String doctype = doc.getName(); - - if (!doctype.equals("jxta:PSEOp") && !typedoctype.equals("jxta:PSEOp")) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - TextElement elem = (TextElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled element \'" + elem.getName() + "\' in " + doc.getName()); - } - } - } - - // sanity check time! - - if (null == op) { - throw new IllegalArgumentException("operation was never initialized."); - } - } - } - - /** - * The Peer Group we are working for. - */ - PeerGroup group; - - /** - * Implementation advertisement for this instance. - */ - ModuleImplAdvertisement implAdvertisement; - - /** - * The PSE Membership service we are paired with. - */ - PSEMembershipService pseMembership; - - /** - * If {@code true} then a null credential will be allowed for the null op. - */ - final boolean allowNullCredentialForNullOperation = false; - - /** - * The default constructor - */ - public PSEAccessService() {} - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement implAdv) throws PeerGroupException { - this.group = group; - implAdvertisement = (ModuleImplAdvertisement) implAdv; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring PSE Access Service : " + assignedID); - - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: " + implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : " + implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : " + implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : " + implAdvertisement.getCode()); - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : " + group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID : " + group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID : " + group.getPeerID()); - - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] args) { - MembershipService membership = group.getMembershipService(); - - if (null == membership) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a membership service"); - } - - return Module.START_AGAIN_STALLED; - } - - ModuleImplAdvertisement membershipImplAdv = (ModuleImplAdvertisement) membership.getImplAdvertisement(); - - if ((null != membershipImplAdv) && PSEMembershipService.pseMembershipSpecID.equals(membershipImplAdv.getModuleSpecID()) - && (membership instanceof PSEMembershipService)) { - pseMembership = (PSEMembershipService) membership; - } else { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("PSE Access Service requires a PSE Membership Service."); - } - - return -1; - } - - return 0; - } - - /** - * {@inheritDoc} - */ - public void stopApp() { - pseMembership = null; - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * {@inheritDoc} - */ - public Service getInterface() { - return this; - } - - /** - * {@inheritDoc} - */ - public AccessResult doAccessCheck(PrivilegedOperation op, Credential cred) { - if ((null == op) && (null == cred)) { - return allowNullCredentialForNullOperation ? AccessResult.PERMITTED : AccessResult.DISALLOWED; - } - - if ((null == cred) || !(cred instanceof PSECredential)) { - return AccessResult.DISALLOWED; - } - - if (!cred.isValid()) { - return AccessResult.DISALLOWED; - } - - if (null == op) { - return AccessResult.PERMITTED; - } - - if (!(op instanceof PSEOperation)) { - return AccessResult.DISALLOWED; - } - - if (op.getSourceService() != this) { - return AccessResult.DISALLOWED; - } - - if (!op.isValid()) { - return AccessResult.DISALLOWED; - } - - PSECredential offerer = ((PSEOperation) op).getOfferer(); - - X509Certificate opCerts[] = offerer.getCertificateChain(); - - X509Certificate credCerts[] = ((PSECredential) cred).getCertificateChain(); - - // FIXME 20060409 bondolo THIS IS NOT A VALID TEST. It is a shortcut for - // PKIX validation and assumes that all presented certificates chains - // are valid and trustworthy. IT IS NOT SECURE. (It does not ensure that - // certficiates are really signed by their claimed issuer.) - for (X509Certificate credCert : Arrays.asList(credCerts)) { - for (X509Certificate opCert : Arrays.asList(opCerts)) { - if (credCert.getPublicKey().equals(opCert.getPublicKey())) { - return AccessResult.PERMITTED; - } - } - } - - return AccessResult.DISALLOWED; - } - - /** - * {@inheritDoc} - */ - public PrivilegedOperation newPrivilegedOperation(Object subject, Credential offerer) { - if (!(subject instanceof PSECredential)) { - throw new IllegalArgumentException(getClass().getName() + " only supports PSECredential subjects."); - } - - if (subject != offerer) { - throw new IllegalArgumentException("PSE Access Service requires operation and offerer to be the same object."); - } - - if (!offerer.isValid()) { - throw new IllegalArgumentException("offerer is not a valid credential"); - } - - return new PSEOperation((PSEAccessService) getInterface(), (PSECredential) offerer); - } - - /** - * {@inheritDoc} - */ - public PrivilegedOperation newPrivilegedOperation(Element source) { - return new PSEOperation((PSEAccessService) getInterface(), source); - } - - /** - * {@inheritDoc} - */ - PeerGroup getPeerGroup() { - return group; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/pse/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/pse/package.html deleted file mode 100644 index 90177d2a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/pse/package.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.access.AccessService} implementation which - utilizes the PSE Membership service to make access control descisions. - -

      This Access Service is essentially an interface to PKIX Certificate - path validation. The trust anchor for the validation takes the place of the - The privledged operation for access determination. If the provided - credential cannot be validated against the provided trust anchor then the - operation will be disallowed. - - @see net.jxta.access.AccessService - @see net.jxta.impl.membership.pse.PSEMembershipService - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/simpleACL/SimpleACLAccessService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/simpleACL/SimpleACLAccessService.java deleted file mode 100644 index dccb3f1a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/simpleACL/SimpleACLAccessService.java +++ /dev/null @@ -1,525 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.access.simpleACL; - - -import java.net.URI; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; - -import java.net.URISyntaxException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.access.AccessService; -import net.jxta.credential.Credential; -import net.jxta.credential.PrivilegedOperation; -import net.jxta.document.Advertisement; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.TextElement; -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.JxtaError; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.service.Service; - - -/** - * Implements the {@link net.jxta.access.AccessService} using a simple ACL - * scheme. - * - *

      The ACL table is read from the group advertisement. Each - * perm entry of the Access Service parameters in the group adv is - * assumed to be a permission in the following format: - * - *

      - *    <operation> ":" ( <identity> )* ( "," <identity> )*
      - * 
      - * - *

      A sample ACL table extracted from a PeerGroupAdvertisement: - * - *

      - * ...
      - * <Svc>
      - *   <MCID>urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE0000001005</MCID>
      - *   <Parm>
      - *     <perm>&lt;&lt;DEFAULT>>:nobody,permit</perm>
      - *     <perm>everyone:&lt;&lt;ALL>></perm>
      - *     <perm>permit:nobody,permit,allow</perm>
      - *     <perm>deny:notpermit,notallow</perm>
      - *   </Parm>
      - * </Svc>
      - * ...
      - * 
      - * - *

      If <<ALL>> is provided as an identity then the - * operation is permitted for all valid credentials. - * - *

      if <<DEFAULT>> is provided as an operation then the - * provided identities will be allowed for all operations which are not - * recognized. - * - *

      This implementation makes no effort to ensure that the - * permission table has not been altered. It is not appropriate for use - * in security sensitive deployments unless the integrity of the group - * advertisement is ensured. - * - * @see net.jxta.access.AccessService - **/ -public class SimpleACLAccessService implements AccessService { - - /** - * Logger. - **/ - private final static Logger LOG = Logger.getLogger(SimpleACLAccessService.class.getName()); - - /** - * Well known access specification identifier: the simple ACL access service - **/ - public static final ModuleSpecID simpleACLAccessSpecID = (ModuleSpecID) - ID.create(URI.create("urn:jxta:uuid-DeadBeefDeafBabaFeedBabe000000100206")); - - /** - * Operation for the Always Access Service. - **/ - private static class SimpleACLOperation implements PrivilegedOperation { - - SimpleACLAccessService source; - - String op; - - Credential offerer; - - protected SimpleACLOperation(SimpleACLAccessService source, String op, Credential offerer) { - this.source = source; - this.op = op; - this.offerer = offerer; - } - - protected SimpleACLOperation(SimpleACLAccessService source, Element root) { - this.source = source; - initialize(root); - } - - /** - * {@inheritDoc} - **/ - public ID getPeerGroupID() { - return source.getPeerGroup().getPeerGroupID(); - } - - /** - * {@inheritDoc} - **/ - public ID getPeerID() { - return null; - } - - /** - * {@inheritDoc} - * - *

      AlwaysOperation are always valid. - **/ - public boolean isExpired() { - return false; - } - - /** - * {@inheritDoc} - * - *

      AlwaysOperation are always valid. - **/ - public boolean isValid() { - return true; - } - - /** - * {@inheritDoc} - **/ - public String getSubject() { - return op; - } - - /** - * {@inheritDoc} - **/ - public Service getSourceService() { - return source; - } - - /** - * {@inheritDoc} - **/ - public StructuredDocument getDocument(MimeMediaType as) throws Exception { - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(as, "jxta:Cred"); - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - ((Attributable) doc).addAttribute("xml:space", "preserve"); - ((Attributable) doc).addAttribute("type", "jxta:SimpleACLOp"); - } - - Element e = doc.createElement("PeerGroupID", getPeerGroupID().toString()); - - doc.appendChild(e); - - e = doc.createElement("Operation", op); - doc.appendChild(e); - - StructuredDocumentUtils.copyElements(doc, doc, offerer.getDocument(as), "Offerer"); - - return doc; - } - - /** - * {@inheritDoc} - **/ - public Credential getOfferer() { - return offerer; - } - - /** - * Process an individual element from the document. - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - **/ - protected boolean handleElement(TextElement elem) { - if (elem.getName().equals("PeerGroupID")) { - try { - URI gID = new URI(elem.getTextValue().trim()); - ID pgid = IDFactory.fromURI(gID); - - if (!pgid.equals(getPeerGroupID())) { - throw new IllegalArgumentException( - "Operation is from a different group. " + pgid + " != " + getPeerGroupID()); - } - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Unusable ID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a group id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("Operation")) { - op = elem.getTextValue(); - return true; - } - - if (elem.getName().equals("Offerer")) { - try { - offerer = source.getPeerGroup().getMembershipService().makeCredential(elem); - } catch (Throwable failed) { - throw new IllegalArgumentException("Offerer credential could not be constructed" + failed); - } - return true; - } - - // element was not handled - return false; - } - - /** - * Initialize from a portion of a structured document. - **/ - protected void initialize(Element root) { - - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports TextElement"); - } - - TextElement doc = (TextElement) root; - - String typedoctype = ""; - - if (root instanceof Attributable) { - Attribute itsType = ((Attributable) root).getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - } - - String doctype = doc.getName(); - - if (!doctype.equals("jxta:SimpleACLOp") && !typedoctype.equals("jxta:SimpleACLOp")) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - TextElement elem = (TextElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled element \'" + elem.getName() + "\' in " + doc.getName()); - } - } - } - - // sanity check time! - - if (null == op) { - throw new IllegalArgumentException("operation was never initialized."); - } - - if (null == offerer) { - throw new IllegalArgumentException("offerer was never initialized."); - } - } - } - - /** - * The peer group we are working for. - **/ - PeerGroup group; - - /** - * Implementation advertisement for this instance. - **/ - ModuleImplAdvertisement implAdvertisement; - - /** - * The ACLs we are supporting. - **/ - private final Map> ACLs = new HashMap>(); - - /** - * The default constructor - **/ - public SimpleACLAccessService() {} - - /** - * {@inheritDoc} - **/ - public void init(PeerGroup group, ID assignedID, Advertisement implAdv) throws PeerGroupException { - this.group = group; - implAdvertisement = (ModuleImplAdvertisement) implAdv; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Access Service : " + assignedID); - - configInfo.append("\n\tImplementation:"); - configInfo.append("\n\t\tImpl Description: " + implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : " + implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : " + implAdvertisement.getCode()); - configInfo.append("\n\tGroup Params:"); - configInfo.append("\n\t\tGroup: " + group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID: " + group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID: " + group.getPeerID()); - LOG.config(configInfo.toString()); - } - - PeerGroupAdvertisement configAdv = group.getPeerGroupAdvertisement(); - - TextElement myParam = (TextElement) configAdv.getServiceParam(assignedID); - - if (null == myParam) { - throw new PeerGroupException("parameters for group access controls missing."); - } - - Enumeration allACLS = myParam.getChildren(); - - while (allACLS.hasMoreElements()) { - TextElement anACL = (TextElement) allACLS.nextElement(); - - if (!anACL.getName().equals("perm")) { - continue; - } - - String etcPasswd = anACL.getTextValue(); - - int nextDelim = etcPasswd.indexOf(':'); - - if (-1 == nextDelim) { - continue; - } - - String operation = etcPasswd.substring(0, nextDelim).trim(); - - if ("<>".equals(operation)) { - operation = null; - } - - String identities = etcPasswd.substring(nextDelim + 1); - Set allowed = new HashSet(); - - StringTokenizer eachIdentity = new StringTokenizer(identities, ","); - - while (eachIdentity.hasMoreTokens()) { - String anIdentity = eachIdentity.nextToken().trim(); - - if ("<>".equals(anIdentity)) { - anIdentity = null; - } - - allowed.add(anIdentity); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Adding operation : \'" + ((null == operation) ? "<>" : operation) + "\' with " + allowed.size() - + " identities."); - } - - ACLs.put(operation, allowed); - } - } - - /** - * {@inheritDoc} - **/ - public int startApp(String[] args) { - return 0; - } - - /** - * {@inheritDoc} - **/ - public void stopApp() {} - - /** - * {@inheritDoc} - **/ - public ModuleImplAdvertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * {@inheritDoc} - **/ - public SimpleACLAccessService getInterface() { - return this; - } - - /** - * {@inheritDoc} - **/ - public AccessResult doAccessCheck(PrivilegedOperation op, Credential cred) { - if ((null != cred) && !cred.isValid()) { - return AccessResult.DISALLOWED; - } - - if ((null != op) && !op.isValid()) { - return AccessResult.DISALLOWED; - } - - Set allowed = ACLs.get((null != op) ? op.getSubject() : null); - - // do we know this operation? - if (null == allowed) { - // try the default permission - allowed = ACLs.get(null); - - if (null == allowed) { - return AccessResult.DISALLOWED; - } - } - - String credSubject = (null != cred) ? cred.getSubject().toString() : null; - - return (allowed.contains(credSubject) || allowed.contains(null)) ? AccessResult.PERMITTED : AccessResult.DISALLOWED; - } - - /** - * {@inheritDoc} - **/ - public PrivilegedOperation newPrivilegedOperation(Object subject, Credential offerer) { - if (!(subject instanceof String)) { - throw new IllegalArgumentException(getClass().getName() + " only supports String subjects."); - } - - if (!offerer.isValid()) { - throw new IllegalArgumentException("offerer is not a valid credential"); - } - - return new SimpleACLOperation(this, (String) subject, offerer); - } - - /** - * {@inheritDoc} - **/ - public PrivilegedOperation newPrivilegedOperation(Element source) { - return new SimpleACLOperation(this, source); - } - - /** - * {@inheritDoc} - **/ - PeerGroup getPeerGroup() { - return group; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/simpleACL/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/simpleACL/package.html deleted file mode 100644 index 724bf3b5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/access/simpleACL/package.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.access.AccessService} implementation which - provides basic Access Control List (ACL) functionality. Supports a static - ACL loaded from the Peer Group Advertisement. - - @see net.jxta.access.AccessService - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/Cm.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/Cm.java deleted file mode 100644 index 241d8c71..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/Cm.java +++ /dev/null @@ -1,1209 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.cm; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.XMLDocument; -import net.jxta.impl.util.JxtaHash; -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.xindice.core.DBException; -import net.jxta.impl.xindice.core.data.Key; -import net.jxta.impl.xindice.core.data.Record; -import net.jxta.impl.xindice.core.data.Value; -import net.jxta.impl.xindice.core.filer.BTreeCallback; -import net.jxta.impl.xindice.core.filer.BTreeFiler; -import net.jxta.impl.xindice.core.indexer.IndexQuery; -import net.jxta.impl.xindice.core.indexer.NameIndexer; -import net.jxta.logging.Logging; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.protocol.SrdiMessage; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.lang.reflect.UndeclaredThrowableException; -import java.math.BigInteger; -import java.net.URI; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This class implements a limited document caching mechanism - * intended to provide cache for services that have a need for cache - * to search and exchange jxta documents. - *

      - * Only Core Services are intended to use this mechanism. - */ -public final class Cm implements Runnable { - - /** - * Logger. - */ - private final static Logger LOG = Logger.getLogger(Cm.class.getName()); - - /** - * the name we will use for the base directory - */ - final File ROOTDIRBASE; - - /** - * adv types - */ - private static final String[] DIRNAME = {"Peers", "Groups", "Adv", "Raw"}; - - // garbage collect once an hour - public static final long DEFAULT_GC_MAX_INTERVAL = 1 * TimeUtils.ANHOUR; - - /* - * expiration db - */ - private BTreeFiler cacheDB = null; - private Indexer indexer = null; - private final static String databaseFileName = "advertisements"; - - private boolean stop = false; - - private boolean trackDeltas = false; - private final Map> deltaMap = new HashMap>(3); - - /** - * file descriptor for the root of the cm - */ - protected File rootDir; - - private Thread gcThread = null; - private long gcTime = 0; - private final long gcMinInterval = 1000L * 60L; - private long gcMaxInterval = DEFAULT_GC_MAX_INTERVAL; - - - private final int maxInconvenienceLevel = 1000; - private volatile int inconvenienceLevel = 0; - - /** - * Constructor for cm - * - * @param areaName the name of the cm sub-dir to create - *

      - * NOTE: Default garbage interval once an hour - * @param storeRoot store root dir - */ - public Cm(URI storeRoot, String areaName) { - // Default garbage collect once an hour - this(Thread.currentThread().getThreadGroup(), storeRoot, areaName, DEFAULT_GC_MAX_INTERVAL, false); - } - - /** - * Constructor for cm - * - * @param threadGroup the thread group - * @param storeRoot persistence location - * @param gcinterval garbage collect max interval - * @param trackDeltas when true deltas are tracked - * @param areaName storage area name - */ - public Cm(ThreadGroup threadGroup, URI storeRoot, String areaName, long gcinterval, boolean trackDeltas) { - this.trackDeltas = trackDeltas; - this.gcMaxInterval = gcinterval; - this.gcTime = System.currentTimeMillis() + gcMaxInterval; - - ROOTDIRBASE = new File(new File(storeRoot), "cm"); - - try { - rootDir = new File(ROOTDIRBASE, areaName); - rootDir = new File(rootDir.getAbsolutePath()); - if (!rootDir.exists()) { - // We need to create the directory - if (!rootDir.mkdirs()) { - throw new RuntimeException("Cm cannot create directory " + rootDir); - } - } - - /* - * to avoid inconsistent database state, it is highly recommended that - * checkpoint is true by default, which causes fd.sync() on every write - * operation. In transitory caches such as SrdiCache it makes perfect sense - */ - boolean chkPoint = true; - ResourceBundle jxtaRsrcs = ResourceBundle.getBundle("net.jxta.user"); - String checkpointStr = jxtaRsrcs.getString("impl.cm.defferedcheckpoint"); - - if (checkpointStr != null) { - chkPoint = !(checkpointStr.equalsIgnoreCase("true")); - } - - // Storage - cacheDB = new BTreeFiler(); - // no deffered checkpoint - cacheDB.setSync(chkPoint); - cacheDB.setLocation(rootDir.getAbsolutePath(), databaseFileName); - - if (!cacheDB.open()) { - cacheDB.create(); - // now open it - cacheDB.open(); - } - - // Index - indexer = new Indexer(chkPoint); - indexer.setLocation(rootDir.getAbsolutePath(), databaseFileName); - - if (!indexer.open()) { - indexer.create(); - // now open it - indexer.open(); - } - - if (System.getProperty("net.jxta.impl.cm.index.rebuild") != null) { - rebuildIndex(); - } - gcThread = new Thread(threadGroup, this, "CM GC Thread interval : " + gcMinInterval); - gcThread.setDaemon(true); - gcThread.start(); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Instantiated Cm for: " + rootDir.getAbsolutePath()); - } - } catch (DBException de) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Unable to Initialize databases", de); - } - throw new UndeclaredThrowableException(de, "Unable to Initialize databases"); - } catch (Throwable e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Unable to create Cm", e); - } - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else if (e instanceof Error) { - throw (Error) e; - } else { - throw new UndeclaredThrowableException(e, "Unable to create Cm"); - } - } - } - - @Override - public String toString() { - return "CM for " + rootDir.getAbsolutePath() + "[" + super.toString() + "]"; - } - - private static String getDirName(Advertisement adv) { - if (adv instanceof PeerAdvertisement) { - return DIRNAME[DiscoveryService.PEER]; - } else if (adv instanceof PeerGroupAdvertisement) { - return DIRNAME[DiscoveryService.GROUP]; - } - return DIRNAME[DiscoveryService.ADV]; - } - - /** - * Generates a random file name using doc hashcode - * - * @param doc to hash to generate a unique name - * @return String a random file name - */ - public static String createTmpName(StructuredTextDocument doc) { - try { - StringWriter out = new StringWriter(); - - doc.sendToWriter(out); - out.close(); - - JxtaHash digester = new JxtaHash(out.toString()); - BigInteger hash = digester.getDigestInteger(); - - if (hash.compareTo(BigInteger.ZERO) < 0) { - hash = hash.negate(); - } - return "cm" + hash.toString(16); - } catch (IOException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception creating tmp name: ", ex); - } - throw new IllegalStateException("Could not generate name from document"); - } - } - - /** - * Gets the list of all the files into the given folder - * - * @param dn contains the name of the folder - * @param threshold the max number of results - * @param expirations List to contain expirations - * @return List Strings containing the name of the - * files - */ - public List getRecords(String dn, int threshold, List expirations) { - return getRecords(dn, threshold, expirations, false); - } - - public synchronized List getRecords(String dn, int threshold, List expirations, boolean purge) { - List res = new ArrayList(); - - if (dn == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("null directory name"); - } - return res; - } else { - IndexQuery iq = new IndexQuery(IndexQuery.SW, new Value(dn)); - try { - cacheDB.query(iq, new SearchCallback(cacheDB, indexer, res, expirations, threshold, purge)); - } catch (DBException dbe) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Exception during getRecords(): ", dbe); - } - } catch (IOException ie) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Exception during getRecords(): ", ie); - } - } - return res; - } - } - - public void garbageCollect() { - // calling getRecords is good enough since it removes - // expired entries - Map map = indexer.getIndexers(); - Iterator it = map.keySet().iterator(); - long t0; - - while (it != null && it.hasNext()) { - t0 = System.currentTimeMillis(); - String indexName = (String) it.next(); - getRecords(indexName, Integer.MAX_VALUE, null, true); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Cm garbageCollect :" + indexName + " in :" + (System.currentTimeMillis() - t0)); - } - } - } - - /** - * Returns the relative time in milliseconds at which the file - * will expire. - * - * @param dn contains the name of the folder - * @param fn contains the name of the file - * @return the absolute time in milliseconds at which this - * document will expire. -1 is returned if the file is not - * recognized or already expired. - */ - public synchronized long getLifetime(String dn, String fn) { - try { - Key key = new Key(dn + "/" + fn); - Record record = cacheDB.readRecord(key); - - if (record == null) { - return -1; - } - Long life = (Long) record.getMetaData(Record.LIFETIME); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Lifetime for :" + fn + " " + life.toString()); - } - if (life < System.currentTimeMillis()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing expired record :" + fn); - } - try { - remove(dn, fn); - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Failed to remove record", e); - } - } - } - return TimeUtils.toRelativeTimeMillis(life); - } catch (DBException de) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to remove " + dn + "/" + fn, de); - } - return -1; - } - } - - /** - * Returns the maximum duration in milliseconds for which this - * document should cached by those other than the publisher. This - * value is either the cache lifetime or the remaining lifetime - * of the document, whichever is less. - * - * @param dn contains the name of the folder - * @param fn contains the name of the file - * @return number of milliseconds until the file expires or -1 if the - * file is not recognized or already expired. - */ - public synchronized long getExpirationtime(String dn, String fn) { - try { - Key key = new Key(dn + "/" + fn); - Record record = cacheDB.readRecord(key); - long expiration = calcExpiration(record); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Expiration for :" + fn + " " + expiration); - } - if (expiration < 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing expired record :" + fn); - } - try { - remove(dn, fn); - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Failed to remove record", e); - } - } - } - return expiration; - } catch (DBException de) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to get " + dn + "/" + fn, de); - } - return -1; - } - } - - /** - * Figures out expiration - * - * @param record record - * @return expiration in ms - */ - private static long calcExpiration(Record record) { - if (record == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Record is null returning expiration of -1"); - } - return -1; - } - Long exp = (Long) record.getMetaData(Record.EXPIRATION); - Long life = (Long) record.getMetaData(Record.LIFETIME); - long expiresin = life - System.currentTimeMillis(); - - if (expiresin <= 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - MessageFormat.format("Record expired lifetime : {0} expiration: {1} expires in: {2}", life, exp - , - expiresin)); - LOG.fine(MessageFormat.format("Record expires on :{0}", new Date(life))); - } - return -1; - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Record lifetime: {0} expiration: {1} expires in: {2}", life, exp, expiresin)); - LOG.fine(MessageFormat.format("Record expires on :{0}", new Date(life))); - } - return Math.min(expiresin, exp.longValue()); - } - } - - /** - * Returns the inputStream of a specified file, in a specified dir - * - * @param dn directory name - * @param fn file name - * @return The inputStream value - * @throws IOException if an I/O error occurs - */ - public InputStream getInputStream(String dn, String fn) throws IOException { - Key key = new Key(dn + "/" + fn); - try { - Record record = cacheDB.readRecord(key); - if (record == null) { - return null; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Restored record for " + key); - } - Value val = record.getValue(); - - if (val != null) { - return val.getInputStream(); - } else { - return null; - } - } catch (DBException de) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to restore record for " + key, de); - } - IOException failure = new IOException("Failed to restore record for " + key); - failure.initCause(de); - throw failure; - } - } - - /** - * Remove a file - * - * @param dn directory name - * @param fn file name - * @throws IOException if an I/O error occurs - */ - public synchronized void remove(String dn, String fn) throws IOException { - - try { - if (fn == null) { - return; - } - Key key = new Key(dn + "/" + fn); - Record record = cacheDB.readRecord(key); - long removePos = cacheDB.findValue(key); - - cacheDB.deleteRecord(key); - if (record != null) { - try { - if (calcExpiration(record) > 0) { - InputStream is = record.getValue().getInputStream(); - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, is); - Advertisement adv = AdvertisementFactory.newAdvertisement(asDoc); - Map indexables = getIndexfields(adv.getIndexFields(), asDoc); - - indexer.removeFromIndex(addKey(dn, indexables), removePos); - // add it to deltas to expire it in srdi - addDelta(dn, indexables, 0); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removed " + record); - } - } - } catch (Exception e) { - // bad bits we are done - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to remove " + dn + "/" + fn, e); - } - } - } - } catch (DBException de) { - // entry does not exist - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("failed to remove " + dn + "/" + fn); - } - } - } - - /** - * Restore a saved StructuredDocument. - * - * @param dn directory name - * @param fn file name - * @return StructuredDocument containing the file - * @throws IOException if an I/O error occurs - * was not possible. - */ - public StructuredDocument restore(String dn, String fn) throws IOException { - InputStream is = getInputStream(dn, fn); - return StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, is); - } - - /** - * Restore an advetisement into a byte array. - * - * @param dn directory name - * @param fn file name - * @return byte [] containing the file - * @throws IOException if an I/O error occurs - */ - public synchronized byte[] restoreBytes(String dn, String fn) throws IOException { - - try { - Key key = new Key(dn + "/" + fn); - Record record = cacheDB.readRecord(key); - - if (record == null) { - return null; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("restored " + record); - } - Value val = record.getValue(); - - if (val != null) { - return val.getData(); - } else { - return null; - } - } catch (DBException de) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to restore " + dn + "/" + fn, de); - } - IOException failure = new IOException("failed to restore " + dn + "/" + fn); - failure.initCause(de); - throw failure; - } - } - - /** - * Stores a StructuredDocument in specified dir, and file name - * - * @param dn directory name - * @param fn file name - * @param adv Advertisement to store - * @throws IOException if an I/O error occurs - */ - public void save(String dn, String fn, Advertisement adv) throws IOException { - save(dn, fn, adv, DiscoveryService.INFINITE_LIFETIME, DiscoveryService.NO_EXPIRATION); - } - - /** - * Stores a StructuredDocument in specified dir, and file name, and - * associated doc timeouts - * - * @param dn directory name - * @param fn file name - * @param adv Advertisement to save - * @param lifetime Document (local) lifetime in relative ms - * @param expiration Document (global) expiration time in relative ms - * @throws IOException Thrown if there is a problem saving the document. - */ - public synchronized void save(String dn, String fn, Advertisement adv, long lifetime, long expiration) throws IOException { - - try { - if (expiration < 0 || lifetime <= 0) { - throw new IllegalArgumentException("Bad expiration or lifetime."); - } - XMLDocument doc; - - try { - doc = (XMLDocument) adv.getDocument(MimeMediaType.XMLUTF8); - } catch (RuntimeException e) { - IOException failure = new IOException("Advertisement couldn't be saved"); - failure.initCause(e); - throw failure; - } - - Key key = new Key(dn + "/" + fn); - // save the new version - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - doc.sendToStream(baos); - baos.close(); - Value value = new Value(baos.toByteArray()); - Long oldLife = null; - Record record = cacheDB.readRecord(key); - - if (record != null) { - // grab the old lifetime - oldLife = (Long) record.getMetaData(Record.LIFETIME); - } - - long absoluteLifetime = TimeUtils.toAbsoluteTimeMillis(lifetime); - - if (oldLife != null) { - if (absoluteLifetime < oldLife) { - // make sure we don't override the original value - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Overriding attempt to decrease adv lifetime from : {0} to :{1}", - new Date(oldLife), new Date(absoluteLifetime))); - } - absoluteLifetime = oldLife; - } - } - // make sure expiration does not exceed lifetime - if (expiration > lifetime) { - expiration = lifetime; - } - long pos = cacheDB.writeRecord(key, value, absoluteLifetime, expiration); - Map indexables = getIndexfields(adv.getIndexFields(), doc); - Map keyedIdx = addKey(dn, indexables); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Indexing " + keyedIdx + " at " + pos); - } - indexer.addToIndex(keyedIdx, pos); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - // too noisy - // LOG.debug("Wrote " + key + " = " + value); - LOG.fine("Stored " + indexables + " at " + pos); - } - - if (expiration > 0) { - // Update for SRDI with our caches lifetime only if we are prepared to share the advertisement with others. - addDelta(dn, indexables, TimeUtils.toRelativeTimeMillis(absoluteLifetime)); - } - - } catch (DBException de) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, MessageFormat.format("Failed to write {0}/{1} {2} {3}", dn, fn, lifetime, expiration), de); - } - IOException failure = new IOException("Failed to write " + dn + "/" + fn + " " + lifetime + " " + expiration); - failure.initCause(de); - throw failure; - } - } - - /** - * Store some bytes in specified dir, and file name, and - * associated doc timeouts - * - * @param dn directory name - * @param fn file name - * @param data byte array to save - * @param lifetime Document (local) lifetime in relative ms - * @param expiration Document (global) expiration time in relative ms - * @throws IOException Thrown if there is a problem saving the document. - */ - public synchronized void save(String dn, String fn, byte[] data, long lifetime, long expiration) throws IOException { - - try { - if (expiration < 0 || lifetime <= 0) { - throw new IllegalArgumentException("Bad expiration or lifetime."); - } - - Key key = new Key(dn + "/" + fn); - Value value = new Value(data); - Long oldLife = null; - Record record = cacheDB.readRecord(key); - - if (record != null) { - // grab the old lifetime - oldLife = (Long) record.getMetaData(Record.LIFETIME); - } - - // save the new version - - long absoluteLifetime = TimeUtils.toAbsoluteTimeMillis(lifetime); - - if (oldLife != null) { - if (absoluteLifetime < oldLife) { - // make sure we don't override the original value - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Overriding attempt to decrease adv lifetime from : {0} to :{1}", - new Date(oldLife), new Date(absoluteLifetime))); - } - absoluteLifetime = oldLife; - } - } - - // make sure expiration does not exceed lifetime - if (expiration > lifetime) { - expiration = lifetime; - } - - cacheDB.writeRecord(key, value, absoluteLifetime, expiration); - } catch (DBException de) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to write " + dn + "/" + fn + " " + lifetime + " " + expiration, de); - } - - IOException failure = new IOException("Failed to write " + dn + "/" + fn + " " + lifetime + " " + expiration); - failure.initCause(de); - throw failure; - } - } - - private static Map getIndexfields(String[] fields, StructuredDocument doc) { - Map map = new HashMap(); - - if (doc == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Null document"); - } - return map; - } - if (fields == null) { - return map; - } - for (String field : fields) { - Enumeration en = doc.getChildren(field); - while (en.hasMoreElements()) { - String val = (String) ((Element) en.nextElement()).getValue(); - if (val != null) { - map.put(field, val); - } - } - } - return map; - } - - /* adds a primary index 'dn' to indexables */ - private static Map addKey(String dn, Map map) { - if (map == null) { - return null; - } - - Map tmp = new HashMap(); - if (map.size() > 0) { - Iterator it = map.keySet().iterator(); - - while (it != null && it.hasNext()) { - String name = it.next(); - - tmp.put(dn + name, map.get(name)); - } - } - return tmp; - } - - private static final class EntriesCallback implements BTreeCallback { - - private BTreeFiler cacheDB = null; - private int threshold; - private List results; - private String key; - - EntriesCallback(BTreeFiler cacheDB, List results, String key, int threshold) { - this.cacheDB = cacheDB; - this.results = results; - this.key = key; - this.threshold = threshold; - } - - /** - * {@inheritDoc} - */ - public boolean indexInfo(Value val, long pos) { - if (results.size() >= threshold) { - return false; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Found " + val.toString() + " at " + pos); - } - - Record record; - try { - record = cacheDB.readRecord(pos); - } catch (DBException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while reading indexed", ex); - } - return false; - } - if (record == null) { - return true; - } - long exp = calcExpiration(record); - - if (exp <= 0) { - // skip expired and private entries - return true; - } - Long life = (Long) record.getMetaData(Record.LIFETIME); - SrdiMessage.Entry entry = new SrdiMessage.Entry(key, val.toString(), life - System.currentTimeMillis()); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(" key [" + entry.key + "] value [" + entry.value + "] exp [" + entry.expiration + "]"); - } - results.add(entry); - return true; - } - } - - - private final class SearchCallback implements BTreeCallback { - - private BTreeFiler cacheDB = null; - private Indexer indexer = null; - private int threshold; - private List results; - private List expirations; - private boolean purge; - - SearchCallback(BTreeFiler cacheDB, Indexer indexer, List results, List expirations, int threshold) { - this(cacheDB, indexer, results, expirations, threshold, false); - } - - SearchCallback(BTreeFiler cacheDB, Indexer indexer, List results, List expirations, int threshold, boolean purge) { - this.cacheDB = cacheDB; - this.indexer = indexer; - this.results = results; - this.threshold = threshold; - this.expirations = expirations; - this.purge = purge; - } - - /** - * {@inheritDoc} - */ - public boolean indexInfo(Value val, long pos) { - if (results.size() >= threshold) { - return false; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Found " + val.toString() + " at " + pos); - } - - Record record; - try { - record = cacheDB.readRecord(pos); - } catch (DBException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while reading indexed", ex); - } - return false; - } - - if (record == null) { - return true; - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINEST)) { - LOG.finest("Search callback record " + record.toString()); - } - long exp = calcExpiration(record); - if (exp < 0) { - if (purge) { - try { - indexer.purge(pos); - cacheDB.deleteRecord(record.getKey()); - } catch (DBException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while reading indexed", ex); - } - } catch (IOException ie) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while reading indexed", ie); - } - } - } else { - ++inconvenienceLevel; - } - return true; - } - - if (expirations != null) { - expirations.add(exp); - } - results.add(record.getValue().getInputStream()); - return true; - } - } - - protected static IndexQuery getIndexQuery(String value) { - - int operator; - - if (value == null) { - return null; - } else if (value.length() == 0 || "*".equals(value)) { - return null; - } else if (value.indexOf("*") < 0) { - operator = IndexQuery.EQ; - } else if (value.charAt(0) == '*' && value.charAt(value.length() - 1) != '*') { - operator = IndexQuery.EW; - value = value.substring(1, value.length()); - } else if (value.charAt(value.length() - 1) == '*' && value.charAt(0) != '*') { - operator = IndexQuery.SW; - value = value.substring(0, value.length() - 1); - } else { - operator = IndexQuery.BWX; - value = value.substring(1, value.length() - 1); - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Index query operator :" + operator); - } - return new IndexQuery(operator, new Value(value)); - } - - /** - * Search and recovers documents that contains at least - * a macthing pair of tag/value. - * - * @param dn contains the name of the folder on which to - * perform the search - * @param value contains the value to search on. - * @param attribute attribute to search on - * @param threshold threshold - * @param expirations List to contain expirations - * @return Enumeration containing of all the documents names - */ - public synchronized List search(String dn, String attribute, String value, int threshold, List expirations) { - List res = new ArrayList(); - IndexQuery iq = getIndexQuery(value); - try { - indexer.search(iq, dn + attribute, new SearchCallback(cacheDB, indexer, res, expirations, threshold)); - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while searching in index", ex); - } - } - return res; - } - - /** - * returns all entries that are cached - * - * @param dn the relative dir name - * @param clearDeltas if true clears the delta cache - * @return SrdiMessage.Entries - */ - public synchronized List getEntries(String dn, boolean clearDeltas) { - List res = new ArrayList(); - try { - Map map = indexer.getIndexers(); - BTreeFiler listDB = indexer.getListDB(); - Iterator it = map.keySet().iterator(); - - while (it != null && it.hasNext()) { - String indexName = (String) it.next(); - // seperate the index name from attribute - if (indexName.startsWith(dn)) { - String attr = indexName.substring((dn).length()); - NameIndexer idxr = (NameIndexer) map.get(indexName); - idxr.query(null, new Indexer.SearchCallback(listDB, new EntriesCallback(cacheDB, res, attr, Integer.MAX_VALUE))); - } - } - } catch (Exception ex) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Exception while searching in index", ex); - } - } - - if (clearDeltas) { - clearDeltas(dn); - } - return res; - } - - /** - * returns all entries that are added since this method was last called - * - * @param dn the relative dir name - * @return SrdiMessage.Entries - */ - public synchronized List getDeltas(String dn) { - List result = new ArrayList(); - List deltas = deltaMap.get(dn); - - if (deltas != null) { - result.addAll(deltas); - deltas.clear(); - } - return result; - } - - private synchronized void clearDeltas(String dn) { - - List deltas = deltaMap.get(dn); - - if (deltas == null) { - return; - } - deltas.clear(); - } - - private synchronized void addDelta(String dn, Map indexables, long exp) { - - if (trackDeltas) { - Iterator> eachIndex = indexables.entrySet().iterator(); - - if (eachIndex.hasNext()) { - List deltas = deltaMap.get(dn); - - if (deltas == null) { - deltas = new ArrayList(); - deltaMap.put(dn, deltas); - } - while (eachIndex.hasNext()) { - Map.Entry anEntry = eachIndex.next(); - String attr = anEntry.getKey(); - String value = anEntry.getValue(); - SrdiMessage.Entry entry = new SrdiMessage.Entry(attr, value, exp); - - deltas.add(entry); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Added entry :" + entry + " to deltas"); - } - } - } - } - } - - public synchronized void setTrackDeltas(boolean trackDeltas) { - this.trackDeltas = trackDeltas; - if (!trackDeltas) { - deltaMap.clear(); - } - } - - /** - * stop the cm - */ - public synchronized void stop() { - try { - cacheDB.close(); - indexer.close(); - stop = true; - notify(); - } catch (DBException ex) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Unable to close advertisments.tbl", ex); - } - } - } - - /** - * {@inheritDoc} - */ - public synchronized void run() { - try { - while (!stop) { - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("waiting " + gcMinInterval + "ms before garbage collection"); - } - wait(gcMinInterval); - } catch (InterruptedException woken) { - Thread.interrupted(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Thread interrupted", woken); - } - } - - if (stop) { - // if asked to stop, exit - break; - } - - if ((inconvenienceLevel > maxInconvenienceLevel) || (System.currentTimeMillis() > gcTime)) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Garbage collection started"); - } - garbageCollect(); - inconvenienceLevel = 0; - gcTime = System.currentTimeMillis() + gcMaxInterval; - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Garbage collection completed"); - } - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - gcThread = null; - } - } - - private synchronized void rebuildIndex() throws DBException, IOException { - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Rebuilding indices"); - } - - String pattern = "*"; - IndexQuery any = new IndexQuery(IndexQuery.ANY, pattern); - - cacheDB.query(any, new RebuildIndexCallback(cacheDB, indexer)); - } - - private static final class RebuildIndexCallback implements BTreeCallback { - - private BTreeFiler database = null; - private Indexer index = null; - - RebuildIndexCallback(BTreeFiler database, Indexer index) { - this.database = database; - this.index = index; - } - - /** - * {@inheritDoc} - */ - public boolean indexInfo(Value val, long pos) { - try { - Record record = database.readRecord(pos); - - if (record == null) { - return true; - } - - InputStream is = record.getValue().getInputStream(); - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, is); - Advertisement adv = AdvertisementFactory.newAdvertisement(asDoc); - Map indexables = getIndexfields(adv.getIndexFields(), asDoc); - - String dn = getDirName(adv); - Map keyedIdx = addKey(dn, indexables); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Restoring index " + keyedIdx + " at " + pos); - } - index.addToIndex(keyedIdx, pos); - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception rebuilding index at " + pos, ex); - } - return true; - } - return true; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/Indexer.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/Indexer.java deleted file mode 100644 index ef76db6f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/Indexer.java +++ /dev/null @@ -1,617 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.cm; - -import net.jxta.impl.xindice.core.DBException; -import net.jxta.impl.xindice.core.data.Key; -import net.jxta.impl.xindice.core.data.Record; -import net.jxta.impl.xindice.core.data.Value; -import net.jxta.impl.xindice.core.filer.BTreeCallback; -import net.jxta.impl.xindice.core.filer.BTreeException; -import net.jxta.impl.xindice.core.filer.BTreeFiler; -import net.jxta.impl.xindice.core.indexer.IndexQuery; -import net.jxta.impl.xindice.core.indexer.NameIndexer; -import net.jxta.logging.Logging; - -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.logging.Level; -import java.util.logging.Logger; - -public final class Indexer { - - /** - * The logger - */ - private final static transient Logger LOG = Logger.getLogger(Indexer.class.getName()); - - private final static String listFileName = "offsets"; - - private String dir = null; - private String file = null; - private final Map indices = new HashMap(); - private BTreeFiler listDB = null; - private boolean sync = true; - - /* - * Indexer manages indexes to various advertisement types, - * and maintains a listDB which holds records that hold references - * to records in advertisments.tbl - * - * ------- ------- / ------- - * | index | ---->> | listDB | ------->> - | advDB | - * ------- ------- \ ------- - * - */ - public Indexer() {} - - /** - * Creates an indexer - * - * @param sync passed through to xindice to determine a lazy checkpoint or not - * false == lazy checkpoint - */ - public Indexer(boolean sync) { - this.sync = sync; - } - - public void setLocation(String dir, String file) { - this.dir = dir; - this.file = file; - - // upon restart, load existing indices - - File directory = new File(dir); - File[] indexFiles = directory.listFiles(new FilenameFilter() { - public boolean accept(File parentDir, String fileName) { - return fileName.endsWith(".idx"); - } - }); - - for (File indexFile : indexFiles) { - String indexFileName = indexFile.getName(); - int dash = indexFileName.lastIndexOf("-"); - int dot = indexFileName.lastIndexOf(".idx"); - - if (dot > 0 && dash > 0) { - String name = indexFileName.substring(dash + 1, dot).trim(); - - if (indices.get(name) == null) { - try { - NameIndexer indexer = new NameIndexer(); - - // location should be the same as in - // addToIndex below - indexer.setLocation(dir, file + "-" + name); - indexer.setSync(sync); - if (!indexer.open()) { - indexer.create(); - indexer.open(); - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Adding :" + indexFileName + " under " + name); - } - indices.put(name, indexer); - } catch (DBException ignore) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failed to create Index " + name, ignore); - } - } - } - } - } - try { - // record pointers - listDB = new BTreeFiler(); - listDB.setSync(sync); - listDB.setLocation(directory.getCanonicalPath(), file + "-" + listFileName); - if (!listDB.open()) { - listDB.create(); - // now open it - listDB.open(); - } - } catch (DBException dbe) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failed during listDB Creation", dbe); - } - } catch (IOException ie) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failed during listDB Creation", ie); - } - } - } - - public boolean open() throws DBException { - return true; - } - - public boolean create() throws DBException { - return true; - } - - public synchronized boolean close() throws DBException { - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Closing Indexer"); - } - - Iterator> eachIndex = indices.entrySet().iterator(); - while (eachIndex.hasNext()) { - Map.Entry anEntry = eachIndex.next(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Closing Index :" + anEntry.getKey()); - } - - try { - anEntry.getValue().close(); - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure closing index :" + anEntry.getKey(), failed); - } - } - - eachIndex.remove(); - } - - // clear just in case. - indices.clear(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Closing listDB"); - } - - listDB.close(); - return true; - } - - /** - * returns an iteration of index fields (attributes) - */ - public Map getIndexers() { - return Collections.unmodifiableMap(indices); - } - - /** - * returns listDB - */ - public BTreeFiler getListDB() { - return listDB; - } - - private static final class EndsWithCallback implements BTreeCallback { - - private int op = IndexQuery.ANY; - private BTreeCallback callback = null; - private Value pattern = null; - - EndsWithCallback(int op, BTreeCallback callback, Value pattern) { - this.op = op; - this.callback = callback; - this.pattern = pattern; - } - - /** - * {@inheritDoc} - */ - public boolean indexInfo(Value val, long pos) { - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("value :" + val + " pattern :" + pattern); - } - - switch (op) { - case IndexQuery.EW: - if (val.endsWith(pattern)) { - return callback.indexInfo(val, pos); - } - break; - - case IndexQuery.NEW: - if (!val.endsWith(pattern)) { - return callback.indexInfo(val, pos); - } - break; - - case IndexQuery.BWX: - if (val.contains(pattern)) { - return callback.indexInfo(val, pos); - } - break; - - default: - break; - - } - return true; - } - } - - public void search(IndexQuery query, String name, BTreeCallback callback) throws IOException, BTreeException { - - BTreeCallback cb = new SearchCallback(listDB, callback); - - if (query != null) { - int op = query.getOperator(); - if (op == IndexQuery.EW || op == IndexQuery.NEW || op == IndexQuery.BWX) { - query = new IndexQuery(IndexQuery.ANY, query.getValues()); - cb = new EndsWithCallback(op, new SearchCallback(listDB, callback), query.getValue(0)); - } - } - - if (name == null) { - if (indices != null) { - Iterator i = indices.values().iterator(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Searching all indexes"); - } - while (i.hasNext()) { - NameIndexer index = i.next(); - index.query(query, new SearchCallback(listDB, callback)); - } - } - } else { - NameIndexer indexer = indices.get(name); - if (indexer == null) { - return; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Searching Index : " + name); - } - indexer.query(query, cb); - } - } - - public void addToIndex(Map indexables, long pos) throws IOException, DBException { - - if (indexables == null) { - return; - } - // FIXME add indexer name to NameIndexer, to optimize this loop - for (String name : indexables.keySet()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("looking up NameIndexer : " + name); - } - NameIndexer indexer = indices.get(name); - - if (indexer == null) { - indexer = new NameIndexer(); - // location should be the same as in setLocation above - indexer.setLocation(dir, file + "-" + name); - indexer.setSync(sync); - if (!indexer.open()) { - indexer.create(); - indexer.open(); - } - indices.put(name, indexer); - } - - // we need to make sure that the db key is unique from the - // the index key to avoid value collision - Key dbKey = new Key(name + indexables.get(name)); - Key indexKey = new Key(indexables.get(name)); - long listPos = writeRecord(listDB, dbKey, pos); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - StringBuilder message = new StringBuilder().append("Adding a reference at position :").append(listPos).append(" to ").append(name).append(" index, Key: ").append( - indexables.get(name)); - LOG.finer(message.toString()); - } - indexer.add(indexKey, listPos); - } - } - - public void removeFromIndex(Map indexables, long pos) throws DBException { - - Collection names; - - if (indexables == null) { - names = indices.keySet(); - } else { - names = indexables.keySet(); - } - - Long lpos = pos; - - for (String name : names) { - NameIndexer indexer = indices.get(name); - - if (indexer != null) { - // we need to make sure that the db key is unique from the - // the index key to avoid value collision - Key dbKey = null; - - if (indexables != null) { - dbKey = new Key(name + indexables.get(name)); - } - Key indexKey = null; - - if (indexables != null) { - indexKey = new Key(indexables.get(name)); - } - synchronized (listDB) { - Record record = listDB.readRecord(dbKey); - Set offsets = readRecord(record); - - if (!offsets.isEmpty()) { - if (offsets.contains(lpos)) { - offsets.remove(lpos); - Value recordValue = new Value(toByteArray(offsets)); - - listDB.writeRecord(dbKey, recordValue); - } - if (offsets.isEmpty()) { - // only we can proceed to remove the entry from the index - listDB.deleteRecord(dbKey); - indexer.remove(indexKey); - } - } else { - // empty record purge it - listDB.deleteRecord(dbKey); - indexer.remove(indexKey); - } - } - } - } - } - - /** - * purge all index entries pointing to a certain record. - * - * @param list List of Long position(s) at which the record to be purged is - * located in the main database. - * @throws IOException if an io error occurs - * @throws BTreeException if an DB error occurs - */ - public void purge(List list) throws IOException, BTreeException { - IndexQuery iq = new IndexQuery(IndexQuery.ANY, ""); - Collection keys = new ArrayList(indices.keySet()); - - for (String objKey : keys) { - NameIndexer index = indices.get(objKey); - PurgeCallback pc = new PurgeCallback(listDB, index, objKey, list); - - index.query(iq, pc); - } - } - - /** - * purge all index entries pointing to a certain record. - * - * @param pos the position at which the record to be purged is - * located in the main database. - * @throws IOException if an io error occurs - * @throws BTreeException if an BTree error occurs - */ - public void purge(long pos) throws IOException, BTreeException { - purge(Collections.singletonList(pos)); - } - - private static final class PurgeCallback implements BTreeCallback { - - private final NameIndexer indexer; - private final List list; - private final BTreeFiler listDB; - private final String indexKey; - - PurgeCallback(BTreeFiler listDB, NameIndexer indexer, String indexKey, List list) { - this.listDB = listDB; - this.indexer = indexer; - this.indexKey = indexKey; - this.list = list; - } - - /** - * {@inheritDoc} - */ - public boolean indexInfo(Value val, long pos) { - // Read record to determine whether there's a refrence to pos - try { - synchronized (listDB) { - Record record = listDB.readRecord(pos); - Set offsets = readRecord(record); - - boolean changed = offsets.removeAll(list); - if (changed) { - if (!offsets.isEmpty()) { - Value recordValue = new Value(toByteArray(offsets)); - - listDB.writeRecord(pos, recordValue); - } else { - listDB.deleteRecord(new Key(indexKey + val)); - indexer.remove(new Key(val)); - } - } - } - } catch (DBException ignore) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "An exception occured", ignore); - } - } - return true; - } - } - - private static byte[] toByteArray(Set offsets) { - try { - int size = offsets.size(); - ByteArrayOutputStream bos = new ByteArrayOutputStream((size * 8) + 4); - DataOutputStream dos = new DataOutputStream(bos); - - dos.writeInt(size); - for (Long lpos : offsets) { - dos.writeLong(lpos.longValue()); - } - dos.close(); - return bos.toByteArray(); - } catch (IOException ie) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception during array to byte array conversion", ie); - } - } - return null; - } - - public static Set readRecord(Record record) { - Set result = new TreeSet(); - - if (record == null) { - return result; - } - - InputStream is = record.getValue().getInputStream(); - - try { - DataInputStream ois = new DataInputStream(is); - int size = ois.readInt(); - - for (int i = 0; i < size; i++) { - result.add(ois.readLong()); - } - ois.close(); - } catch (IOException ie) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while reading Entry", ie); - } - } - return result; - } - - private static long writeRecord(BTreeFiler listDB, Key key, long pos) throws DBException, IOException { - - synchronized (listDB) { - Long lpos = pos; - Record record = listDB.readRecord(key); - Set offsets = readRecord(record); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE) && offsets != null) { - LOG.finer("list.contains " + pos + " : " + offsets.contains(lpos)); - } - - if (offsets != null && !offsets.contains(lpos)) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Adding a reference to record at :" + lpos); - LOG.finer("Writing :" + offsets.size() + " references"); - } - offsets.add(lpos); - } - Value recordValue = new Value(toByteArray(offsets)); - - return listDB.writeRecord(key, recordValue); - } - } - - public static final class SearchCallback implements BTreeCallback { - - private BTreeCallback callback = null; - private BTreeFiler listDB = null; - - public SearchCallback(BTreeFiler listDB, BTreeCallback callback) { - this.listDB = listDB; - this.callback = callback; - } - - /** - * {@inheritDoc} - */ - public boolean indexInfo(Value val, long pos) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Found " + val.toString() + " at " + pos); - } - Record record = null; - Set offsets = null; - boolean result = true; - - try { - synchronized (listDB) { - record = listDB.readRecord(pos); - offsets = readRecord(record); - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Found " + offsets.size() + " entries"); - } - } - - for (Long lpos : offsets) { - result &= callback.indexInfo(val, lpos); - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Callback result : " + result); - } - } - } catch (DBException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while reading indexed", ex); - } - return false; - } - return result; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/Srdi.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/Srdi.java deleted file mode 100644 index 925ad7bb..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/Srdi.java +++ /dev/null @@ -1,666 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.cm; - -import net.jxta.credential.Credential; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.protocol.ResolverSrdiMsgImpl; -import net.jxta.impl.protocol.SrdiMessageImpl; -import net.jxta.impl.util.JxtaHash; -import net.jxta.logging.Logging; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.protocol.ResolverQueryMsg; -import net.jxta.protocol.ResolverSrdiMsg; -import net.jxta.protocol.SrdiMessage; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.rendezvous.RendezVousStatus; -import net.jxta.rendezvous.RendezvousEvent; -import net.jxta.rendezvous.RendezvousListener; -import net.jxta.resolver.ResolverService; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.math.BigInteger; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.Vector; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Srdi is a service which provides SRDI functionalities such as : - *

      - *

        - *
      • pushing of SRDI messages to a another peer/propagate
      • - *
      • replication of an SRDI Message to other peers in a given peerview
      • - *
      • given an expression SRDI provides a independently calculated starting point
      • - *
      • Forwarding a ResolverQuery, and taking care of hopCount, random selection
      • - *
      • registers with the RendezvousService to determine when to share SrdSRDIi Entries
      • - * and whether to push deltas, or full a index - *
      • provides a SrdiInterface giving to provide a generic SRDI message definition
      • - *
      - *

      - * If Srdi is started as a thread it performs periodic SRDI pushes of - * indices and also has the ability to respond to rendezvous events. - *

      - * ResolverSrdiMessages define a ttl, to indicate to the receiving service - * whether to replicate such message or not. - *

      - * In addition A ResolverQuery defines a hopCount to indicate how many - * hops a query has been forwarded. This element could be used to detect/stop a - * query forward loopback hopCount is checked to make ensure a query is not - * forwarded more than twice. - * - * @see JXTA Protocols Specification : Peer Resolver Protocol - */ -public class Srdi implements Runnable, RendezvousListener { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(Srdi.class.getName()); - - private PeerGroup group = null; - private String handlername = null; - private SrdiInterface srdiService = null; - private SrdiIndex srdiIndex; - private long connectPollInterval = 0; - private long pushInterval = 0; - - private volatile boolean stop = false; - private AtomicBoolean republishSignal = new AtomicBoolean(false); - - private ResolverService resolver; - private MembershipService membership; - private final JxtaHash jxtaHash = new JxtaHash(); - private CredentialListener membershipCredListener = null; - private Credential credential = null; - private StructuredDocument credentialDoc = null; - private final String rdvEventLock; - - /** - * Random number generator used for random result selection - */ - private final static Random random = new Random(); - - // This ought be to configurable/based on a function applied to the rpv size - /** - * Replication threshold (minimum number of rdv's in peer view before replication) - */ - public final static int RPV_REPLICATION_THRESHOLD = 3; - - /** - * Listener we use for membership property events. - */ - private class CredentialListener implements PropertyChangeListener { - - /** - * {@inheritDoc} - */ - public void propertyChange(PropertyChangeEvent evt) { - if ("defaultCredential".equals(evt.getPropertyName())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("New default credential event"); - } - - synchronized (Srdi.this) { - credential = (Credential) evt.getNewValue(); - credentialDoc = null; - if (null != credential) { - try { - credentialDoc = credential.getDocument(MimeMediaType.XMLUTF8); - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not generate credential document", all); - } - } - } - } - } - } - } - - - /** - * Interface for pushing entries. - */ - public interface SrdiInterface { - - /** - * Pushe SRDI entries. - * - * @param all if true then push all entries otherwise just push - * those which have changed since the last push. - */ - void pushEntries(boolean all); - } - - /** - * Starts the Srdi Service. wait for connectPollInterval prior to - * pushing the index if connected to a rdv, otherwise index is - * as soon as the Rendezvous connect occurs - * - * @param group group context to operate in - * @param handlername the SRDI handlername - * @param srdiService the service utilizing this Srdi, for purposes of - * callback push entries on events such as rdv connect/disconnect, etc. - * @param srdiIndex The index instance associated with this service - * @param connectPollInterval initial timeout before the very first push of entries in milliseconds - * @param pushInterval the Interval at which the deltas are pushed in milliseconds - */ - public Srdi(PeerGroup group, String handlername, SrdiInterface srdiService, SrdiIndex srdiIndex, long connectPollInterval, long pushInterval) { - - this.group = group; - this.handlername = handlername; - this.srdiService = srdiService; - this.srdiIndex = srdiIndex; - this.connectPollInterval = connectPollInterval; - this.pushInterval = pushInterval; - this.rdvEventLock = new String(handlername); - membership = group.getMembershipService(); - - resolver = group.getResolverService(); - - group.getRendezVousService().addListener(this); - - synchronized (this) { - membershipCredListener = new CredentialListener(); - membership.addPropertyChangeListener("defaultCredential", membershipCredListener); - - try { - credential = membership.getDefaultCredential(); - - if (null != credential) { - credentialDoc = credential.getDocument(MimeMediaType.XMLUTF8); - } else { - credentialDoc = null; - } - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "could not get credential", all); - } - } - } - } - - /** - * stop the current running thread - */ - public synchronized void stop() { - - if (stop) { - return; - } - - stop = true; - - RendezVousService rendezvous = group.getRendezVousService(); - - if (null != rendezvous) { - rendezvous.removeListener(this); - } - - membership.removePropertyChangeListener("defaultCredential", membershipCredListener); - membershipCredListener = null; - - // wakeup and die - synchronized (rdvEventLock) { - rdvEventLock.notify(); - } - } - - /** - * Replicates a SRDI message to other rendezvous' - * entries are replicated by breaking out entries out of the message - * and sorted out into rdv distribution bins. after which smaller messages - * are sent to other rdv's - * - * @param srdiMsg srdi message to replicate - */ - - public void replicateEntries(SrdiMessage srdiMsg) { - - List rpv = getGlobalPeerView(); - - if (srdiMsg.getScope() < SrdiMessage.REPLICATE || !group.isRendezvous() || rpv.size() < RPV_REPLICATION_THRESHOLD) { - return; - } - - Iterator allEntries = srdiMsg.getEntries().iterator(); - Map bins = new HashMap(rpv.size()); - - while (allEntries.hasNext()) { - SrdiMessage.Entry entry = (SrdiMessage.Entry) allEntries.next(); - PeerID destPeer = getReplicaPeer(srdiMsg.getPrimaryKey() + entry.key + entry.value); - - if (destPeer == null || destPeer.equals(group.getPeerID())) { - // don't replicate message back to ourselves - continue; - } - SrdiMessageImpl sm = bins.get(destPeer); - - if (sm == null) { - sm = new SrdiMessageImpl(); - sm.setPrimaryKey(srdiMsg.getPrimaryKey()); - sm.setPeerID(srdiMsg.getPeerID()); - bins.put(destPeer, sm); - } - sm.addEntry(entry); - } - - for (PeerID destPeer : bins.keySet()) { - SrdiMessageImpl msg = bins.get(destPeer); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + group.getPeerGroupName() + " / " + handlername + "] Forwarding replica Srdi to " + destPeer); - } - pushSrdi(destPeer, msg); - } - } - - /** - * Push an SRDI message to a peer - * ttl is 1, and therefore services receiving this message could - * choose to replicate this message - * - * @param peer peer to push message to, if peer is null it is - * the message is propagated - * @param srdi SRDI message to send - */ - public void pushSrdi(ID peer, SrdiMessage srdi) { - try { - ResolverSrdiMsg resSrdi = new ResolverSrdiMsgImpl(handlername, credential, srdi.toString()); - - if (null == peer) { - resolver.sendSrdi(null, resSrdi); - } else { - resolver.sendSrdi(peer.toString(), resSrdi); - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to send srdi message", e); - } - } - } - - /** - * Forwards a Query to a specific peer - * hopCount is incremented to indicate this query is forwarded - * - * @param peer peerid to forward query to - * @param query The query - */ - public void forwardQuery(PeerID peer, ResolverQueryMsg query) { - - query.incrementHopCount(); - if (query.getHopCount() > 2) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("hopCount exceeded. Not forwarding query " + query.getHopCount()); - } - // query has been forwarded too many times - return; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("[{0} / {1}] Forwarding Query to {2}", - group.getPeerGroupName(), handlername, peer)); - } - resolver.sendQuery(peer.toString(), query); - } - - /** - * Forwards a Query to a list of peers - * hopCount is incremented to indicate this query is forwarded - * - * @param peers The peerids to forward query to - * @param query The query - */ - public void forwardQuery(List peers, ResolverQueryMsg query) { - - query.incrementHopCount(); - if (query.getHopCount() > 2) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("hopCount exceeded not forwarding query {0}", query.getHopCount())); - } - // query has been forwarded too many times - return; - } - - for (PeerID destPeer : peers) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("[{0} / {1}] Forwarding Query to {2}", - group.getPeerGroupName(), handlername, destPeer)); - } - resolver.sendQuery(destPeer.toString(), query); - } - } - - /** - * Forwards a Query to a list of peers - * if the list of peers exceeds threshold, and random threshold is picked - * from peers - * hopCount is incremented to indicate this query is forwarded - * - * @param peers The peerids to forward query to - * @param query The query - * @param threshold number of peers to forward the query to - */ - public void forwardQuery(List peers, ResolverQueryMsg query, int threshold) { - - if (query.getHopCount() > 2) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("[{0} / {1}] hopCount exceeded ({2}) not forwarding query.", - group.getPeerGroupName(), handlername, query.getHopCount())); - } - // query has been forwarded too many times - return; - } - if (peers.size() <= threshold) { - forwardQuery(peers, query); - } else { - // pick some random entries out of the list - List newPeers = randomResult(peers, threshold); - forwardQuery(newPeers, query); - } - } - - /** - * returns a random List(threshold) from a given list - * - * @param result starting set - * @param threshold sub-set desired - * @return sub-list of result - */ - protected List randomResult(List result, int threshold) { - if (threshold < result.size()) { - List res = new ArrayList(threshold); - for (int i = 0; i < threshold; i++) { - int rand = random.nextInt(result.size()); - res.add(result.get(rand)); - result.remove(rand); - } - return res; - } - return result; - } - - /** - * Given an expression return a peer from the list peers in the peerview - * this function is used to to give a replication point, and entry point - * to query on a pipe - * - * @param expression expression to derive the mapping from - * @return The replicaPeer value - */ - public PeerID getReplicaPeer(String expression) { - PeerID pid; - List rpv = getGlobalPeerView(); - - if (rpv.size() >= RPV_REPLICATION_THRESHOLD) { - BigInteger digest; - - synchronized (jxtaHash) { - jxtaHash.update(expression); - digest = jxtaHash.getDigestInteger().abs(); - } - BigInteger sizeOfSpace = java.math.BigInteger.valueOf(rpv.size()); - BigInteger sizeOfHashSpace = BigInteger.ONE.shiftLeft(8 * digest.toByteArray().length); - int pos = (digest.multiply(sizeOfSpace)).divide(sizeOfHashSpace).intValue(); - - pid = rpv.get(pos); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("[{0} / {1}] Found a direct peer {2}", group.getPeerGroupName(), handlername, pid)); - } - return pid; - } else { - return null; - } - } - - /** - * forward srdi message to another peer - * - * @param peerid PeerID to forward query to - * @param srcPid The source originator - * @param primaryKey primary key - * @param secondarykey secondary key - * @param value value of the entry - * @param expiration expiration in ms - */ - public void forwardSrdiMessage(PeerID peerid, PeerID srcPid, String primaryKey, String secondarykey, String value, long expiration) { - - try { - SrdiMessageImpl srdi = new SrdiMessageImpl(srcPid, // ttl of 0, avoids additional replication - 0, primaryKey, secondarykey, value, expiration); - - ResolverSrdiMsgImpl resSrdi = new ResolverSrdiMsgImpl(handlername, credential, srdi.toString()); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("[{0} / {1}] Forwarding a SRDI messsage of type {2} to {3}", group.getPeerGroupName(), - handlername, primaryKey, peerid)); - } - resolver.sendSrdi(peerid.toString(), resSrdi); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed forwarding SRDI Message", e); - } - } - } - - /** - * {@inheritDoc} - */ - @SuppressWarnings("fallthrough") - public void rendezvousEvent(RendezvousEvent event) { - - int theEventType = event.getType(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("[{0} / {1}] Processing {2}", group.getPeerGroupName(), handlername, event)); - } - - switch (theEventType) { - - case RendezvousEvent.RDVCONNECT: - synchronized (rdvEventLock) { - // wake up the publish thread now. - rdvEventLock.notify(); - } - - /* - * FALLSTHRU - */ - case RendezvousEvent.RDVRECONNECT: - // No need to wake up the publish thread; reconnect should not force indices to be published. - break; - - case RendezvousEvent.CLIENTCONNECT: - case RendezvousEvent.CLIENTRECONNECT: - case RendezvousEvent.BECAMERDV: - case RendezvousEvent.BECAMEEDGE: - // XXX 20031110 bondolo perhaps becoming edge one should cause it to wake up so that run() switch to - // don't do anything. - break; - - case RendezvousEvent.RDVFAILED: - case RendezvousEvent.RDVDISCONNECT: - republishSignal.set(true); - break; - - case RendezvousEvent.CLIENTFAILED: - case RendezvousEvent.CLIENTDISCONNECT: - // we should flush the cache for the peer - synchronized (rdvEventLock) { - if (group.isRendezvous() && (srdiIndex != null)) { - srdiIndex.remove((PeerID) event.getPeerID()); - } - } - break; - - default: - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning( - MessageFormat.format("[{0} / {1}] Unexpected RDV event {2}", group.getPeerGroupName(), handlername, event)); - } - break; - } - } - - /** - * {@inheritDoc} - *

      - * Main processing method for the SRDI Worker thread - * Send all entries, wait for pushInterval, then send deltas - */ - public void run() { - - boolean waitingForRdv; - boolean republish = true; - - try { - while (!stop) { - // upon connection we will have to republish - republish |= republishSignal.compareAndSet(true, false); - waitingForRdv = group.isRendezvous() || !group.getRendezVousService().isConnectedToRendezVous() || - group.getRendezVousService().getRendezVousStatus() == RendezVousStatus.ADHOC; - - if (!waitingForRdv) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + group.getPeerGroupName() + " / " + handlername + "] Pushing " - + (republish ? "all entries" : "deltas")); - } - - srdiService.pushEntries(republish); - republish = false; - } - - synchronized (rdvEventLock) { - try { - rdvEventLock.wait(waitingForRdv ? connectPollInterval : pushInterval); - } catch (InterruptedException e) { - Thread.interrupted(); - } - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, - "Uncaught Throwable in " + Thread.currentThread().getName() + "[" + group.getPeerGroupName() + " / " - + handlername + "]",all); - } - } - } - - /** - * get the global peerview as the rendezvous service only returns - * the peerview without the local RDV peer. We need this - * consistent view for the SRDI index if not each RDV will have a - * different peerview, off setting the index even when the peerview - * is stable - * - * @return the sorted list - */ - public Vector getGlobalPeerView() { - - Vector global = new Vector(); - SortedSet set = new TreeSet(); - - try { - // get the local peerview - List rpv = group.getRendezVousService().getLocalWalkView(); - - for (RdvAdvertisement padv : rpv) { - set.add(padv.getPeerID().toString()); - } - - // add myself - set.add(group.getPeerID().toString()); - - // produce a vector of Peer IDs - for (String aSet : set) { - try { - PeerID peerID = (PeerID) IDFactory.fromURI(new URI(aSet)); - global.add(peerID); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerID ID in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("ID was not a peerID"); - } - } - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure generating the global view", ex); - } - } - return global; - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/SrdiIndex.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/SrdiIndex.java deleted file mode 100644 index f4849d11..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/cm/SrdiIndex.java +++ /dev/null @@ -1,987 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.cm; - -import net.jxta.id.IDFactory; -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.xindice.core.DBException; -import net.jxta.impl.xindice.core.data.Key; -import net.jxta.impl.xindice.core.data.Record; -import net.jxta.impl.xindice.core.data.Value; -import net.jxta.impl.xindice.core.filer.BTreeCallback; -import net.jxta.impl.xindice.core.filer.BTreeFiler; -import net.jxta.impl.xindice.core.indexer.IndexQuery; -import net.jxta.impl.xindice.core.indexer.NameIndexer; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; - -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.UndeclaredThrowableException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * SrdiIndex - */ -public class SrdiIndex implements Runnable { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(SrdiIndex.class.getName()); - - private long interval = 1000 * 60 * 10; - private volatile boolean stop = false; - private final Indexer srdiIndexer; - private final BTreeFiler cacheDB; - private Thread gcThread = null; - private final Set gcPeerTBL = new HashSet(); - - private final String indexName; - - /** - * Constructor for the SrdiIndex - * - * @param group group - * @param indexName the index name - */ - public SrdiIndex(PeerGroup group, String indexName) { - this.indexName = indexName; - - try { - String pgdir = null; - File storeHome; - - if (group == null) { - pgdir = "srdi-index"; - storeHome = new File(".jxta"); - } else { - pgdir = group.getPeerGroupID().getUniqueValue().toString(); - storeHome = new File(group.getStoreHome()); - } - - File rootDir = new File(new File(storeHome, "cm"), pgdir); - - rootDir = new File(rootDir, "srdi"); - if (!rootDir.exists()) { - // We need to create the directory - if (!rootDir.mkdirs()) { - throw new RuntimeException("Cm cannot create directory " + rootDir); - } - } - // peerid database - // Storage - cacheDB = new BTreeFiler(); - // lazy checkpoint - cacheDB.setSync(false); - cacheDB.setLocation(rootDir.getCanonicalPath(), indexName); - - if (!cacheDB.open()) { - cacheDB.create(); - // now open it - cacheDB.open(); - } - - // index - srdiIndexer = new Indexer(false); - srdiIndexer.setLocation(rootDir.getCanonicalPath(), indexName); - if (!srdiIndexer.open()) { - srdiIndexer.create(); - // now open it - srdiIndexer.open(); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("[" + ((group == null) ? "none" : group.toString()) + "] : Initialized " + indexName); - } - } catch (DBException de) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Unable to Initialize databases", de); - } - - throw new UndeclaredThrowableException(de, "Unable to Initialize databases"); - } catch (Throwable e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Unable to create Cm", e); - } - - if (e instanceof Error) { - throw (Error) e; - } else if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new UndeclaredThrowableException(e, "Unable to create Cm"); - } - } - } - - /** - * Construct a SrdiIndex and starts a GC thread which runs every "interval" - * milliseconds - * - * @param interval the interval at which the gc will run in milliseconds - * @param group group context - * @param indexName SrdiIndex name - */ - - public SrdiIndex(PeerGroup group, String indexName, long interval) { - this(group, indexName); - this.interval = interval; - startGC(group, indexName, interval); - } - - /** - * Start the GC thread - * - * @param group the PeerGroup - * @param indexName index name - * @param interval interval in milliseconds - */ - protected void startGC(PeerGroup group, String indexName, long interval) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("[" + ((group == null) ? "none" : group.toString()) + "] : Starting SRDI GC Thread for " + indexName); - } - - gcThread = new Thread(group.getHomeThreadGroup(), this, "SrdiIndex GC :" + indexName + " every " + interval + "ms"); - gcThread.setDaemon(true); - gcThread.start(); - } - - /** - * Returns the name of this srdi index. - * - * @return index name. - */ - public String getIndexName() { - return indexName; - } - - /** - * add an index entry - * - * @param primaryKey primary key - * @param attribute Attribute String to query on - * @param value value of the attribute string - * @param expiration expiration associated with this entry relative time in - * milliseconds - * @param pid peerid reference - */ - public synchronized void add(String primaryKey, String attribute, String value, PeerID pid, long expiration) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + indexName + "] Adding " + primaryKey + "/" + attribute + " = \'" + value + "\' for " + pid); - } - - try { - Key key = new Key(primaryKey + attribute + value); - long expiresin = TimeUtils.toAbsoluteTimeMillis(expiration); - - // update the record if it exists - synchronized (cacheDB) { - // FIXME hamada 10/14/04 it is possible a peer re-appears with - // a different set of indexes since it's been marked for garbage - // collection. will address this issue in a subsequent patch - gcPeerTBL.remove(pid); - - Record record = cacheDB.readRecord(key); - List old; - - if (record != null) { - old = readRecord(record).list; - } else { - old = new ArrayList(); - } - Entry entry = new Entry(pid, expiresin); - - if (!old.contains(entry)) { - old.add(entry); - } else { - // entry exists, replace it (effectively updating expiration) - old.remove(old.indexOf(entry)); - old.add(entry); - } - // no sense in keeping expired entries. - old = removeExpired(old); - long t0 = TimeUtils.timeNow(); - byte[] data = getData(key, old); - - // if (LOG.isLoggable(Level.FINE)) { - // LOG.fine("Serialized result in : " + (TimeUtils.timeNow() - t0) + "ms."); - // } - if (data == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Failed to serialize data"); - } - return; - } - Value recordValue = new Value(data); - long pos = cacheDB.writeRecord(key, recordValue); - Map indexables = getIndexMap(primaryKey + attribute, value); - - srdiIndexer.addToIndex(indexables, pos); - } - } catch (IOException de) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to add SRDI", de); - } - } catch (DBException de) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to add SRDI", de); - } - } - } - - /** - * retrieves a record - * - * @param pkey primary key - * @param skey secondary key - * @param value value - * @return List of Entry objects - */ - public List getRecord(String pkey, String skey, String value) { - Record record = null; - - try { - Key key = new Key(pkey + skey + value); - - synchronized (cacheDB) { - record = cacheDB.readRecord(key); - } - } catch (DBException de) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to retrieve SrdiIndex record", de); - } - } - // if record is null, readRecord returns an empty list - return readRecord(record).list; - - } - - /** - * inserts a pkey into a map with a value of value - * - * @param primaryKey primary key - * @param value value - * @return The Map - */ - - private Map getIndexMap(String primaryKey, String value) { - if (primaryKey == null) { - return null; - } - if (value == null) { - value = ""; - } - Map map = new HashMap(1); - - map.put(primaryKey, value); - return map; - } - - /** - * remove entries pointing to peer id from cache - * - * @param pid peer id to remove - */ - public synchronized void remove(PeerID pid) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(" Adding " + pid + " to peer GC table"); - } - gcPeerTBL.add(pid); - } - - /** - * Query SrdiIndex - * - * @param attribute Attribute String to query on - * @param value value of the attribute string - * @return an enumeration of canonical paths - * @param primaryKey primary key - * @param threshold max number of results - */ - public synchronized List query(String primaryKey, String attribute, String value, int threshold) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + indexName + "] Querying for " + threshold + " " + primaryKey + "/" + attribute + " = \'" + value + "\'"); - } - - // return nothing - if (primaryKey == null) { - return Collections.emptyList(); - } - - List res; - - // a blind query - if (attribute == null) { - res = query(primaryKey); - } else { - res = new ArrayList(); - - IndexQuery iq = Cm.getIndexQuery(value); - - try { - srdiIndexer.search(iq, primaryKey + attribute, new SearchCallback(cacheDB, res, threshold, gcPeerTBL)); - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while searching in index", ex); - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( "[" + indexName + "] Returning " + res.size() + " results for " + primaryKey + "/" + attribute + " = \'" - + value + "\'"); - } - - return res; - } - - /** - * Query SrdiIndex - * - * @param primaryKey primary key - * @return A list of Peer IDs. - */ - public synchronized List query(String primaryKey) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + indexName + "] Querying for " + primaryKey); - } - - List res = new ArrayList(); - - try { - Map map = srdiIndexer.getIndexers(); - - for (Map.Entry index : map.entrySet()) { - String indexName = index.getKey(); - // seperate the index name from attribute - if (indexName.startsWith(primaryKey)) { - NameIndexer idxr = index.getValue(); - idxr.query(null, new SearchCallback(cacheDB, res, Integer.MAX_VALUE, gcPeerTBL)); - } - } - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while searching in index", ex); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + indexName + "] Returning " + res.size() + " results for " + primaryKey); - } - - return res; - } - - private static final class SearchCallback implements BTreeCallback { - private final BTreeFiler cacheDB; - private final int threshold; - private final List results; - private final Set excludeTable; - - SearchCallback(BTreeFiler cacheDB, List results, int threshold, Set excludeTable) { - this.cacheDB = cacheDB; - this.threshold = threshold; - this.results = results; - this.excludeTable = excludeTable; - } - - /** - * @inheritDoc - */ - public boolean indexInfo(Value val, long pos) { - - if (results.size() >= threshold) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("SearchCallback.indexInfo reached Threshold :" + threshold); - } - return false; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Found " + val); - } - Record record = null; - - try { - record = cacheDB.readRecord(pos); - } catch (DBException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while reading indexed", ex); - } - return false; - } - - if (record != null) { - long t0 = TimeUtils.timeNow(); - SrdiIndexRecord rec = readRecord(record); - - if (Logging.SHOW_FINEST && LOG.isLoggable(Level.FINEST)) { - LOG.finest("Got result back in : " + (TimeUtils.timeNow() - t0) + "ms."); - } - - copyIntoList(results, rec.list, excludeTable); - } - - return results.size() < threshold; - } - } - - - private static final class GcCallback implements BTreeCallback { - private final BTreeFiler cacheDB; - private final Indexer idxr; - private final List list; - private final Set table; - - GcCallback(BTreeFiler cacheDB, Indexer idxr, List list, Set table) { - this.cacheDB = cacheDB; - this.idxr = idxr; - this.list = list; - this.table = table; - } - - /** - * @inheritDoc - */ - public boolean indexInfo(Value val, long pos) { - - Record record = null; - synchronized (cacheDB) { - try { - record = cacheDB.readRecord(pos); - } catch (DBException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while reading indexed", ex); - } - return false; - } - if (record == null) { - return true; - } - SrdiIndexRecord rec = readRecord(record); - List res = rec.list; - boolean changed = false; - - Iterator eachEntry = res.iterator(); - while(eachEntry.hasNext()) { - Entry entry = eachEntry.next(); - - if (entry.isExpired() || table.contains(entry.peerid)) { - changed = true; - eachEntry.remove(); - } - } - if (changed) { - if (res.isEmpty()) { - try { - cacheDB.deleteRecord(rec.key); - list.add(pos); - } catch (DBException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while deleting empty record", e); - } - } - } else { - // write it back - byte[] data = getData(rec.key, res); - Value recordValue = new Value(data); - - try { - cacheDB.writeRecord(pos, recordValue); - } catch (DBException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while writing back record", ex); - } - } - } - } - } - return true; - } - } - - /** - * copies the content of List into a list. Expired entries are not - * copied - * - * @param to list to copy into - * @param from list to copy from - * @param table table of PeerID's - */ - private static void copyIntoList(List to, List from, Set table) { - for (Entry entry : from) { - boolean expired = entry.isExpired(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Entry peerid : " + entry.peerid + (expired ? " EXPIRED " : (" Expires at : " + entry.expiration))); - } - - if (!to.contains(entry.peerid) && !expired) { - if (!table.contains(entry.peerid)) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("adding Entry :" + entry.peerid + " to list"); - } - to.add(entry.peerid); - } else { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Skipping gc marked entry :" + entry.peerid); - } - } - } else { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Skipping expired Entry :" + entry.peerid); - } - } - } - } - - /** - * Converts a List of {@link Entry} into a byte[] - * - * @param key record key - * @param list List to convert - * @return byte [] - */ - private static byte[] getData(Key key, List list) { - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(bos); - - dos.writeUTF(key.toString()); - dos.writeInt(list.size()); - for (Entry anEntry : list) { - dos.writeUTF(anEntry.peerid.toString()); - dos.writeLong(anEntry.expiration); - } - dos.close(); - return bos.toByteArray(); - } catch (IOException ie) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Exception while reading Entry", ie); - } - } - return null; - } - - /** - * Reads the content of a record into List - * - * @param record Btree Record - * @return List of entries - */ - public static SrdiIndexRecord readRecord(Record record) { - List result = new ArrayList(); - Key key = null; - - if (record == null) { - return new SrdiIndexRecord(null, result); - } - if (record.getValue().getLength() <= 0) { - return new SrdiIndexRecord(null, result); - } - InputStream is = record.getValue().getInputStream(); - - try { - DataInputStream ois = new DataInputStream(is); - - key = new Key(ois.readUTF()); - int size = ois.readInt(); - - for (int i = 0; i < size; i++) { - try { - String idstr = ois.readUTF(); - PeerID pid = (PeerID) IDFactory.fromURI(new URI(idstr)); - long exp = ois.readLong(); - Entry entry = new Entry(pid, exp); - - result.add(entry); - } catch (URISyntaxException badID) { - // ignored - } - } - ois.close(); - } catch (EOFException eofe) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Empty record", eofe); - } - } catch (IOException ie) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception while reading Entry", ie); - } - } - return new SrdiIndexRecord(key, result); - } - - /** - * Empties the index completely. - * The entries are abandoned to the GC. - */ - public synchronized void clear() { - // FIXME changing the behavior a bit - // instead of dropping all srdi entries, we let them expire - // if that is not a desired behavior the indexer could be dropped - // simply close it, and remove all index db created - try { - srdiIndexer.close(); - cacheDB.close(); - } catch (Exception e) { - // bad bits we are done - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to close index", e); - } - } - } - - /** - * Garbage Collect expired entries - */ - public void garbageCollect() { - try { - Map map = srdiIndexer.getIndexers(); - - for(NameIndexer idxr : map.values()) { - List list = new ArrayList(); - - if(stop) { - break; - } - - synchronized(this) { - idxr.query(null, new GcCallback(cacheDB, srdiIndexer, list, gcPeerTBL)); - srdiIndexer.purge(list); - } - } - gcPeerTBL.clear(); - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure during SRDI Garbage Collect", ex); - } - } - } - - /** - * Remove expired entries from a List - * - * @param list A list of entries. - * @return The same list with the expired entries removed. - */ - private static List removeExpired(List list) { - Iterator eachEntry = list.iterator(); - - while(eachEntry.hasNext()) { - Entry entry = eachEntry.next(); - - if (entry.isExpired()) { - eachEntry.remove(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing expired Entry peerid :" + entry.peerid + " Expires at :" + entry.expiration); - } - } - } - return list; - } - - private static boolean isExpired(long expiration) { - return (TimeUtils.timeNow() > expiration); - } - - /** - * stop the current running thread - */ - public synchronized void stop() { - if(stop) { - return; - } - - stop = true; - - // wakeup and die - try { - Thread temp = gcThread; - if (temp != null) { - synchronized (temp) { - temp.notify(); - } - } - } catch (Exception ignored) { - // ignored - } - - // Stop the database - - try { - srdiIndexer.close(); - cacheDB.close(); - gcPeerTBL.clear(); - } catch (Exception ex) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Unable to stop the Srdi Indexer", ex); - } - } - } - - /** - * {@inheritDoc} - *

      - * Periodic thread for GC - */ - public void run() { - try { - while (!stop) { - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Waiting for " + interval + "ms before garbage collection"); - } - synchronized (gcThread) { - gcThread.wait(interval); - } - } catch (InterruptedException woken) { - // The only reason we are woken is to stop. - Thread.interrupted(); - continue; - } - - if (stop) { - break; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Garbage collection started"); - } - - garbageCollect(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Garbage collection completed"); - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - synchronized (this) { - gcThread = null; - } - } - } - - /** - * Flushes the Srdi directory for a specified group - * this method should only be called before initialization of a given group - * calling this method on a running group would have undefined results - * - * @param group group context - */ - public static void clearSrdi(PeerGroup group) { - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Clearing SRDI for " + group.getPeerGroupName()); - } - - try { - String pgdir = null; - - if (group == null) { - pgdir = "srdi-index"; - } else { - pgdir = group.getPeerGroupID().getUniqueValue().toString(); - } - File rootDir = null; - - if (group != null) { - rootDir = new File(new File(new File(group.getStoreHome()), "cm"), pgdir); - } - - rootDir = new File(rootDir, "srdi"); - if (rootDir.exists()) { - // remove it along with it's content - String[] list = rootDir.list(); - - for (String aList : list) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing : " + aList); - } - File file = new File(rootDir, aList); - - if (!file.delete()) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unable to delete the file"); - } - } - } - rootDir.delete(); - } - } catch (Throwable t) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Unable to clear Srdi", t); - } - } - } - - /** - * An entry in the index tables. - */ - public final static class Entry { - - public final PeerID peerid; - public final long expiration; - - /** - * Peer Pointer reference - * - * @param peerid PeerID for this entry - * @param expiration the expiration for this entry - */ - public Entry(PeerID peerid, long expiration) { - this.peerid = peerid; - this.expiration = expiration; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - return obj instanceof Entry && (peerid.equals(((Entry) obj).peerid)); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return peerid.hashCode(); - } - - /** - * Return the absolute time in milliseconds at which this entry will - * expire. - * - * @return The absolute time in milliseconds at which this entry will - * expire. - */ - public long getExpiration() { - return expiration; - } - - /** - * Return {@code true} if this entry is expired. - * - * @return {@code true} if this entry is expired otherwise {@code false}. - */ - public boolean isExpired() { - return TimeUtils.timeNow() > expiration; - } - } - - - /** - * an SrdiIndexRecord wrapper - */ - public final static class SrdiIndexRecord { - - public final Key key; - public final List list; - - /** - * SrdiIndex record - * - * @param key record key - * @param list record entries - */ - public SrdiIndexRecord(Key key,List list) { - this.key = key; - this.list = list; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - return obj instanceof SrdiIndexRecord && (key.equals(((SrdiIndexRecord) obj).key)); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return key.hashCode(); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/config.properties b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/config.properties deleted file mode 100644 index f88f5ffb..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/config.properties +++ /dev/null @@ -1,19 +0,0 @@ -# JXTA Distribution Configuration Properties File -# -# This file contains properties which configure several basic defaults -# for JXTA distributions. Normally these values do not need to be changed -# by applications. (Most of the values have remained been unchanged since -# they were originally defined). -# - -# ID of the net peer group as a URI -#NetPeerGroupID=jxta-NetGroup -NetPeerGroupID=uuid-E6973087961042BC8412A6356F9FB70702 -# Name of the Net Peer Group -#NetPeerGroupName=NetPeerGroup -NetPeerGroupName=p2p.linphone.org-NetPeerGroup -# Description of the Net Peer Group -#NetPeerGroupDesc=default Net Peer Group -NetPeerGroupDesc=Net Peer Group for p2p.linphone.org -# Default type of ID to use when creating an ID -IDNewInstances=uuid diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/discovery/DiscoveryServiceImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/discovery/DiscoveryServiceImpl.java deleted file mode 100644 index 3dd7e6ef..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/discovery/DiscoveryServiceImpl.java +++ /dev/null @@ -1,1718 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.discovery; - - -import net.jxta.credential.Credential; -import net.jxta.discovery.DiscoveryEvent; -import net.jxta.discovery.DiscoveryListener; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.OutgoingMessageEvent; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.impl.cm.Cm; -import net.jxta.impl.cm.Srdi; -import net.jxta.impl.cm.SrdiIndex; -import net.jxta.impl.peergroup.StdPeerGroup; -import net.jxta.impl.protocol.DiscoveryConfigAdv; -import net.jxta.impl.protocol.DiscoveryQuery; -import net.jxta.impl.protocol.DiscoveryResponse; -import net.jxta.impl.protocol.ResolverQuery; -import net.jxta.impl.protocol.ResolverResponse; -import net.jxta.impl.protocol.SrdiMessageImpl; -import net.jxta.impl.resolver.InternalQueryHandler; -import net.jxta.impl.util.TimeUtils; -import net.jxta.logging.Logging; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.DiscoveryQueryMsg; -import net.jxta.protocol.DiscoveryResponseMsg; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.protocol.ResolverQueryMsg; -import net.jxta.protocol.ResolverResponseMsg; -import net.jxta.protocol.ResolverSrdiMsg; -import net.jxta.protocol.SrdiMessage; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.rendezvous.RendezvousEvent; -import net.jxta.rendezvous.RendezvousListener; -import net.jxta.resolver.ResolverService; -import net.jxta.resolver.SrdiHandler; -import net.jxta.service.Service; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.net.URI; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * This Discovery Service implementation provides a mechanism to discover - * Advertisements using the Resolver service and SRDI. - *

      - *

      This implementation uses the standard JXTA Peer Discovery Protocol - * (PDP). - *

      - *

      The DiscoveryService service also provides a way to obtain information - * from a specified peer and request other peer advertisements, this method is - * particularly useful in the case of a portal where new relationships may be - * established starting from a predetermined peer (perhaps described in address - * book, or through an invitation). - * - * @see net.jxta.discovery.DiscoveryService - * @see net.jxta.protocol.DiscoveryQueryMsg - * @see net.jxta.impl.protocol.DiscoveryQuery - * @see net.jxta.protocol.DiscoveryResponseMsg - * @see net.jxta.impl.protocol.DiscoveryResponse - * @see net.jxta.resolver.ResolverService - * @see JXTA Protocols Specification : Peer Discovery Protocol - */ -public class DiscoveryServiceImpl implements DiscoveryService, InternalQueryHandler, RendezvousListener, SrdiHandler, Srdi.SrdiInterface { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(DiscoveryServiceImpl.class.getName()); - - /** - * adv types - */ - final static String[] dirname = {"Peers", "Groups", "Adv"}; - - /** - * The Query ID which will be associated with remote publish operations. - */ - private final static int REMOTE_PUBLISH_QUERYID = 0; - - private final static String srdiIndexerFileName = "discoverySrdi"; - - /** - * The current resolver query ID. static to make debugging easier. - */ - private final static AtomicInteger qid = new AtomicInteger(0); - - /** - * The maximum number of responses we will return for ANY query. - */ - private final static int MAX_RESPONSES = 50; - - /** - * The cache manager we're going to use to cache jxta advertisements - */ - protected Cm cm; - - /** - * assignedID as a String. - */ - private PeerGroup group = null; - private String handlerName = null; - private ModuleImplAdvertisement implAdvertisement = null; - - private ResolverService resolver = null; - private RendezVousService rendezvous = null; - private MembershipService membership = null; - - private PeerID localPeerId = null; - - private boolean localonly = false; - private boolean alwaysUseReplicaPeer = false; - - private boolean stopped = true; - - /** - * The table of discovery listeners. - */ - private Set listeners = new HashSet(); - - /** - * The table of discovery query listeners. - */ - private Hashtable listenerTable = new Hashtable(); - - private final String checkPeerAdvLock = new String("Check/Update PeerAdvertisement Lock"); - private PeerAdvertisement lastPeerAdv = null; - private int lastModCount = -1; - - private boolean isRdv = false; - - private SrdiIndex srdiIndex = null; - private Srdi srdi = null; - private Thread srdiThread = null; - - private CredentialListener membershipCredListener = null; - private Credential credential = null; - private StructuredDocument credentialDoc = null; - - private long initialDelay = 60 * TimeUtils.ASECOND; - private long runInterval = 30 * TimeUtils.ASECOND; - - /** - * the discovery interface object - */ - private DiscoveryService discoveryInterface = null; - - /** - * Listener we use for membership property events. - */ - private class CredentialListener implements PropertyChangeListener { - - /** - * {@inheritDoc} - */ - public void propertyChange(PropertyChangeEvent evt) { - if ("defaultCredential".equals(evt.getPropertyName())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("New default credential event"); - } - - synchronized (DiscoveryServiceImpl.this) { - credential = (Credential) evt.getNewValue(); - credentialDoc = null; - - if (null != credential) { - try { - credentialDoc = credential.getDocument(MimeMediaType.XMLUTF8); - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not generate credential document", all); - } - } - } - } - } - } - } - - /** - * {@inheritDoc} - */ - public synchronized Service getInterface() { - if (discoveryInterface == null) { - discoveryInterface = new DiscoveryServiceInterface(this); - } - return discoveryInterface; - } - - /** - * {@inheritDoc} - */ - public Advertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * {@inheritDoc} - */ - public int getRemoteAdvertisements(String peer, int type, String attribute, String value, int threshold) { - - return getRemoteAdvertisements(peer, type, attribute, value, threshold, null); - } - - /** - * {@inheritDoc} - */ - public int getRemoteAdvertisements(String peer, int type, String attribute, String value, int threshold, DiscoveryListener listener) { - - int myQueryID = qid.incrementAndGet(); - - if (localonly || stopped) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("localonly, no network operations performed"); - } - return myQueryID; - } - - if (resolver == null) { - // warn about calling the service before it started - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("resolver has not started yet, query discarded."); - } - return myQueryID; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - StringBuilder query = new StringBuilder( - "Sending query#" + myQueryID + " for " + threshold + " " + dirname[type] + " advs"); - - if (attribute != null) { - query.append("\n\tattr = ").append(attribute); - if (value != null) { - query.append("\tvalue = ").append(value); - } - } - LOG.fine(query.toString()); - } - - long t0 = System.currentTimeMillis(); - - DiscoveryQueryMsg dquery = new DiscoveryQuery(); - - dquery.setDiscoveryType(type); - dquery.setAttr(attribute); - dquery.setValue(value); - dquery.setThreshold(threshold); - - if (listener != null) { - listenerTable.put(myQueryID, listener); - } - - ResolverQueryMsg query = new ResolverQuery(); - - query.setHandlerName(handlerName); - query.setCredential(credentialDoc); - query.setSrcPeer(localPeerId); - query.setQuery(dquery.toString()); - query.setQueryId(myQueryID); - - // check srdi - if (peer == null && srdiIndex != null) { - List res = srdiIndex.query(dirname[type], attribute, value, threshold); - - if (!res.isEmpty()) { - srdi.forwardQuery(res, query, threshold); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Srdi forward a query #" + myQueryID + " in " + (System.currentTimeMillis() - t0) + "ms."); - } - return myQueryID; - // nothing in srdi, get a starting point in rpv - } else if (group.isRendezvous() && attribute != null && value != null) { - PeerID destPeer = srdi.getReplicaPeer(dirname[type] + attribute + value); - - if (destPeer != null) { - if (!destPeer.equals(group.getPeerID())) { - // forward query increments the hopcount to indicate getReplica - // has been invoked once - srdi.forwardQuery(destPeer, query); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Srdi forward query #" + myQueryID + " to " + destPeer + " in " - + (System.currentTimeMillis() - t0) + "ms."); - } - return myQueryID; - } - } - } - } - - // no srdi, not a rendezvous, start the walk - resolver.sendQuery(peer, query); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - if (peer == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sent a query #" + myQueryID + " in " + (System.currentTimeMillis() - t0) + "ms."); - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sent a query #" + myQueryID + " to " + peer + " in " + (System.currentTimeMillis() - t0) + "ms."); - } - } - } - - return myQueryID; - } - - /** - * {@inheritDoc} - */ - public Enumeration getLocalAdvertisements(int type, String attribute, String value) throws IOException { - - if ((type > 2) || (type < 0)) { - throw new IllegalArgumentException("Unknown Advertisement type"); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - StringBuilder query = new StringBuilder("Searching for " + dirname[type] + " advs"); - - if (attribute != null) { - query.append("\n\tattr = ").append(attribute); - } - if (value != null) { - query.append("\tvalue = ").append(value); - } - LOG.fine(query.toString()); - } - - return Collections.enumeration(search(type, attribute, value, Integer.MAX_VALUE, false, null)); - } - - /** - * {@inheritDoc} - */ - public void init(PeerGroup pg, ID assignedID, Advertisement impl) throws PeerGroupException { - - group = pg; - handlerName = assignedID.toString(); - implAdvertisement = (ModuleImplAdvertisement) impl; - localPeerId = group.getPeerID(); - - ConfigParams confAdv = pg.getConfigAdvertisement(); - - // Get the config. If we do not have a config, we're done; we just keep - // the defaults (edge peer/no auto-rdv) - if (confAdv != null) { - Advertisement adv = null; - - try { - XMLDocument configDoc = (XMLDocument) confAdv.getServiceParam(assignedID); - - if (null != configDoc) { - adv = AdvertisementFactory.newAdvertisement(configDoc); - } - } catch (NoSuchElementException failed) {// ignored - } - - if (adv instanceof DiscoveryConfigAdv) { - DiscoveryConfigAdv discoConfigAdv = (DiscoveryConfigAdv) adv; - - alwaysUseReplicaPeer = discoConfigAdv.getForwardAlwaysReplica(); - - localonly |= discoConfigAdv.getLocalOnly(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - if (localonly) { - LOG.fine("localonly set to true via service parameters"); - } - if (alwaysUseReplicaPeer) { - LOG.fine("alwaysUseReplicaPeer set to true via service parameters"); - } - } - } - } - - cm = ((StdPeerGroup) group).getCacheManager(); - cm.setTrackDeltas(!localonly); - - // Initialize the peer adv tracking. - checkUpdatePeerAdv(); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Discovery Service : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID : ").append(group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tLocal Only : ").append(localonly); - configInfo.append("\n\t\tAlways Use ReplicaPeer : ").append(alwaysUseReplicaPeer); - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] arg) { - - // Now we know that the resolver is going to be there. - // The cm needs the resolver. The code is arranged so that - // until the resolver and the cm are created, we just pretend - // to be working. We have no requirement to be operational before - // startApp() is called, but we must tolerate our public methods - // being invoked. The reason for it is that services are registered - // upon return from init() so that other services startApp() methods - // can find them. (all startApp()s are called after all init()s - with - // a few exceptions). - - resolver = group.getResolverService(); - - if (null == resolver) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a resolver service"); - } - - return Module.START_AGAIN_STALLED; - } - - membership = group.getMembershipService(); - - if (null == membership) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a membership service"); - } - - return Module.START_AGAIN_STALLED; - } - - rendezvous = group.getRendezVousService(); - - if (null == rendezvous) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a rendezvous service"); - } - - return Module.START_AGAIN_STALLED; - } - - // local only discovery - if (!localonly) { - resolver.registerHandler(handlerName, this); - } - - // Get the initial credential doc - synchronized (this) { - membershipCredListener = new CredentialListener(); - membership.addPropertyChangeListener("defaultCredential", membershipCredListener); - - try { - membershipCredListener.propertyChange( - new PropertyChangeEvent(membership, "defaultCredential", null, membership.getDefaultCredential())); - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not get credential", all); - } - } - } - - if (rendezvous.isRendezVous()) { - beRendezvous(); - } else { - beEdge(); - } - - rendezvous.addListener(this); - - stopped = false; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Discovery service started"); - } - - return Module.START_OK; - } - - /** - * {@inheritDoc} - *

      - *

      Detach from the resolver - */ - public void stopApp() { - - stopped = true; - boolean failed = false; - - membership.removePropertyChangeListener("defaultCredential", membershipCredListener); - membershipCredListener = null; - credential = null; - credentialDoc = null; - - rendezvous.removeListener(this); - - if (resolver.unregisterHandler(handlerName) == null) { - failed = true; - } - - if (rendezvous.isRendezVous()) { - if (resolver.unregisterSrdiHandler(handlerName) == null) { - failed = true; - } - } - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING) && failed) { - LOG.warning("failed to unregister discovery from resolver."); - } - - // stop the DiscoverySrdiThread - if (srdiThread != null) { - srdi.stop(); - srdi = null; - } - - // Reset values in order to avoid cross-reference problems with GC - resolver = null; - group = null; - membership = null; - srdiIndex = null; - srdiThread = null; - rendezvous = null; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Discovery service stopped."); - } - } - - /** - * {@inheritDoc} - */ - public void flushAdvertisements(String id, int type) throws IOException { - if (stopped) { - return; - } - if ((type >= PEER) && (type <= ADV)) { - if (null != id) { - ID advID = ID.create(URI.create(id)); - String advName = advID.getUniqueValue().toString(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("flushing adv " + advName + " of type " + dirname[type]); - } - cm.remove(dirname[type], advName); - } else { - // XXX bondolo 20050902 For historical purposes we ignore null - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Flush request by type IGNORED. You must delete advertisements individually."); - } - } - } else { - throw new IllegalArgumentException("Invalid Advertisement type."); - } - } - - /** - * {@inheritDoc} - */ - public void flushAdvertisement(Advertisement adv) throws IOException { - if (stopped) { - return; - } - - int type; - - if (adv instanceof PeerAdvertisement) { - type = PEER; - } else if (adv instanceof PeerGroupAdvertisement) { - type = GROUP; - } else { - type = ADV; - } - - ID id = adv.getID(); - String advName; - - if (id != null && !id.equals(ID.nullID)) { - advName = id.getUniqueValue().toString(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Flushing adv " + advName + " of type " + dirname[type]); - } - } else { - XMLDocument doc; - - try { - doc = (XMLDocument) adv.getDocument(MimeMediaType.XMLUTF8); - } catch (Exception everything) { - IOException failure = new IOException("Failure removing Advertisement"); - - failure.initCause(everything); - throw failure; - } - advName = Cm.createTmpName(doc); - } - - if (advName != null) { - cm.remove(dirname[type], advName); - } - } - - /** - * {@inheritDoc} - */ - public void publish(Advertisement adv) throws IOException { - publish(adv, DiscoveryService.DEFAULT_LIFETIME, DiscoveryService.DEFAULT_EXPIRATION); - } - - /** - * {@inheritDoc} - */ - public void publish(Advertisement adv, long lifetime, long expiration) throws IOException { - - if (stopped) { - return; - } - - ID advID; - String advName; - - int type; - - if (adv instanceof PeerAdvertisement) { - type = PEER; - } else if (adv instanceof PeerGroupAdvertisement) { - type = GROUP; - } else { - type = ADV; - } - - advID = adv.getID(); - - // if we dont have a unique id for the adv, use the hash method - if ((null == advID) || advID.equals(ID.nullID)) { - XMLDocument doc; - - try { - doc = (XMLDocument) adv.getDocument(MimeMediaType.XMLUTF8); - } catch (Exception everything) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to generated document from advertisement", everything); - } - IOException failure = new IOException("Failed to generate document from advertisement"); - - failure.initCause(everything); - throw failure; - } - - try { - advName = Cm.createTmpName(doc); - } catch (IllegalStateException ise) { - IOException failure = new IOException("Failed to generate tempname from advertisement"); - - failure.initCause(ise); - throw failure; - } - } else { - advName = advID.getUniqueValue().toString(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Publishing a " + adv.getAdvType() + " as " + dirname[type] + " / " + advName + "\n\texpiration : " - + expiration + "\tlifetime :" + lifetime); - } - - // save it - cm.save(dirname[type], advName, adv, lifetime, expiration); - } - - /** - * {@inheritDoc} - */ - public void remotePublish(Advertisement adv) { - remotePublish(null, adv, DiscoveryService.DEFAULT_EXPIRATION); - } - - /** - * {@inheritDoc} - */ - public void remotePublish(Advertisement adv, long expiration) { - remotePublish(null, adv, expiration); - } - - /** - * {@inheritDoc} - */ - public void remotePublish(String peerid, Advertisement adv) { - remotePublish(peerid, adv, DiscoveryService.DEFAULT_EXPIRATION); - } - - /** - * {@inheritDoc} - */ - public void processResponse(ResolverResponseMsg response) { - processResponse(response, null); - } - - /** - * {@inheritDoc} - */ - public void processResponse(ResolverResponseMsg response, EndpointAddress srcAddress) { - if (stopped) { - return; - } - - long t0 = System.currentTimeMillis(); - DiscoveryResponse res; - - try { - XMLDocument asDoc = (XMLDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8 - , - new StringReader(response.getResponse())); - - res = new DiscoveryResponse(asDoc); - } catch (Exception e) { - // we don't understand this msg, let's skip it - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to Read Discovery Response", e); - } - return; - } - - /* - PeerAdvertisement padv = res.getPeerAdvertisement(); - if (padv == null) - return; - - if (LOG.isLoggable(Level.FINE)) { - LOG.fine("Got a " + dirname[res.getDiscoveryType()] + - " from "+padv.getName()+ " response : " + - res.getQueryAttr() + " = " + res.getQueryValue()); - } - - try { - // The sender does not put an expiration on that one, but - // we do not want to keep it around for more than the - // default duration. It may get updated or become invalid. - publish(padv, PEER, DEFAULT_EXPIRATION, DEFAULT_EXPIRATION); - } catch (Exception e) { - if (LOG.isLoggable(Level.FINE)) { - LOG.fine(e, e); - } - return; - } - */ - Advertisement adv; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Processing responses for query #" + response.getQueryId()); - } - - Enumeration en = res.getAdvertisements(); - Enumeration exps = res.getExpirations(); - - while (en.hasMoreElements()) { - adv = en.nextElement(); - long exp = exps.nextElement(); - - if (exp > 0 && adv != null) { - try { - publish(adv, exp, exp); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Error publishing Advertisement", e); - } - } - } - } - - DiscoveryEvent newevent = new DiscoveryEvent(srcAddress, res, response.getQueryId()); - - DiscoveryListener dl = listenerTable.get(new Integer(response.getQueryId())); - - if (dl != null) { - try { - dl.discoveryEvent(new DiscoveryEvent(srcAddress, res, response.getQueryId())); - } catch (Throwable all) { - LOG.log(Level.SEVERE, "Uncaught Throwable in listener :" + Thread.currentThread().getName(), all); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("processed a response for query #" + response.getQueryId() + " in :" + (System.currentTimeMillis() - t0)); - } - - // are there any registered discovery listeners, - // generate the event and callback. - t0 = System.currentTimeMillis(); - - DiscoveryListener[] allListeners = listeners.toArray(new DiscoveryListener[0]); - - for (DiscoveryListener allListener : allListeners) { - try { - allListener.discoveryEvent(newevent); - } catch (Throwable all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING - , - "Uncaught Throwable in listener (" + allListener.getClass().getName() + ") :" - + Thread.currentThread().getName() - , - all); - } - } - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Called all listenters to query #" + response.getQueryId() + " in :" + (System.currentTimeMillis() - t0)); - } - } - - /** - * {@inheritDoc} - */ - public int processQuery(ResolverQueryMsg query) { - - return processQuery(query, null); - } - - /** - * {@inheritDoc} - */ - public int processQuery(ResolverQueryMsg query, EndpointAddress srcAddress) { - if (stopped) { - return ResolverService.OK; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - if (srcAddress != null) { - LOG.fine("Processing query #" + query.getQueryId() + " from:" + srcAddress); - } else { - LOG.fine("Processing query #" + query.getQueryId() + " from: unknown"); - } - } - - List results; - List expirations = new ArrayList(); - DiscoveryQuery dq; - long t0 = System.currentTimeMillis(); - - try { - XMLDocument asDoc = (XMLDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, new StringReader(query.getQuery())); - - dq = new DiscoveryQuery(asDoc); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Malformed query : ", e); - } - return ResolverService.OK; - } - - if ((dq.getThreshold() < 0) || (dq.getDiscoveryType() < PEER) || (dq.getDiscoveryType() > ADV)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Malformed query"); - } - return ResolverService.OK; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Got a " + dirname[dq.getDiscoveryType()] + " query #" + query.getQueryId() + " query :" + dq.getAttr() - + " = " + dq.getValue()); - } - - /* - // Get the Peer Adv from the query and publish it. - PeerAdvertisement padv = dq.getPeerAdvertisement(); - try { - if (!(padv.getPeerID().toString()).equals(localPeerId)) { - // publish others only. Since this one comes from outside, - // we must not keep it beyond its expiration time. - // FIXME: [jice@jxta.org 20011112] In theory there should - // be an expiration time associated with it in the msg, like - // all other items. - publish(padv, PEER, DEFAULT_EXPIRATION, DEFAULT_EXPIRATION); - } - } catch (Exception e) { - if (LOG.isLoggable(Level.FINE)) { - LOG.fine("Bad Peer Adv in Discovery Query", e); - } - } - */ - - /* - * threshold==0 and type==PEER is a special case. In this case we are - * responding for the purpose of providing our own adv only. - */ - int thresh = Math.min(dq.getThreshold(), MAX_RESPONSES); - - /* - * threshold==0 and type==PEER is a special case. In this case we are - * responding for the purpose of providing our own adv only. - */ - if ((dq.getDiscoveryType() == PEER) && (0 == dq.getThreshold())) { - respond(query, dq, Collections.singletonList(group.getPeerAdvertisement().toString()) - , - Collections.singletonList(DiscoveryService.DEFAULT_EXPIRATION)); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Responding to query #" + query.getQueryId() + " in :" + (System.currentTimeMillis() - t0)); - } - return ResolverService.OK; - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("start local search query" + dq.getAttr() + " " + dq.getValue()); - } - results = search(dq.getDiscoveryType(), dq.getAttr(), dq.getValue(), thresh, true, expirations); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("start local search pruned " + results.size()); - } - } - - // We only share the advs with > 0 expiration time. - Iterator eachExpiration = expirations.iterator(); - Iterator eachAdv = results.iterator(); - - while (eachExpiration.hasNext()) { - eachAdv.next(); - - if (eachExpiration.next() <= 0) { - eachAdv.remove(); - eachExpiration.remove(); - } - } - - if (!results.isEmpty()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Responding to " + dirname[dq.getDiscoveryType()] + " Query : " + dq.getAttr() + " = " + dq.getValue()); - } - respond(query, dq, results, expirations); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Responded to query #" + query.getQueryId() + " in :" + (System.currentTimeMillis() - t0)); - } - return ResolverService.OK; - } else { - // If this peer is a rendezvous, simply let the resolver - // re-propagate the query. - // If this peer is not a rendez, just discard the query. - if (!group.isRendezvous()) { - return ResolverService.OK; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Querying SrdiIndex query #" + query.getQueryId()); - } - List res = srdiIndex.query(dirname[dq.getDiscoveryType()], dq.getAttr(), dq.getValue(), thresh); - - if (!res.isEmpty()) { - srdi.forwardQuery(res, query, thresh); - return ResolverService.OK; - } else if (query.getHopCount() == 0) { - PeerID destPeer = srdi.getReplicaPeer(dirname[dq.getDiscoveryType()] + dq.getAttr() + dq.getValue()); - - // destPeer can be null in a small rpv (<3) - if (destPeer != null) { - if (!destPeer.equals(group.getPeerID())) { - srdi.forwardQuery(destPeer, query); - return ResolverService.OK; - } else { - // start the walk since this peer is this the starting peer - query.incrementHopCount(); - } - } - } - } - return ResolverService.Repropagate; - } - - private void respond(ResolverQueryMsg query, DiscoveryQuery dq, List results, List expirations) { - if (localonly || stopped) { - return; - } - - ResolverResponseMsg response; - DiscoveryResponse dresponse = new DiscoveryResponse(); - - // peer adv is optional, skip - dresponse.setDiscoveryType(dq.getDiscoveryType()); - dresponse.setQueryAttr(dq.getAttr()); - dresponse.setQueryValue(dq.getValue()); - dresponse.setResponses(results); - dresponse.setExpirations(expirations); - - // create a response from the query - response = query.makeResponse(); - response.setCredential(credentialDoc); - response.setResponse(dresponse.toString()); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Responding to " + query.getSrcPeer()); - } - - resolver.sendResponse(query.getSrcPeer().toString(), response); - } - - /** - * {@inheritDoc} - */ - public synchronized void addDiscoveryListener(DiscoveryListener listener) { - - listeners.add(listener); - } - - /** - * {@inheritDoc} - */ - public synchronized boolean removeDiscoveryListener(DiscoveryListener listener) { - - Iterator> e = listenerTable.entrySet().iterator(); - - while (e.hasNext()) { - Map.Entry anEntry = e.next(); - - if (listener == anEntry.getValue()) { - e.remove(); - } - } - return (listeners.remove(listener)); - } - - /** - * {@inheritDoc} - */ - public void remotePublish(String peerid, Advertisement adv, long timeout) { - - if (localonly || stopped) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("localonly, no network operations performed"); - } - return; - } - int type; - - if (adv instanceof PeerAdvertisement) { - type = PEER; - } else if (adv instanceof PeerGroupAdvertisement) { - type = GROUP; - } else { - type = ADV; - } - remotePublish(peerid, adv, type, timeout); - } - - /* - * remote publish the advertisement - */ - private void remotePublish(String peerid, Advertisement adv, int type, long expiration) { - - if (localonly || stopped) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("localonly, no network operations performed"); - } - return; - } - - // In case this is invoked before startApp(). - if (resolver == null) { - return; - } - - switch (type) { - case PEER: - if (adv instanceof PeerAdvertisement) { - break; - } - throw new IllegalArgumentException("Not a peer advertisement"); - - case GROUP: - if (adv instanceof PeerGroupAdvertisement) { - break; - } - throw new IllegalArgumentException("Not a peergroup advertisement"); - - case ADV: - break; - - default: - throw new IllegalArgumentException("Unknown advertisement type"); - } - - List advert = new ArrayList(1); - List expirations = new ArrayList(1); - - advert.add(adv.toString()); - expirations.add(expiration); - - DiscoveryResponseMsg dresponse = new DiscoveryResponse(); - - dresponse.setDiscoveryType(type); - dresponse.setResponses(advert); - dresponse.setExpirations(expirations); - - ResolverResponseMsg pushRes = new ResolverResponse(); - - pushRes.setHandlerName(handlerName); - pushRes.setCredential(credentialDoc); - pushRes.setQueryId(REMOTE_PUBLISH_QUERYID); - pushRes.setResponse(dresponse.toString()); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Remote publishing "); - } - - resolver.sendResponse(peerid, pushRes); - } - - /** - * Search for a doc, that matches attr, and value - * bytes is set to true if the caller wants wire format of the - * advertisement, or set to false if caller wants Advertisement - * objects. - * - * @param type Discovery type PEER, GROUP, ADV - * @param threshold the upper limit of responses from one peer - * @param bytes flag to indicate how the results are returned-- advs, or streams - * @param expirations List containing the expirations associated with is returned - * @param attr attribute name to narrow discovery to Valid values for - * this parameter are null (don't care), or exact element name in the - * advertisement of interest (e.g. "Name") - * @param value Value - * @return list of results either as docs, or Strings - */ - private List search(int type, String attr, String value, int threshold, boolean bytes, List expirations) { - - if (stopped) { - return new ArrayList(); - } - - if (type == PEER) { - checkUpdatePeerAdv(); - } - - List results; - - if (threshold <= 0) { - throw new IllegalArgumentException("threshold must be greater than zero"); - } - - if (expirations != null) { - expirations.clear(); - } - - if (attr != null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Searching for " + threshold + " entries of type : " + dirname[type]); - } - // a discovery query with a specific search criteria. - results = cm.search(dirname[type], attr, value, threshold, expirations); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting " + threshold + " entries of type : " + dirname[type]); - } - // Returning any entry that exists - results = cm.getRecords(dirname[type], threshold, expirations); - } - - if (results.isEmpty() || bytes) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Returning " + results.size() + " results"); - } - - // nothing more to do; - return results; - } - - // Convert the input streams returned by the cm into Advertisements. - - List advertisements = new ArrayList(); - - for (int i = 0; i < results.size(); i++) { - InputStream bis = null; - - try { - bis = (InputStream) results.get(i); - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, bis); - Advertisement adv = AdvertisementFactory.newAdvertisement(asDoc); - - advertisements.add(adv); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building advertisment", e); - } - - // we won't be including this advertisement so remove it's expiration. - if (null != expirations) { - expirations.remove(i); - } - - } finally { - if (null != bis) { - try { - bis.close(); - } catch (IOException ignored) { - // ignored - } - } - bis = null; - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Returning " + advertisements.size() + " advertisements"); - } - - return advertisements; - } - - /** - * {@inheritDoc} - */ - public long getAdvExpirationTime(ID id, int type) { - if (stopped) { - return -1; - } - String advName; - - if (id != null && !id.equals(ID.nullID)) { - advName = id.getUniqueValue().toString(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting expiration time of " + advName + " of type " + dirname[type]); - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("invalid attempt to get advertisement expiration time of NullID"); - } - return -1; - } - - return cm.getExpirationtime(dirname[type], advName); - } - - /** - * {@inheritDoc} - */ - public long getAdvLifeTime(ID id, int type) { - if (id == null || id.equals(ID.nullID) || stopped) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("invalid attempt to get advertisement lifetime of a NullID"); - } - return -1; - } - - String advName = id.getUniqueValue().toString(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting lifetime of " + advName + " of type " + dirname[type]); - } - - return cm.getLifetime(dirname[type], advName); - } - - /** - * {@inheritDoc} - */ - public long getAdvExpirationTime(Advertisement adv) { - if (stopped) { - return -1; - } - int type; - - if (adv instanceof PeerAdvertisement) { - type = PEER; - } else if (adv instanceof PeerGroupAdvertisement) { - type = GROUP; - } else { - type = ADV; - } - - String advName; - ID id = adv.getID(); - - if (id != null && !id.equals(ID.nullID)) { - advName = id.getUniqueValue().toString(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("attempting to getAdvExpirationTime on " + advName + " of type " + dirname[type]); - } - } else { - XMLDocument doc; - - try { - doc = (XMLDocument) adv.getDocument(MimeMediaType.XMLUTF8); - } catch (Exception everything) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to get document", everything); - } - return -1; - } - advName = Cm.createTmpName(doc); - } - - return cm.getExpirationtime(dirname[type], advName); - } - - /** - * {@inheritDoc} - */ - public long getAdvLifeTime(Advertisement adv) { - if (stopped) { - return -1; - } - int type; - - if (adv instanceof PeerAdvertisement) { - type = PEER; - } else if (adv instanceof PeerGroupAdvertisement) { - type = GROUP; - } else { - type = ADV; - } - - ID id = adv.getID(); - String advName; - - if (id != null && !id.equals(ID.nullID)) { - advName = id.getUniqueValue().toString(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("attempting to getAdvLifeTime " + advName + " of type " + dirname[type]); - } - } else { - XMLDocument doc; - - try { - doc = (XMLDocument) adv.getDocument(MimeMediaType.XMLUTF8); - } catch (Exception everything) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to get document", everything); - } - return -1; - } - advName = Cm.createTmpName(doc); - } - return cm.getLifetime(dirname[type], advName); - } - - /** - * {@inheritDoc} - */ - public boolean processSrdi(ResolverSrdiMsg message) { - if (stopped) { - return true; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + group.getPeerGroupID() + "] Received an SRDI messsage"); - } - - SrdiMessage srdiMsg; - - try { - XMLDocument asDoc = (XMLDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, new StringReader(message.getPayload())); - - srdiMsg = new SrdiMessageImpl(asDoc); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed parsing srdi message", e); - } - return false; - } - - PeerID pid = srdiMsg.getPeerID(); - - for (Object o : srdiMsg.getEntries()) { - SrdiMessage.Entry entry = (SrdiMessage.Entry) o; - - srdiIndex.add(srdiMsg.getPrimaryKey(), entry.key, entry.value, pid, entry.expiration); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Primary Key [" + srdiMsg.getPrimaryKey() + "] key [" + entry.key + "] value [" + entry.value + "] exp [" - + entry.expiration + "]"); - } - } - srdi.replicateEntries(srdiMsg); - return true; - } - - /** - * {@inheritDoc} - */ - public void messageSendFailed(PeerID peerid, OutgoingMessageEvent e) { - if (srdiIndex != null) { - srdiIndex.remove(peerid); - } - } - - /** - * {@inheritDoc} - */ - public void pushEntries(boolean all) { - - pushSrdi(null, PEER, all); - pushSrdi(null, GROUP, all); - pushSrdi(null, ADV, all); - } - - /** - * push srdi entries - * - * @param all if true push all entries, otherwise just deltas - * @param peer peer id - * @param type if true sends all entries - */ - protected void pushSrdi(ID peer, int type, boolean all) { - if (stopped) { - return; - } - - List entries; - - if (all) { - entries = cm.getEntries(dirname[type], true); - } else { - entries = cm.getDeltas(dirname[type]); - } - - if (!entries.isEmpty()) { - SrdiMessage srdiMsg; - - try { - srdiMsg = new SrdiMessageImpl(group.getPeerID(), 1, // ttl of 1, ensure it is replicated - dirname[type], entries); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Pushing " + entries.size() + (all ? " entries" : " deltas") + " of type " + dirname[type]); - } - srdi.pushSrdi(peer, srdiMsg); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception pushing SRDI Entries", e); - } - } - } else { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("No" + (all ? " entries" : " deltas") + " of type " + dirname[type] + " to push"); - } - } - } - - /** - * {@inheritDoc} - */ - public synchronized void rendezvousEvent(RendezvousEvent event) { - - int theEventType = event.getType(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + group.getPeerGroupName() + "] Processing " + event); - } - - switch (theEventType) { - - case RendezvousEvent.RDVCONNECT: - case RendezvousEvent.RDVRECONNECT: - // start tracking deltas - cm.setTrackDeltas(true); - break; - - case RendezvousEvent.CLIENTCONNECT: - case RendezvousEvent.CLIENTRECONNECT: - break; - - case RendezvousEvent.RDVFAILED: - case RendezvousEvent.RDVDISCONNECT: - // stop tracking deltas until we connect again - cm.setTrackDeltas(false); - break; - - case RendezvousEvent.CLIENTFAILED: - case RendezvousEvent.CLIENTDISCONNECT: - break; - - case RendezvousEvent.BECAMERDV: - beRendezvous(); - break; - - case RendezvousEvent.BECAMEEDGE: - beEdge(); - break; - - default: - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning(MessageFormat.format("[{0}] Unexpected RDV event : {1}", group.getPeerGroupName(), event)); - } - break; - } - } - - /** - * Checks to see if the local peer advertisement has been updated and if - * it has then republish it to the CM. - */ - private void checkUpdatePeerAdv() { - PeerAdvertisement newPadv = group.getPeerAdvertisement(); - int newModCount = newPadv.getModCount(); - - boolean updated = false; - - synchronized (checkPeerAdvLock) { - if ((lastPeerAdv != newPadv) || (lastModCount < newModCount)) { - lastPeerAdv = newPadv; - lastModCount = newModCount; - updated = true; - } - - if (updated) { - // Publish the local Peer Advertisement - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("publishing local advertisement"); - } - - // This is our own; we can publish it for a long time in our cache - publish(newPadv, INFINITE_LIFETIME, DEFAULT_EXPIRATION); - } catch (Exception ignoring) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not publish local peer advertisement: ", ignoring); - } - } - } - } - } - - /** - * Change the behavior to be an rendezvous Peer Discovery Service. - * If the Service was acting as an Edge peer, cleanup. - */ - private synchronized void beRendezvous() { - - if (isRdv && (srdi != null || srdiIndex != null)) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Already a rendezvous -- No Switch is needed"); - } - return; - } - - isRdv = true; - - // rdv peers do not need to track deltas - cm.setTrackDeltas(false); - - if (srdiIndex == null) { - srdiIndex = new SrdiIndex(group, srdiIndexerFileName); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("srdiIndex created"); - } - - } - - // Kill SRDI, create a new one. - if (srdi != null) { - srdi.stop(); - if (srdiThread != null) { - srdiThread = null; - } - srdi = null; - } - - if (!localonly) { - srdi = new Srdi(group, handlerName, this, srdiIndex, initialDelay, runInterval); - resolver.registerSrdiHandler(handlerName, this); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("srdi created, and registered as an srdi handler "); - } - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Switched to Rendezvous peer role."); - } - } - - /** - * Change the behavior to be an Edge Peer Discovery Service. - * If the Service was acting as a Rendezvous, cleanup. - */ - private synchronized void beEdge() { - - // make sure we have been here before - if (!isRdv && srdiThread != null) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Already an Edge peer -- No Switch is needed."); - } - return; - } - - isRdv = false; - if (!rendezvous.getConnectedPeerIDs().isEmpty()) { - // if we have a rendezvous connection track deltas, otherwise wait - // for a connect event to set this option - cm.setTrackDeltas(true); - } - if (srdiIndex != null) { - srdiIndex.stop(); - srdiIndex = null; - resolver.unregisterSrdiHandler(handlerName); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("stopped cache and unregistered from resolver"); - } - } - - // Kill SRDI - if (srdi != null) { - srdi.stop(); - if (srdiThread != null) { - srdiThread = null; - } - srdi = null; - } - - if (!localonly) { - // Create a new SRDI - srdi = new Srdi(group, handlerName, this, null, initialDelay, runInterval); - - // only edge peers distribute srdi - srdiThread = new Thread(group.getHomeThreadGroup(), srdi, "Discovery Srdi Thread"); - srdiThread.setDaemon(true); - srdiThread.start(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Started SRDIThread"); - } - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Switched to a Edge peer role."); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/discovery/DiscoveryServiceInterface.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/discovery/DiscoveryServiceInterface.java deleted file mode 100644 index 4562ef6c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/discovery/DiscoveryServiceInterface.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.discovery; - - -import java.util.Enumeration; -import java.io.IOException; - -import net.jxta.discovery.DiscoveryListener; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.service.Service; - - -/** - * Provides a pure interface object that permits interaction with the actual - * Discovery Service implementation without giving access to the real object. - */ -public final class DiscoveryServiceInterface implements DiscoveryService { - - private DiscoveryServiceImpl impl; - - /** - * Only authorized constructor - * - * @param theRealThing The actual discovery implementation - */ - protected DiscoveryServiceInterface(DiscoveryServiceImpl theRealThing) { - impl = theRealThing; - } - - /** - * {@inheritDoc} - */ - public Service getInterface() { - return this; - } - - /** - * {@inheritDoc} - */ - public Advertisement getImplAdvertisement() { - return impl.getImplAdvertisement(); - } - - /** - * {@inheritDoc} - * - *

      FIXME: This is meaningless for the interface object; - * it is there only to satisfy the requirements of the - * interface that we implement. Ultimately, the API should define - * two levels of interfaces: one for the real service implementation - * and one for the interface object. Right now it feels a bit heavy - * to so that since the only different between the two would be - * init() and may-be getName(). - */ - public void init(PeerGroup pg, ID assignedID, Advertisement impl) {} - - /** - * {@inheritDoc} - * - *

      This is here for temporary class hierarchy reasons. - * it is ALWAYS ignored. By definition, the interface object - * protects the real object's start/stop methods from being called - */ - public int startApp(String[] arg) { - return 0; - } - - /** - * {@inheritDoc} - * - *

      This is here for temporary class hierarchy reasons. - * it is ALWAYS ignored. By definition, the interface object - * protects the real object's start/stop methods from being called - * - *

      This request is currently ignored. - */ - public void stopApp() {} - - /** - * {@inheritDoc} - */ - public int getRemoteAdvertisements(String peer, int type, String attribute, String value, int threshold) { - - return impl.getRemoteAdvertisements(peer, type, attribute, value, threshold); - } - - /** - * {@inheritDoc} - */ - public int getRemoteAdvertisements(String peer, int type, String attribute, String value, int threshold, DiscoveryListener listener) { - return impl.getRemoteAdvertisements(peer, type, attribute, value, threshold, listener); - } - - /** - * {@inheritDoc} - */ - public Enumeration getLocalAdvertisements(int type, String attribute, String value) throws IOException { - return impl.getLocalAdvertisements(type, attribute, value); - } - - /** - * {@inheritDoc} - */ - public void flushAdvertisement(Advertisement adv) throws IOException { - - impl.flushAdvertisement(adv); - } - - /** - * {@inheritDoc} - */ - public void flushAdvertisements(String id, int type) throws IOException { - impl.flushAdvertisements(id, type); - } - - /** - * {@inheritDoc} - */ - public long getAdvExpirationTime(ID id, int type) { - return impl.getAdvExpirationTime(id, type); - } - - /** - * {@inheritDoc} - */ - public long getAdvLifeTime(ID id, int type) { - return impl.getAdvLifeTime(id, type); - } - - /** - * {@inheritDoc} - */ - public long getAdvExpirationTime(Advertisement adv) { - return impl.getAdvExpirationTime(adv); - } - - /** - * {@inheritDoc} - */ - public long getAdvLifeTime(Advertisement adv) { - return impl.getAdvLifeTime(adv); - } - - /** - * {@inheritDoc} - */ - public void publish(Advertisement adv) throws IOException { - impl.publish(adv); - } - - /** - * {@inheritDoc} - */ - public void publish(Advertisement adv, long lifetime, long expiration) throws IOException { - - impl.publish(adv, lifetime, expiration); - } - - /** - * {@inheritDoc} - */ - public void remotePublish(Advertisement adv) { - impl.remotePublish(adv); - } - - /** - * {@inheritDoc} - */ - public void remotePublish(Advertisement adv, long expiration) { - impl.remotePublish(adv, expiration); - } - - /** - * {@inheritDoc} - */ - public void remotePublish(String peerid, Advertisement adv) { - impl.remotePublish(peerid, adv); - } - - /** - * {@inheritDoc} - */ - public void remotePublish(String peerid, Advertisement adv, long expiration) { - impl.remotePublish(peerid, adv, expiration); - } - - /** - * {@inheritDoc} - */ - public synchronized void addDiscoveryListener(DiscoveryListener listener) { - impl.addDiscoveryListener(listener); - } - - /** - * {@inheritDoc} - */ - public synchronized boolean removeDiscoveryListener(DiscoveryListener listener) { - return (impl.removeDiscoveryListener(listener)); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/discovery/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/discovery/package.html deleted file mode 100644 index c225a79d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/discovery/package.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.discovery.DiscoveryService} implementation which - implements the standard JXTA Peer Discovery Protocol (PDP). - - @see net.jxta.discovery.DiscoveryService - @see net.jxta.resolver.ResolverService - @see JXTA Protocols Specification : Peer Discovery Protocol - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/DOMXMLDocument.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/DOMXMLDocument.java deleted file mode 100644 index d10ca087..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/DOMXMLDocument.java +++ /dev/null @@ -1,490 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.document; - - -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import java.io.IOException; -import java.lang.reflect.UndeclaredThrowableException; -import javax.xml.parsers.ParserConfigurationException; - -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentType; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import org.w3c.dom.ls.DOMImplementationLS; -import org.w3c.dom.ls.LSSerializer; -import org.w3c.dom.ls.LSOutput; - -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentFactory.Instantiator.ExtensionMapping; -import net.jxta.document.XMLDocument; - -import net.jxta.impl.document.TextDocumentCommon.Utils; - - -/** - * This class is an implementation of the StructuredDocument interface using - * DOM - * - * @see W3C Document Object Model (DOM) - * @see DOM Java Language Binding - * @see Document Object Model (DOM) Level 3 Load and Save Specification - * @see Java API for XML Processing (JAXP) - * @see org.w3c.dom - */ -public class DOMXMLDocument extends DOMXMLElement implements XMLDocument { - - private static final class Instantiator implements StructuredDocumentFactory.TextInstantiator { - - /** - * The MIME Media Types which this StructuredDocument is - * capable of emitting. - */ - private static final MimeMediaType[] myTypes = { - MimeMediaType.XML_DEFAULTENCODING, - new MimeMediaType("Application", "Xml") - }; - - /** - * these are the file extensions which are likely to contain files of - * the type i like. - */ - private static final ExtensionMapping[] myExtensions = { - new ExtensionMapping("xml", myTypes[0]), - new ExtensionMapping("xml", null) - }; - - /** - * Creates new XMLDocumentInstantiator - */ - public Instantiator() {} - - /** - * {@inheritDoc} - */ - public MimeMediaType[] getSupportedMimeTypes() { - return (myTypes); - } - - /** - * {@inheritDoc} - */ - public ExtensionMapping[] getSupportedFileExtensions() { - return (myExtensions); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, String doctype) { - return new DOMXMLDocument(mimeType, doctype); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, String doctype, String value) { - return new DOMXMLDocument(mimeType, doctype, value); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, InputStream source) throws IOException { - return new DOMXMLDocument(mimeType, source); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, Reader source) throws IOException { - return new DOMXMLDocument(mimeType, source); - } - - } - - public static final StructuredDocumentFactory.TextInstantiator INSTANTIATOR = new Instantiator(); - - private MimeMediaType mimeType; - - /** - * Constructor for new instances of DOMXMLDocument - * with a value for the root element. - * - * @param mimeType This is the MIME Media Type being requested. In general - * it should be equivalent with the MIME Media Type returned by - * {@link #getMimeType()}. A StructuredDocument - * sub-class may, however, support more than one MIME Media type so this may be a - * true parameter. XMLDocument supports additional the MIME Media Type parameters, - * "charset". The charset parameter must be a value per IETF RFC 2279 or ISO-10646. - * @param docType Used as the root type of this document. {@link net.jxta.document.XMLDocument} uses this as the XML - * DOCTYPE. - * @param value String value to be associated with the root element. - * null if none is wanted. - * @throws RuntimeException Exceptions generated by the underlying implementation. - */ - private DOMXMLDocument(final MimeMediaType mimeType, final String docType, final String value) { - super(null, null); - this.root = this; - - this.mimeType = mimeType; - - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - - docBuilderFactory.setNamespaceAware(true); - docBuilderFactory.setValidating(false); - try { - DocumentBuilder dataDocBuilder = docBuilderFactory.newDocumentBuilder(); - DOMImplementation domImpl = dataDocBuilder.getDOMImplementation(); - DocumentType doctypeNode = domImpl.createDocumentType(docType, null, null); - - domNode = domImpl.createDocument("http://jxta.org", docType, doctypeNode); - } catch (ParserConfigurationException misconfig) { - throw new UndeclaredThrowableException(misconfig); - } - - if (value != null) { - Node text = ((Document) domNode).createTextNode(value); - - ((Document) domNode).getDocumentElement().appendChild(text); - } - } - - /** - * Constructor for new instances of DOMXMLDocument - * - * @param mimeType This is the MIME Media Type being requested. In general it should be equivalent with - * the MIME Media Type returned by {@link #getMimeType()}. A StructuredDocument - * sub-class may, however, support more than one MIME Media type so this may be a - * true parameter. XMLDocument supports additional the MIME Media Type parameters, - * "charset". The charset parameter must be a value per IETF RFC 2279 or ISO-10646. - * @param docType Used as the root type of this document. {@link net.jxta.document.XMLDocument} uses this as the XML - * DOCTYPE. - * @throws RuntimeException Exceptions generated by the underlying implementation. - */ - private DOMXMLDocument(final MimeMediaType mimeType, final String docType) { - this(mimeType, docType, null); - } - - /** - * Constructor for existing documents. - * - * @param mimeType This is the MIME Media Type being requested. In general - * it should be equivalent with the MIME Media Type returned by - * {@link #getMimeType()}. A StructuredDocument sub-class may, - * however, support more than one MIME Media type so this may be a - * true parameter. XMLDocument supports additional the MIME Media Type parameters, - * "charset". The charset parameter must be a value per IETF RFC 2279 or ISO-10646. - * @param stream Contains the input used to construct this object. This stream should be of a type - * conformant with the type specified by the MIME Media Type "charset" parameter. - * @throws RuntimeException Propagates exceptions from the underlying implementation. - * @throws java.io.IOException Thrown for failures processing the document. - */ - private DOMXMLDocument(final MimeMediaType mimeType, final InputStream stream) throws IOException { - super(null, null); - this.root = this; - - this.mimeType = mimeType; - - String charset = mimeType.getParameter("charset"); - - Reader source; - - if (charset == null) { - source = new InputStreamReader(stream); - } else { - source = new InputStreamReader(stream, charset); - } - - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - - docBuilderFactory.setNamespaceAware(true); - docBuilderFactory.setValidating(false); - try { - DocumentBuilder dataDocBuilder = docBuilderFactory.newDocumentBuilder(); - - domNode = dataDocBuilder.parse(new InputSource(source)); - } catch (ParserConfigurationException misconfig) { - throw new UndeclaredThrowableException(misconfig); - } catch (SAXException parseError) { - throw new IOException(parseError.toString()); - } - } - - /** - * Constructor for existing documents. - * - * @param mimeType This is the MIME Media Type being requested. In general - * it should be equivalent with the MIME Media Type returned by - * {@link #getMimeType()}. A StructuredDocument sub-class may, - * however, support more than one MIME Media type so this may be a - * true parameter. XMLDocument supports additional the MIME Media Type parameters, - * "charset". The charset parameter must be a value per IETF RFC 2279 or ISO-10646. - * @param source Contains the input used to construct this object. This reader - * should be of a type conformant with the type specified by the MIME Media Type - * "charset" parameter. - * @throws RuntimeException Propagates exceptions from the underlying implementation. - */ - private DOMXMLDocument(final MimeMediaType mimeType, final Reader source) throws IOException { - super(null, null); - this.root = this; - - this.mimeType = mimeType; - - DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - - docBuilderFactory.setNamespaceAware(true); - docBuilderFactory.setValidating(false); - try { - DocumentBuilder dataDocBuilder = docBuilderFactory.newDocumentBuilder(); - - domNode = dataDocBuilder.parse(new InputSource(source)); - } catch (ParserConfigurationException misconfig) { - throw new UndeclaredThrowableException(misconfig); - } catch (SAXException parseError) { - throw new IOException(parseError.toString()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - try { - StringWriter stringOut = new StringWriter(); - - sendToWriter(stringOut); - stringOut.close(); - - return stringOut.toString(); - } catch (IOException ex) { - throw new UndeclaredThrowableException(ex); - } - } - - /** - * {@inheritDoc} - */ - public MimeMediaType getMimeType() { - return mimeType; - } - - /** - * {@inheritDoc} - */ - public String getFileExtension() { - return Utils.getExtensionForMime(INSTANTIATOR.getSupportedFileExtensions(), getMimeType()); - } - - /** - * {@inheritDoc} - */ - public InputStream getStream() throws IOException { - String result = toString(); - - if (null == result) { - return null; - } - - String charset = mimeType.getParameter("charset"); - - if (charset == null) { - return new ByteArrayInputStream(result.getBytes()); - } else { - return new ByteArrayInputStream(result.getBytes(charset)); - } - } - - /** - * {@inheritDoc} - */ - public void sendToStream(OutputStream stream) throws IOException { - Writer osw; - String charset = mimeType.getParameter("charset"); - - if (charset == null) { - osw = new OutputStreamWriter(stream); - } else { - osw = new OutputStreamWriter(stream, charset); - } - - Writer out = new BufferedWriter(osw); - - sendToWriter(out); - out.flush(); - osw.flush(); - } - - /** - * {@inheritDoc} - */ - public Reader getReader() { - String result = toString(); - - if (null == result) { - return null; - } - - return new StringReader(result); - } - - /** - * {@inheritDoc} - */ - public void sendToWriter(Writer writer) throws IOException { - String charset = mimeType.getParameter("charset"); - - try { - DOMImplementationLS domImpl = (DOMImplementationLS) ((Document) domNode).getImplementation().getFeature("LS", "3.0"); - LSOutput output = domImpl.createLSOutput(); - - if (charset != null) { - output.setEncoding(charset); - } else { - output.setEncoding(java.nio.charset.Charset.defaultCharset().name()); - } - - output.setCharacterStream(writer); - - LSSerializer serial = domImpl.createLSSerializer(); - - serial.write(domNode, output); - } catch (Throwable ex) { - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; - } else if (ex instanceof Error) { - throw (Error) ex; - } else { - throw new UndeclaredThrowableException(ex); - } - } - } - - /** - * {@inheritDoc} - */ - public DOMXMLElement createElement(Object key) { - return createElement(key, null); - } - - /** - * {@inheritDoc} - */ - public DOMXMLElement createElement(Object key, Object val) { - if (!String.class.isAssignableFrom(key.getClass())) { - throw new ClassCastException(key.getClass().getName() + " not supported by createElement."); - } - - if ((null != val) && !String.class.isAssignableFrom(val.getClass())) { - throw new ClassCastException(val.getClass().getName() + " not supported by createElement."); - } - - return createElement((String) key, (String) val); - } - - // StructuredDocument Methods - - /** - * {@inheritDoc} - */ - public DOMXMLElement createElement(String name) { - return new DOMXMLElement(this, ((Document) domNode).createElement(name)); - } - - /** - * {@inheritDoc} - */ - public DOMXMLElement createElement(String name, String value) { - Element root; - - root = ((Document) domNode).createElement(name); - if (null != value) { - root.appendChild(((Document) domNode).createTextNode(value)); - } - return new DOMXMLElement(this, root); - } - - // Element Methods - - // Protected & Private Methods - - @Override - protected Node getAssocNode() { - return ((Document) domNode).getDocumentElement(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/DOMXMLElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/DOMXMLElement.java deleted file mode 100644 index 796eb063..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/DOMXMLElement.java +++ /dev/null @@ -1,383 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.document; - - -import net.jxta.document.Attribute; -import net.jxta.document.XMLElement; - -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; - - -/** - * This class represent an element of an XML document. XML Documents are formed - * as a hierarchy of elements. Each element provides a proxy for DOM elements - * and the text nodes containing values. - */ -public class DOMXMLElement implements XMLElement { - - protected DOMXMLDocument root; - - /** - * The DOM node for which this element is a proxy. - */ - protected Node domNode; - - /** - * Constructor for associating a DOM node with a StructuredDocument Element. - * - * @param root the DOM not which is to be associated with this element. - * @param node the DOM node - */ - protected DOMXMLElement(DOMXMLDocument root, Node node) { - this.root = root; - domNode = node; - } - - /** - * Get the name associated with an element. - * - * @return A string containing the key of this element. - */ - public String getKey() { - return getName(); - } - - /** - * Get the value (if any) associated with an element. - * - * @return A string containing the value of this element, if any, otherwise null. - */ - public String getValue() { - return getTextValue(); - } - - /** - * Get the name associated with an element. - * - * @return A string containing the name of this element. - */ - public String getName() { - return getAssocNode().getNodeName(); - } - - /** - * Get the value (if any) associated with an element. - * - * @return A string containing the value of this element, if any, otherwise null. - */ - public String getTextValue() { - StringBuilder itsValue = new StringBuilder(); - - for (Node eachChild = getAssocNode().getFirstChild(); eachChild != null; eachChild = eachChild.getNextSibling()) { - if (Node.TEXT_NODE == eachChild.getNodeType()) { - itsValue.append(eachChild.getNodeValue()); - } - } - - if (0 == itsValue.length()) { - return null; - } else { - return itsValue.toString(); - } - } - - /** - * Get the root element of the hierarchy this element belongs to. - * - * @return StructuredDocument root of this element's hierarchy. - */ - public DOMXMLDocument getRoot() { - return root; - } - - /** - * Get the parent of this element. If the element has not been inserted into - * the Document then null is returned. If this element is the root of the - * Document then it returns itself. - */ - public DOMXMLElement getParent() { - Node node = getAssocNode(); - - if (node.getOwnerDocument().equals(node)) { - return new DOMXMLElement(root, node); - } else { - return new DOMXMLElement(root, node.getParentNode()); - } - } - - /** - * Add a child element to this element - * - * @param element the element to be added as a child - */ - public void appendChild(DOMXMLElement element) { - getAssocNode().appendChild(element.getAssocNode()); - } - - /** - * Returns an enumeration of the immediate children of this element - * - * @return An enumeration containing all of the children of this element. - */ - public Enumeration getChildren() { - List children = new ArrayList(); - - for (Node eachChild = getAssocNode().getFirstChild(); eachChild != null; eachChild = eachChild.getNextSibling()) { - if (Node.ELEMENT_NODE == eachChild.getNodeType()) { - children.add(new DOMXMLElement(root, eachChild)); - } - } - - return Collections.enumeration(children); - } - - /** - * Returns an enumeration of the immediate children of this element whose - * name match the specified string. - * - * @param key The key which will be matched against. - * @return enumeration containing all of the children of this element. - */ - public Enumeration getChildren(Object key) { - if (key instanceof String) - return getChildren((String) key); - else - throw new ClassCastException(key.getClass().getName() + " not supported by getChildren."); - } - - /** - * Returns an enumeration of the immediate children of this element whose - * name match the specified string. - * - * @param name The name which will be matched against. - * @return An enumeration containing all of the children of this element. - */ - public Enumeration getChildren(String name) { - List children = new ArrayList(); - - for (Node eachChild = getAssocNode().getFirstChild(); eachChild != null; eachChild = eachChild.getNextSibling()) { - if ((Node.ELEMENT_NODE == eachChild.getNodeType()) && (name.equals(eachChild.getNodeName()))) { - children.add(new DOMXMLElement(root, eachChild)); - } - } - - return Collections.enumeration(children); - } - - /** - * Tests two elements for equality. For the XML document the definition of - * equality is: - *

      - *

        - *
      • the item compared against must be an XML Element.
      • - *

        - *

      • The items must belong to the same document.
      • - *

        - *

      • The items must have the same name.
      • - *

        - *

      • The items must have the save textual value.
      • - *
      - * - * @param element the element to be compared against. - * @return true if the elements are equal - */ - @Override - public boolean equals(Object element) { - if (this == element) { - return true; - } - - if (!(element instanceof DOMXMLElement)) { - return false; - } - - DOMXMLElement xmlElement = (DOMXMLElement) element; - - Node me = getAssocNode(); - Node it = xmlElement.getAssocNode(); - - if (me == it) { - return true; - } - - if (me.getOwnerDocument() != it.getOwnerDocument()) { - return false; - } - - if (!getName().equals(xmlElement.getName())) { - return false; - } - - String val1 = getTextValue(); - String val2 = xmlElement.getTextValue(); - - return (null == val1) && (null == val2) || null != val1 && null != val2 && val1.equals(val2); - - } - - /** - * Returns the DOM Node associated with this StructuredDocument element. - * - * @return Node The DOM Node associated with this StructuredDocument element. - */ - protected Node getAssocNode() { - return domNode; - } - - // Attributable methods - - /** - * Adds an attribute with the given name and value. Some implementations - * may support only a single value for each distinct name. Others may - * support multiple values for each name. If the value being provided - * replaces some other value then that value is returned otherwise null - * is returned. - * - * @param name name of the attribute. - * @param value value for the attribute. - * @return String containing previous value for this name if the value - * is being replaced otherwise null. - */ - public String addAttribute(String name, String value) { - String oldAttrValue = ((Element) getAssocNode()).getAttribute(name); - - ((Element) getAssocNode()).setAttribute(name, value); - return (0 == oldAttrValue.length()) ? null : oldAttrValue; - } - - /** - * Adds an attribute with the given name and value. Some implementations - * may support only a single value for each distinct name. Others may - * support multiple values for each name. If the value being provided - * replaces some other value then that value is returned otherwise null - * is returned. - * - * @param newAttrib new attribute. - * @return String containing previous value for this name if the value - * is being replaced otherwise null. - */ - public String addAttribute(Attribute newAttrib) { - String oldAttrValue = ((Element) getAssocNode()).getAttribute(newAttrib.getName()); - - ((Element) getAssocNode()).setAttribute(newAttrib.getName(), newAttrib.getValue()); - return (0 == oldAttrValue.length()) ? null : oldAttrValue; - } - - /** - * Returns an enumerations of the attributes assosicated with this object. - * Each element is of type Attribute. - * - * @return Enumeration the attributes associated with this object. - */ - public Enumeration getAttributes() { - NamedNodeMap nmap = getAssocNode().getAttributes(); - - if (nmap == null) { - List noAttrs = Collections.emptyList(); - - return Collections.enumeration(noAttrs); - } - - List attrs = new ArrayList(); - - for (int i = 0; i < nmap.getLength(); i++) { - Node domAttr = nmap.item(i); - Attribute attr = new Attribute(this, domAttr.getNodeName(), domAttr.getNodeValue()); - - attrs.add(attr); - } - - return Collections.enumeration(attrs); - } - - /** - * returns a single attribute which matches the name provided. If no such - * named attribute exists then null is returned. For impelementations of - * this interface which support multiple values for each name only the - * first value will be returned. To access all values for a name you must - * use getAttributes. - * - * @return Attribute the attributes matching the given name. - */ - public Attribute getAttribute(String name) { - NamedNodeMap nmap = (getAssocNode()).getAttributes(); - - if (nmap == null) { - return null; - } - - for (int i = 0; i < nmap.getLength(); i++) { - Node domAttr = nmap.item(i); - - if (name.equals(domAttr.getNodeName())) { - Attribute attr = new Attribute(this, domAttr.getNodeName(), domAttr.getNodeValue()); - - return attr; - } - } - - return null; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/LiteXMLDocument.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/LiteXMLDocument.java deleted file mode 100644 index ba9116dc..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/LiteXMLDocument.java +++ /dev/null @@ -1,526 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.document; - - -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; - -import java.io.IOException; -import java.lang.reflect.UndeclaredThrowableException; - -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentFactory.Instantiator.ExtensionMapping; -import net.jxta.document.XMLDocument; -import net.jxta.impl.document.LiteXMLElement.charRange; -import net.jxta.impl.document.LiteXMLElement.tagRange; - - -/** - * This class is an implementation of the StructuredDocument interface using - * a simplified XML implementation. - */ -public class LiteXMLDocument extends LiteXMLElement implements XMLDocument { - - /** - * {@inheritDoc} - */ - private final static class Instantiator implements StructuredDocumentFactory.TextInstantiator { - - // "x-" is a mime-type convention for indicating partial or provisional - // compliance to a standard - private static final MimeMediaType[] myTypes = { - MimeMediaType.XML_DEFAULTENCODING, - MimeMediaType.valueOf("Text/x-Xml"), - MimeMediaType.valueOf("Application/Xml"), - MimeMediaType.valueOf("Application/x-Xml") - }; - - // these are the file extensions which are likely to contain files of - // the type I like. - private static final ExtensionMapping[] myExtensions = { - new ExtensionMapping("xml", myTypes[0]), - new ExtensionMapping("xml", (MimeMediaType) null) - }; - - /** - * Creates new LiteXMLDocumentInstantiator - */ - public Instantiator() {} - - /** - * {@inheritDoc} - */ - public MimeMediaType[] getSupportedMimeTypes() { - return (myTypes); - } - - /** - * {@inheritDoc} - */ - public ExtensionMapping[] getSupportedFileExtensions() { - return (myExtensions); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, String doctype) { - return new LiteXMLDocument(mimeType, doctype); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, String doctype, String value) { - return new LiteXMLDocument(mimeType, doctype, value); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, InputStream source) throws IOException { - return new LiteXMLDocument(mimeType, source); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, Reader source) throws IOException { - return new LiteXMLDocument(mimeType, source); - } - } - - /** - * The instantiator for instances of our documents. - */ - public static final StructuredDocumentFactory.TextInstantiator INSTANTIATOR = new Instantiator(); - - /** - * The actual document contents. - */ - final StringBuilder docContent; - - /** - * The mimetype of this document. - */ - private final MimeMediaType mimeType; - - /** - * Creates new LiteXMLDocument - */ - LiteXMLDocument(MimeMediaType mimeType, String type) { - this(mimeType, type, ""); - } - - /** - * Creates new LiteXMLDocument with a textValue in the root element - */ - LiteXMLDocument(MimeMediaType mimeType, String type, String textValue) { - super(null, (LiteXMLElement.tagRange) null); - - parent = this; - - this.mimeType = mimeType; - - docContent = new StringBuilder(); - - for (int eachChar = type.length() - 1; eachChar >= 0; eachChar--) { - if (Character.isWhitespace(type.charAt(eachChar))) { - throw new IllegalArgumentException("Root tag may not contain spaces"); - } - } - - if (null == textValue) { - textValue = ""; - } - - StringBuilder seedDoc = new StringBuilder(textValue.length() + 3 * type.length() + 128); - - seedDoc.append("\n"); - - seedDoc.append("\n"); - - seedDoc.append('<'); - seedDoc.append(type); - seedDoc.append('>'); - - seedDoc.append(textValue); - - seedDoc.append("'); - - try { - init(new StringReader(seedDoc.toString())); - } catch (IOException caught) { - throw new UndeclaredThrowableException(caught); - } - } - - /** - * Creates new LiteXMLDocument - */ - LiteXMLDocument(MimeMediaType mimeType, InputStream in) throws IOException { - super(null, (LiteXMLElement.tagRange) null); - - parent = this; - - this.mimeType = mimeType; - - docContent = new StringBuilder(); - - String charset = mimeType.getParameter("charset"); - - if (charset == null) { - init(new InputStreamReader(in)); - } else { - init(new InputStreamReader(in, charset)); - } - } - - /** - * Creates new LiteXMLDocument - */ - LiteXMLDocument(MimeMediaType mimeType, Reader in) throws IOException { - super(null, (LiteXMLElement.tagRange) null); - - parent = this; - - this.mimeType = mimeType; - - docContent = new StringBuilder(); - - init(in); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - - try { - StringWriter stringOut = new StringWriter(); - - sendToWriter(stringOut); - - stringOut.close(); - - return stringOut.toString(); - } catch (IOException caught) { - throw new UndeclaredThrowableException(caught); - } - } - - /** - * {@inheritDoc} - */ - public MimeMediaType getMimeType() { - return mimeType; - } - - /** - * {@inheritDoc} - */ - public String getFileExtension() { - return TextDocumentCommon.Utils.getExtensionForMime(INSTANTIATOR.getSupportedFileExtensions(), getMimeType()); - } - - /** - * {@inheritDoc} - */ - public LiteXMLElement createElement(Object key) { - return createElement(key, null); - } - - /** - * {@inheritDoc} - */ - public LiteXMLElement createElement(Object key, Object val) { - if (!(key instanceof String)) { - throw new ClassCastException(key.getClass().getName() + " not supported by createElement as key."); - } - - if ((null != val) && !(val instanceof String)) { - throw new ClassCastException(val.getClass().getName() + " not supported by createElement as value."); - } - - return createElement((String) key, (String) val); - } - - /** - * {@inheritDoc} - */ - public LiteXMLElement createElement(String name) { - return createElement(name, (String) null); - } - - /** - * {@inheritDoc} - */ - public LiteXMLElement createElement(String name, String val) { - return new LiteXMLElement(this, name, val); - } - - /** - * Create a new text element as a sub-range of this document. - * - * @param loc The document range for the new element. - * @return The newly created element. - */ - protected LiteXMLElement createElement(tagRange loc) { - return new LiteXMLElement(this, loc); - } - - /** - * {@inheritDoc} - */ - public Reader getReader() { - return new StringReader(toString()); - } - - /** - * {@inheritDoc} - */ - @Override - public LiteXMLDocument getRoot() { - return this; - } - - /** - * {@inheritDoc} - */ - public InputStream getStream() throws IOException { - String charset = mimeType.getParameter("charset"); - - if (charset == null) { - return new ByteArrayInputStream(toString().getBytes()); - } else { - return new ByteArrayInputStream(toString().getBytes(charset)); - } - } - - /** - * {@inheritDoc} - */ - public void sendToWriter(Writer writer) throws IOException { - String charset = mimeType.getParameter("charset"); - - if (charset == null) { - writer.write("\n"); - } else { - writer.write("\n"); - } - - tagRange result = getDocType(docContent, true); - - if (result.isValid()) { - writer.write(docContent.substring(result.startTag.start, result.startTag.end + 1)); - writer.write('\n'); - } - - printNice(writer, 0, true); - } - - /** - * {@inheritDoc} - */ - public void sendToStream(OutputStream stream) throws IOException { - String charset = mimeType.getParameter("charset"); - - Writer osw; - - if (charset == null) { - osw = new OutputStreamWriter(stream); - } else { - osw = new OutputStreamWriter(stream, charset); - } - - Writer out = new BufferedWriter(osw); - - sendToWriter(out); - out.flush(); - } - - /** - * Initialises LiteXMLDocument. - */ - protected void init(Reader in) throws IOException { - loc = new tagRange(); - - char[] smallBuffer = new char[512]; - - do { - int readCount = in.read(smallBuffer); - - if (readCount < 0) { - break; - } - - if (readCount > 0) { - docContent.append(smallBuffer, 0, readCount); - } - - } while (true); - - // startTag will contain the xml declaration - loc.startTag.start = 0; - loc.startTag.end = docContent.indexOf(">"); - - // body is everything after the xml declaration - loc.body.start = loc.startTag.end + 1; - loc.body.end = docContent.length() - 1; - - // end is the end of the doc. - loc.endTag.start = loc.body.end; - loc.endTag.end = loc.body.end; - - tagRange docType = getDocType(getDocument().docContent, false); - - if (docType.isValid()) { - loc = getTagRanges(getDocument().docContent, docContent.substring(docType.body.start, docType.body.end + 1) - , - docType.endTag); - } else { - loc = getTagRanges(getDocument().docContent, null, loc.body); - } - - if (!loc.isValid()) { - throw new RuntimeException("Parsing error in source document."); - } - - if (!loc.startTag.equals(loc.endTag)) { - addChildTags(loc.body, this); // now add the subtags - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - } - - protected tagRange getDocType(final StringBuilder source, boolean wholeElement) { - final String xmldoctype = "!DOCTYPE"; - int start = 0; - int end = getDocument().docContent.length() - 1; - tagRange ranges = getTagRanges(source, xmldoctype, new charRange(start, end)); - - if (!ranges.startTag.isValid()) { - return ranges; - } - - // the rest of the document will be the "end" - ranges.endTag.start = ranges.body.start; - ranges.endTag.end = ranges.body.end; - - if (wholeElement) { - // this will be an empty element - ranges.body.start = ranges.startTag.end + 1; - ranges.body.end = ranges.endTag.start - 1; - } else { - ranges.body.start = ranges.startTag.start + 1 + xmldoctype.length() - 1 + 1; - ranges.startTag.end = ranges.body.start - 1; - - while ((ranges.body.start < end) && // immediately followed by a delimiter or the end of the tag - Character.isWhitespace(source.charAt(ranges.body.start))) { - ranges.body.start++; - } - - ranges.body.end = ranges.body.start; - - while ((ranges.body.end + 1) < end) { // immediately followed by a delimiter or the end of the tag - char possibleEnd = source.charAt(ranges.body.end + 1); - - if (Character.isWhitespace(possibleEnd) || ('/' == possibleEnd) || ('>' == possibleEnd)) { - break; - } - ranges.body.end++; - } - } - - return ranges; - } - - /** - * {@inheritDoc} - */ - @Override - LiteXMLDocument getDocument() { - return this; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/LiteXMLElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/LiteXMLElement.java deleted file mode 100644 index 01aa3c94..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/LiteXMLElement.java +++ /dev/null @@ -1,1729 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.document; - - -import java.io.Writer; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import java.io.IOException; - -import net.jxta.document.Attribute; -import net.jxta.document.XMLElement; -import net.jxta.logging.Logging; - - -/** - * An element of a StructuredDocument. StructuredDocuments - * are made up of hierarchies of elements. LiteXMLElement is part of an implementation - * while makes use of XML-style document conventions, but without the overhead of a - * full parser. - */ -public class LiteXMLElement implements XMLElement { - - /** - * Defines a range of characters, probably within a string. The range is - * deemed to be invalid if 'start' is -1. A zero length range is, by - * convention, described by an 'end' value of 'start' - 1. - */ - protected static class charRange implements Comparable { - - /** - * Contains the start position of this range. - */ - public int start; - - /** - * Contains the end position of this range. one weird thing: if end == start -1, - * then the item is of zero length beginning at start. - */ - public int end; - - /** - * Constructor for a null charRange. - */ - public charRange() { - start = -1; - end = -1; - } - - /** - * Constructor for which the bounds are specified. - */ - public charRange(int start, int end) { - this.start = start; - this.end = end; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object aRange) { - if (this == aRange) { - return true; - } - - if (!(aRange instanceof charRange)) { - return false; - } - - charRange someRange = (charRange) aRange; - - return (start == someRange.start) && (end == someRange.end); - } - - /** - * {@inheritDoc} - */ - public int compareTo(charRange someRange) { - if (this == someRange) { - return 0; - } - - if (start < someRange.start) { - return -1; - } - - if (start > someRange.start) { - return 1; - } - - if (end < someRange.end) { - return -1; - } - - if (end > someRange.end) { - return 1; - } - - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "[" + start + "," + end + "]"; - } - - /** - * Returns true if the charRange specified by someRange is - * contained within this range. - * - * @param someRange The range which must be contained within this range. - * @return true if the specified range is contained with this range otherwise false. - */ - public boolean contains(charRange someRange) { - return (isValid() && someRange.isValid() && (start <= someRange.start) && (end >= someRange.end)); - } - - /** - * Returns true if the tagRange specified by someRange is - * contained within this range. - * - * @param someRange The range which must be contained within this range. - * @return true if the specified range is contained with this range otherwise false. - */ - public boolean contains(tagRange someRange) { - return (isValid() && someRange.isValid() && (start <= someRange.startTag.start) && (end >= someRange.endTag.end)); - } - - /** - * Returns true if the location specified is contained in this range. - * - * @param someLoc the location which is to be tested. - * @return true if the location is in this range, otherwise false. - */ - public boolean contains(int someLoc) { - return (isValid() && (someLoc >= 0) && (start <= someLoc) && (end >= someLoc)); - } - - /** - * Returns true if the range is both non-null and has a length of greater - * than or equal to zero. - * - * @return true if the range is a valid one, otherwise false. - */ - public boolean isValid() { - return length() >= 0; - } - - /** - * Returns the length of this range. - * - * @return The length of the range or -1 if the range is null. - */ - public int length() { - if ((-1 == start) || (-1 == end)) { - return -1; - } - - return (end - start + 1); - } - } - - - /** - * A tagRange is a collection of char ranges useful for describing XML - * structures. - *

      - *

      - *
      startTag
      - *
      The range of the opening tag, ie. <tag>
      - *
      body
      - *
      Everything between startTag and endTag.
      - *
      endTag
      - *
      The range of the terminating tag, ie. </tag>.
      - *
      - *

      - *

      For empty-element tags the startTag, body - * and endTag will be equal. - */ - protected static class tagRange implements Comparable { - public charRange startTag; - public charRange body; - public charRange endTag; - - public tagRange() { - startTag = new charRange(); - body = new charRange(); - endTag = new charRange(); - } - - public tagRange(charRange startTag, charRange body, charRange endTag) { - this.startTag = startTag; - this.body = body; - this.endTag = endTag; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object aRange) { - if (this == aRange) { - return true; - } - - if (!(aRange instanceof tagRange)) { - return false; - } - - tagRange likeMe = (tagRange) aRange; - - return startTag.equals(likeMe.startTag) && body.equals(likeMe.body) && endTag.equals(likeMe.endTag); - } - - /** - * {@inheritDoc} - */ - public int compareTo(tagRange someRange) { - if (this == someRange) { - return 0; - } - - int compared = startTag.compareTo(someRange.startTag); - - if (0 != compared) { - return compared; - } - - return endTag.compareTo(someRange.endTag); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return startTag + ":" + body + ":" + endTag; - } - - /** - * Returns true if the tagRange specified by someRange is - * contained within the body portion of this range. - * - * @param someRange The range which must be contained within this range. - * @return true if the specified range is contained with this range - * otherwise false. - */ - public boolean contains(tagRange someRange) { - return (isValid() && someRange.isValid() && (body.start <= someRange.startTag.start) - && (body.end >= someRange.endTag.end)); - } - - /** - * Returns true if the charRange specified by someRange is - * contained within the body portion of this range. - * - * @param someRange The range which must be contained within this range. - * @return true if the specified range is contained with this range - * otherwise false. - */ - public boolean contains(charRange someRange) { - return (isValid() && someRange.isValid() && (body.start <= someRange.start) && (body.end >= someRange.end)); - } - - /** - * @return true if this tagRange represents and empty - * element. - */ - public boolean isEmptyElement() { - return isValid() && startTag.equals(body) && startTag.equals(endTag); - } - - /** - * @return true if valid - */ - public boolean isValid() { - return (null != startTag) && (null != body) && (null != endTag) && startTag.isValid() && body.isValid() - && endTag.isValid(); - } - } - - /** - * Log4J Logger - */ - private final static transient Logger LOG = Logger.getLogger(LiteXMLElement.class.getName()); - - /** - * If true then every operation which modifies the state of the document will - * perform a consistency check. This is a deadly performance killer but - * helps a lot in isolating bugs. - */ - protected final static transient boolean paranoidConsistencyChecking = false; - - /** - * The document associated with this Element. - */ - protected final transient LiteXMLDocument doc; - - /** - * Identifies the element which is the parent of this element. If - * this.parent == this then this element is the root of the document. - * If null == parent then this element has not yet been - * inserted into the document. - */ - protected transient LiteXMLElement parent; - - /** - * The portion of the source XML associated with this node - */ - protected transient tagRange loc; - - /** - * If this node has yet to be inserted into the document then will contain - * the String value of this node, otherwise null. - */ - private transient StringBuilder uninserted = null; - - /** - * The child elements associated with this element - */ - private transient List children; - - /** - * Creates new LiteXMLElement - * - * @param loc The location of the element within the document. - * @param doc The {@link LiteXMLDocument} which is the root of the document. - */ - protected LiteXMLElement(LiteXMLDocument doc, tagRange loc) { - this.doc = doc; - this.loc = loc; - } - - /** - * Creates new LiteElement - * - * @param doc The {@link LiteXMLDocument} which is the root of the document. - * @param name The name of the element being created. - * @param val The value of the element being created or null if there is no - * content to the element. - */ - public LiteXMLElement(LiteXMLDocument doc, final String name, final String val) { - this(doc, new tagRange()); - - for (int eachChar = name.length() - 1; eachChar >= 0; eachChar--) { - if (Character.isWhitespace(name.charAt(eachChar))) { - throw new IllegalArgumentException("Element names may not contain spaces."); - } - } - - if ((null == val) || (0 == val.length())) { - uninserted = new StringBuilder("<" + name + "/>"); - } else { - uninserted = new StringBuilder(val); - encodeEscaped(uninserted); - uninserted.insert(0, "<" + name + ">"); - uninserted.append(""); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object element) { - if (this == element) { - return true; - } - - if (!(element instanceof LiteXMLElement)) { - return false; - } - - LiteXMLElement liteElement = (LiteXMLElement) element; - - if (getDocument() != liteElement.getDocument()) { - return false; - } - - if (!getName().equals(liteElement.getName())) { - return false; - } - - String val1; - - if (null != uninserted) { - val1 = uninserted.toString(); - } else { - val1 = getTextValue(); - } - - String val2 = liteElement.getTextValue(); - - if ((null == val1) && (null == val2)) { - return true; - } - - return null != val1 && null != val2 && val1.equals(val2); - - } - - /** - * {@inheritDoc} - *

      - *

      A toString implementation for debugging purposes. - */ - @Override - public String toString() { - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - String name = getName(); - - if (name == null) { - name = "<>"; - } - String value = getTextValue(); - - if (value == null) { - value = "<>"; - } - - if ((value.length() + name.length()) >= 60) { - int len = Math.max(20, 60 - name.length()); - - value = value.substring(0, Math.min(len, value.length())); - } - - // FIXME 20021125 bondolo@jxta.org should remove carriage control. - - return super.toString() + " / " + name + " = " + value; - } - - /** - * {@inheritDoc} - */ - public LiteXMLDocument getRoot() { - return getDocument(); - } - - /** - * {@inheritDoc} - */ - public LiteXMLElement getParent() { - return parent; - } - - /** - * {@inheritDoc} - */ - public Enumeration getChildren() { - if (null != uninserted) { - throw new IllegalStateException("This element has not been added."); - } - - if (null == children) { - List empty = Collections.emptyList(); - - return Collections.enumeration(empty); - } else { - return Collections.enumeration(children); - } - } - - /** - * {@inheritDoc} - */ - public String getName() { - if (null != uninserted) { - throw new IllegalStateException("This element has not been added."); - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - int current = loc.startTag.start + 1; - - while (current <= loc.startTag.end) { - char inTagName = getDocument().docContent.charAt(current); - - if (Character.isWhitespace(inTagName) || ('/' == inTagName) || ('>' == inTagName)) { - break; - } - - current++; - } - - return getDocument().docContent.substring(loc.startTag.start + 1, current); - } - - /** - * Get the name associated with an element. - * - * @return A string containing the key of this element. - */ - public String getKey() { - return getName(); - } - - /** - * Get the value (if any) associated with an element. - * - * @return A string containing the value of this element, if any, otherwise null. - */ - public String getValue() { - return getTextValue(); - } - - /** - * {@inheritDoc} - */ - public void appendChild(LiteXMLElement element) { - if (element.getDocument() != getDocument()) { - throw new IllegalArgumentException("Wrong document"); - } - - if (null != element.parent) { - throw new IllegalArgumentException("New element is already in document"); - } - - if (null != uninserted) { - throw new IllegalStateException("This element has not been added."); - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - // If uninserted then this new element contains content which needs to - // be added to the document. If uninserted is null then the child - // element's content is already in the document, but merely needs to - // be recognized as a child. - if (null != element.uninserted) { - if (loc.startTag.equals(loc.endTag)) { - getDocument().docContent.deleteCharAt(loc.endTag.end - 1); // delete the / - loc.startTag.end -= 1; - - // skip past the name portion - int current = loc.startTag.start + 1; - - while (current <= loc.startTag.end) { - char inTagName = getDocument().docContent.charAt(current); - - if (Character.isWhitespace(inTagName) || ('>' == inTagName)) { - break; - } - - current++; - } - - String tagName = getDocument().docContent.substring(loc.startTag.start + 1, current); - - getDocument().docContent.insert(loc.startTag.end + 1, ""); - getDocument().adjustLocations(loc.startTag.end + 1, tagName.length() + 2); - loc.endTag = new charRange(loc.startTag.end + 1, loc.startTag.end + 3 + tagName.length()); - loc.body = new charRange(loc.startTag.end + 1, loc.startTag.end); - } - - getDocument().docContent.insert(loc.endTag.start, element.uninserted); - - element.loc.startTag.start = loc.endTag.start; - element.loc.startTag.end = getDocument().docContent.indexOf(">", element.loc.startTag.start); - - if ('/' != element.uninserted.charAt(element.uninserted.length() - 2)) { - element.loc.body.start = element.loc.startTag.end + 1; - - element.loc.endTag.end = element.loc.startTag.start + element.uninserted.length() - 1; - element.loc.endTag.start = getDocument().docContent.lastIndexOf("<", element.loc.endTag.end); - - element.loc.body.end = element.loc.endTag.start - 1; - } else { - element.loc.body = new charRange(element.loc.startTag.start, element.loc.startTag.end); - element.loc.endTag = new charRange(element.loc.startTag.start, element.loc.startTag.end); - } - - if (0 != loc.body.length()) { - getDocument().adjustLocations(loc.endTag.start, element.uninserted.length()); - } else { - loc.body.start--; - getDocument().adjustLocations(loc.endTag.start, element.uninserted.length()); - loc.body.start++; - } - - loc.body.end += element.uninserted.length(); - - element.uninserted = null; - } - - element.parent = this; - - if (null == children) { - children = new ArrayList(); - } - - children.add(element); - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - } - - /** - * Returns an enumeration of the immediate children of this element whose - * name match the specified string. - * - * @param key The key which will be matched against. - * @return enumeration containing all of the children of this element. - */ - public Enumeration getChildren(Object key) { - if (key instanceof String) - return getChildren((String) key); - else - throw new ClassCastException(key.getClass().getName() + " not supported by getChildren."); - } - - /** - * {@inheritDoc} - */ - public Enumeration getChildren(String name) { - if (null != uninserted) { - throw new IllegalStateException("This element has not been added."); - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - if (null == children) { - List empty = Collections.emptyList(); - - return Collections.enumeration(empty); - } - - List result = new ArrayList(); - - for (LiteXMLElement aChild : children) { - if (name.equals(aChild.getName())) { - result.add(aChild); - } - } - - return Collections.enumeration(result); - } - - /** - * {@inheritDoc} - */ - public String getTextValue() { - return getTextValue(false, true); - } - - /** - * Get the value (if any) associated with an element. - * - * @param getEncoded if true then the contents will be encoded such that - * the contents will not be interpreted as XML. see - * {@link W3C XML 1.0 Specification} - * ie. < -> < & -> & - * @param trim if true trims prefix and suffix white space - * @return A string containing the value of this element, if any, otherwise null. - */ - protected String getTextValue(boolean getEncoded, boolean trim) { - if (null != uninserted) { - throw new IllegalStateException("This element has not been added."); - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - StringBuilder building = new StringBuilder(); - - List ranges = new ArrayList(); - - /* - * insert the ranges of the children in order. insertion method is ok - * because the number of children is usually less than 10 or so. - */ - for (Enumeration eachChild = getChildren(); eachChild.hasMoreElements();) { - LiteXMLElement aChild = eachChild.nextElement(); - charRange childsRange = new charRange(aChild.loc.startTag.start, aChild.loc.endTag.end); - - // find where to insert. - for (int eachRange = 0; eachRange < ranges.size(); eachRange++) { - charRange rangeChild = ranges.get(eachRange); - - if (1 == rangeChild.compareTo(childsRange)) { - ranges.set(eachRange, childsRange); - childsRange = rangeChild; - } - } - ranges.add(childsRange); - } - - int current = loc.body.start; - - // add all the text not part of some child - for (charRange aRange : ranges) { - building.append(getDocument().docContent.substring(current, aRange.start)); - - current = aRange.end + 1; - } - - // Add the last bit. - building.append(getDocument().docContent.substring(current, loc.endTag.start)); - - if (!getEncoded) { - building = decodeEscaped(building); - } - - // trim - int firstNonWhiteSpace = 0; - int lastNonWhiteSpace = building.length() - 1; - - if (trim) { - while (firstNonWhiteSpace < building.length()) { - char possibleSpace = building.charAt(firstNonWhiteSpace); - - if (!Character.isWhitespace(possibleSpace)) { - break; - } - - firstNonWhiteSpace++; - } - - // did we find no non-whitespace? - if (firstNonWhiteSpace >= building.length()) { - return null; - } - - while (lastNonWhiteSpace >= firstNonWhiteSpace) { - char possibleSpace = building.charAt(lastNonWhiteSpace); - - if (!Character.isWhitespace(possibleSpace)) { - break; - } - - lastNonWhiteSpace--; - } - } - - String result = building.substring(firstNonWhiteSpace, lastNonWhiteSpace + 1); - - return result; - } - - /** - * Write the contents of this element and optionally its children. The - * writing is done to a provided java.io.Writer. The writing - * can optionally be indented. - * - * @param into The java.io.Writer that the output will be sent to. - * @param indent the number of tabs which will be inserted before each - * line. - * @param recurse if true then also print the children of this element. - * @throws java.io.IOException if an io error occurs - */ - protected void printNice(Writer into, int indent, boolean recurse) throws IOException { - if (null != uninserted) { - throw new IllegalStateException("This element has not been added."); - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - // print start tag - StringBuilder start = new StringBuilder(); - - if (-1 != indent) { - // do indent - for (int eachTab = 0; eachTab < indent; eachTab++) { - start.append('\t'); - } - } - - start.append(getDocument().docContent.substring(loc.startTag.start, loc.startTag.end + 1)); - - if (-1 != indent) { - start.append('\n'); - } - - into.write(start.toString()); - - // print the rest if this was not an empty element. - if (!loc.startTag.equals(loc.endTag)) { - String itsValue = getTextValue(true, (-1 != indent)); - - // print node value - if (null != itsValue) { - if (-1 != indent) { - // do indent - for (int eachTab = 0; eachTab < indent + 1; eachTab++) { - into.write("\t"); - } - } - - into.write(itsValue); - - if (-1 != indent) { - into.write('\n'); - } - } - - // recurse as needed - if (recurse) { - int childIndent; - - Enumeration childrens = getChildren(); - - Attribute space = getAttribute("xml:space"); - - if (null != space) { - if ("preserve".equals(space.getValue())) { - childIndent = -1; - } else { - childIndent = indent + 1; - } - } else { - if (-1 != indent) { - childIndent = indent + 1; - } else { - childIndent = -1; - } - } - - while (childrens.hasMoreElements()) { - LiteXMLElement aChild = childrens.nextElement(); - - aChild.printNice(into, childIndent, recurse); - } - } - - // print end tag - StringBuilder end = new StringBuilder(); - - if (-1 != indent) { - // do indent - for (int eachTab = 0; eachTab < indent; eachTab++) { - end.append('\t'); - } - } - - end.append(getDocument().docContent.substring(loc.endTag.start, loc.endTag.end + 1)); - - if (-1 != indent) { - end.append('\n'); - } - - into.write(end.toString()); - } - } - - /** - * Given a source string, an optional tag and a range with in the source - * find either the tag specified or the next tag. - *

      - * The search consists of 4 phases : - * 0. If no tag was specified, determine if a tag can be found and - * learn its name. - * 1. Search for the start of the named tag. - * 2. Search for the end tag. Each time we think we have found a tag - * which might be the end tag we make sure it is not the end tag - * of another element with the same name as our tag. - * 3. Calculate the position of the body of the tag given the locations - * of the start and end. - * - * @param source the string to search - * @param tag the tag to search for in the source string. If this tag is - * empty or null then we will search for the next tag. - * @param range describes the range of character locations in the source - * string to which the search will be limited. - * @return tagRange containing the ranges of the found tag. - */ - - protected tagRange getTagRanges(final StringBuilder source, String tag, final charRange range) { - - // FIXME bondolo@jxta.org 20010327 Does not handle XML comments. ie. - if (null != uninserted) { - throw new IllegalStateException("This element has not been added to the document."); - } - - tagRange result = new tagRange(); - int start = range.start; - int end = source.length() - 1; - int current; - boolean foundStartTag = false; - boolean foundEndTag = false; - boolean emptyTag = (null == tag) || (0 == tag.length()); - - // check for bogosity - if ((-1 == start) || (start >= end)) { - throw new IllegalArgumentException("Illegal start value"); - } - - // adjust end of range - if ((-1 != range.end) && (end > range.end)) { - end = range.end; - } - - // check for empty tag and assign empty string - if (null == tag) { - tag = ""; - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Searching for \"" + tag + "\" in range [" + start + "," + end + "]"); - } - - current = start; - - // Begin Phase 0 : Search for any tag. - - if (emptyTag) { - int foundTagText = source.indexOf("<", current); - - // was it not found? if not then quit - if (-1 == foundTagText) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("No Tags Found"); - } - return result; - } - - // this part is about setting the tag if necessary - foundTagText++; - - int afterTagText = foundTagText; - - while (afterTagText <= end) { - char inTagName = source.charAt(afterTagText); - - if (!Character.isWhitespace(inTagName) && ('/' != inTagName) && ('>' != inTagName)) { - afterTagText++; - continue; - } - - tag = source.substring(foundTagText, afterTagText); - emptyTag = (null == tag) || (0 == tag.length()); - - break; - } - - // it better not be still empty - if (emptyTag) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("No tag found"); - } - return result; - } - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Search for \"" + tag + "\" [" + start + "," + end + "]"); - } - - // Begin Phase 1: Search for the Start Tag - - while (!foundStartTag && (current < end)) { - int foundTagText = source.indexOf(tag, current + 1); // first loc is one past current location - int foundTagTerminator; - int foundNextTagStart; - int afterTagText = foundTagText + tag.length(); - - // was it not found - if ((-1 == foundTagText) || (afterTagText > end)) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Tag \"" + tag + "\" Not Found(1)"); - } - return result; - } - - char checkChar = source.charAt(afterTagText); - - // check to see if it is the start tag - if (('<' != source.charAt(foundTagText - 1)) || // it has the open tag delimiter before it - (!Character.isWhitespace(checkChar) && ('/' != checkChar) && ('>' != checkChar))) { // is immediately followed by a delimiter - current = afterTagText; - continue; - } - - foundTagTerminator = source.indexOf(">", afterTagText); - foundNextTagStart = source.indexOf("<", afterTagText + 1); - - if ((-1 == foundTagTerminator) || // the tag has no terminator - (foundTagTerminator > end) || // it is past the valid range - ((-1 != foundNextTagStart) && // there is another tag start - (foundNextTagStart < foundTagTerminator))) { // and it is before the terminator we found. very bad - current = afterTagText; - continue; - } - - foundStartTag = true; - result.startTag.start = foundTagText - 1; - result.startTag.end = foundTagTerminator; - } - - if (!foundStartTag) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Tag \"" + tag + "\" Not Found(2)"); - } - return result; - } - - // is this an empty element declaration? - if ('/' == source.charAt(result.startTag.end - 1)) { - // end is the start and there is no body - result.body = new charRange(result.startTag.start, result.startTag.end); - result.endTag = new charRange(result.startTag.start, result.startTag.end); - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Empty Element \"" + tag + "\" Start : " + result.startTag); - } - return result; - } - - current = result.startTag.end + 1; - - // if current is past the end then our end tag is not found. - if (current >= end) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("End not found \"" + tag + "\" Start : " + result.startTag); - } - return result; - } - - // Begin Phase 2 : Search for the end tag - - String endTag = ""; - int searchFrom = result.startTag.end + 1; - - while (!foundEndTag && (current < end) && (searchFrom < end)) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Searching for \"" + endTag + "\" in range [" + current + "," + end + "]"); - } - - int foundTagText = source.indexOf(endTag, current); - - // was it not found or not in bounds? - if ((-1 == foundTagText) || ((foundTagText + endTag.length() - 1) > end)) { - break; - } // it was not found - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "Prospective tag pair for \"" + tag + "\" " + result.startTag + ":[" + foundTagText + "," - + (foundTagText + endTag.length() - 1) + "]"); - } - - // We recurse here in order to exclude the end tags of any sub elements with the same name - charRange subRange = new charRange(searchFrom, foundTagText - 1); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Recursing to search for \"" + tag + "\" in " + subRange); - } - - tagRange subElement = getTagRanges(source, tag, subRange); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Recursion result \"" + tag + "\" " + subElement); - } - - // if there was an incomplete sub-tag with the same name, skip past it - if (subElement.startTag.isValid()) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Found sub-tag \"" + tag + "\" at " + subElement + " within " + subRange); - } - - if (subElement.endTag.isValid()) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Complete sub-tag \"" + tag + "\" at " + subElement + " within " + subRange); - } - current = subElement.endTag.end + 1; - searchFrom = subElement.endTag.end + 1; - } else { - current = foundTagText + endTag.length(); - } - - continue; - } - - foundEndTag = true; - result.endTag.start = foundTagText; - result.endTag.end = foundTagText + endTag.length() - 1; - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Prospective tag \"" + tag + "\" " + result.endTag + " is confirmed."); - } - } - - // Begin Phase 3 : Calculate the location of the body. - - result.body.start = result.startTag.end + 1; - - if (foundEndTag) { - result.body.end = result.endTag.start - 1; - } else { - result.body.end = end; - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Found element : \"" + tag + "\" " + result); - } - - return result; - } - - /** - * Parse a charRange and add any tags found as content as children of a - * specified element. This process is repeated recursivly. - * - * @param scanRange the range to be parsed for sub-tags - * @param addTo the element to add any discovered children to. - */ - protected void addChildTags(final charRange scanRange, LiteXMLElement addTo) { - if (null != uninserted) { - throw new IllegalStateException("This element has not been added to the document."); - } - - int current = scanRange.start; - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Scanning for children in range " + scanRange); - } - - do { - // scan for any tag. - tagRange aSubtag = getTagRanges(getDocument().docContent, null, new charRange(current, scanRange.end)); - - // did we find one? - if (aSubtag.isValid()) { - LiteXMLElement newChild = getDocument().createElement(aSubtag); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "Adding child tag \"" - + getDocument().docContent.substring(aSubtag.endTag.start + 2, aSubtag.endTag.end) + "\" " - + aSubtag); - } - - addTo.appendChild(newChild); - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - if (!aSubtag.startTag.equals(aSubtag.endTag)) { - addChildTags(aSubtag.body, newChild); // recurse into the new tag - } - - // all done this tag, move on - current = aSubtag.endTag.end + 1; - } else { - current = -1; // all done! - } - } while ((-1 != current) && (current < scanRange.end)); - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - } - - /** - * For this element and all its children adjust the location of its ranges - * by the amount specified. - * - * @param beginningAt adjust all locations which are at or past this - * location. - * @param by amount to adjust all matching locations. - */ - protected void adjustLocations(final int beginningAt, final int by) { - if (null != uninserted) { - throw new IllegalStateException("This element has not been added."); - } - - // Check that this element is not entirely to the left of the shift - // zone. NB: end can be < start if len is 0. - if (loc.endTag.end < beginningAt && loc.endTag.start < beginningAt) { - return; - } - - if ((loc.startTag.end >= beginningAt) - || ((loc.startTag.start >= beginningAt) && ((loc.startTag.end + 1) == loc.startTag.start))) { - loc.startTag.end += by; - } - - if (loc.startTag.start >= beginningAt) { - loc.startTag.start += by; - } - - if ((loc.body.end >= beginningAt) || ((loc.body.start >= beginningAt) && ((loc.body.end + 1) == loc.body.start))) { - loc.body.end += by; - } - - if (loc.body.start >= beginningAt) { - loc.body.start += by; - } - - if ((loc.endTag.end >= beginningAt) || ((loc.endTag.start >= beginningAt) && ((loc.endTag.end + 1) == loc.endTag.start))) { - loc.endTag.end += by; - } - - if (loc.endTag.start >= beginningAt) { - loc.endTag.start += by; - } - - for (Enumeration eachChild = getChildren(); eachChild.hasMoreElements();) { - LiteXMLElement aChild = eachChild.nextElement(); - - aChild.adjustLocations(beginningAt, by); - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - } - - /** - * Given a StringBuilder find all occurrences of escaped characters which - * must be decoded and convert them back to their non-escaped equivalents. - *

      - *

      Also does end of line folding per: - * - * @param target The StringBuilder which will be decoded. - * @return The decoded version of the StringBuilder. - */ - protected StringBuilder decodeEscaped(StringBuilder target) { - - int current = 0; - - StringBuilder result = new StringBuilder(target.length()); - - while (current < target.length()) { - // FIXME bondolo@jxta.org 20010422 Should process xml comments out here. - - // fold 0x0D and 0x0D 0x0A to 0x0A - if ('\r' == target.charAt(current)) { - result.append('\n'); - current++; - if ((current < target.length()) && ('\n' == target.charAt(current))) { - current++; - } - continue; - } - - if ('&' != target.charAt(current)) { - result.append(target.charAt(current)); - current++; - continue; - } - - int terminusAt = current + 1; - - while ((terminusAt < target.length()) && // dont go past end - ((terminusAt - current) < 6) && // only look 6 chars away. - (';' != target.charAt(terminusAt))) { // must be a ; - terminusAt++; - } - - if ((terminusAt >= target.length()) || (';' != target.charAt(terminusAt))) { - // if we get here then we didnt find the terminal we needed - // so we just leave ampersand as it was, the document is - // ill-formed but why make things worse? - result.append(target.charAt(current)); - current++; - continue; - } - - char[] sub = new char[terminusAt - current + 1]; - - target.getChars(current, terminusAt + 1, sub, 0); - String escaped = new String(sub); - - if ("&".equals(escaped)) { - result.append('&'); - current += 4; - } else if ("<".equals(escaped)) { - result.append('<'); - current += 3; - } else if (">".equals(escaped)) { // for compatibility with SGML. We dont encode these - result.append('>'); - current += 3; - } else if (escaped.startsWith("&#")) { - String numericChar = escaped.substring(2, escaped.length() - 1); - - // is it &#; ? - if (numericChar.length() < 1) { - result.append(target.charAt(current)); - current++; - continue; - } - - // is it hex numeric - if (numericChar.charAt(0) == 'x') { - numericChar = numericChar.substring(1); - - // is it &#x; ? - if (numericChar.length() < 1) { - result.append(target.charAt(current)); - current++; - continue; - } - - try { - char asChar = (char) Integer.parseInt(numericChar.toLowerCase(), 16); - - result.append(asChar); - current += escaped.length(); - } catch (NumberFormatException badref) { - // it was bad, we will just skip it. - result.append(target.charAt(current)); - current++; - } - continue; - } - - // its base 10 - try { - char asChar = (char) Integer.parseInt(numericChar, 10); - - result.append(asChar); - current += escaped.length(); - } catch (NumberFormatException badref) { - // it was bad, we will just skip it. - result.append(target.charAt(current)); - current++; - } - continue; - } else { - // if we get here then we didn't know what to do with the - // entity. so we just send it unchanged. - result.append(target.charAt(current)); - current++; - continue; - } - - current++; - } - - return result; - } - - /** - * Given a StringBuilder find all occurrences of characters which must be - * escaped and convert them to their escaped equivalents. - * - * @param target The StringBuilder which will be encoded in place. - */ - protected void encodeEscaped(StringBuilder target) { - - int current = 0; - - while (current < target.length()) { - if ('&' == target.charAt(current)) { - target.insert(current + 1, "amp;"); - current += 5; - } else if ('<' == target.charAt(current)) { - target.setCharAt(current, '&'); - target.insert(current + 1, "lt;"); - current += 4; - } else { - current++; - } - } - } - - /** - * Returns an enumerations of the attributes associated with this object. - * Each element is of type Attribute. - * - * @return Enumeration the attributes associated with this object. - */ - public Enumeration getAttributes() { - List results = new ArrayList(); - - if (null != uninserted) { - throw new IllegalStateException("This element has not been added."); - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - // find the start of the first attribute - int current = loc.startTag.start + 1; - - while (current <= loc.startTag.end) { - char inTagName = getDocument().docContent.charAt(current); - - if (Character.isWhitespace(inTagName) || ('/' == inTagName) || ('>' == inTagName)) { - break; - } - current++; - } - - // loop and add attributes to the vector - while (current < loc.startTag.end) { - tagRange nextAttr = getAttributeLoc(null, new charRange(current, loc.startTag.end)); - - if (!nextAttr.isValid()) { - break; - } - - results.add( - new Attribute(this, getDocument().docContent.substring(nextAttr.startTag.start, nextAttr.startTag.end + 1) - , - getDocument().docContent.substring(nextAttr.body.start, nextAttr.body.end + 1))); - - current = nextAttr.endTag.end + 1; - } - - return Collections.enumeration(results); - } - - /** - * Returns the tagRange of the next attribute contained in the range - * provided. The tag range returned consists of the startTag indicating - * the location of the name, body indicating the location of the value and - * endTag indicating the location of the final quote delimiter. - * - * @param name Name to match. null means match any name. - * @param inRange the limits of the locations to scan. - * @return tagRange containing the location of the next attribute - */ - protected tagRange getAttributeLoc(String name, charRange inRange) { - tagRange result = new tagRange(); - int current = inRange.start; - - do { - // skip the whitespace - - while (current <= inRange.end) { - char inTagName = getDocument().docContent.charAt(current); - - if (!Character.isWhitespace(inTagName) && ('/' != inTagName) && ('>' != inTagName)) { - break; - } - current++; - } - - int equalsAt = getDocument().docContent.indexOf("=", current); - - // make sure there is an equals - if ((-1 == equalsAt) || (equalsAt >= inRange.end)) { - return result; - } - - // get the name - result.startTag.start = current; - result.startTag.end = equalsAt - 1; - - // get the quote char we must match - String requiredQuote = getDocument().docContent.substring(equalsAt + 1, equalsAt + 2); - - // make sure its a valid quote - if (('\'' != requiredQuote.charAt(0)) && ('\"' != requiredQuote.charAt(0))) { - return result; - } - - // find the next occurance of this quote - int nextQuote = getDocument().docContent.indexOf(requiredQuote, equalsAt + 2); - - // make sure the quote is in a good spot. - if ((-1 == nextQuote) || (nextQuote >= inRange.end)) { - return result; - } - - result.body.start = equalsAt + 2; - result.body.end = nextQuote - 1; - - result.endTag.start = nextQuote; - result.endTag.end = nextQuote; - - // check if the name matches. - if ((null != name) && !name.equals(getDocument().docContent.substring(result.startTag.start, result.startTag.end + 1))) { - result.startTag.start = -1; - } - - current = nextQuote + 1; - } while ((current < inRange.end) && (!result.isValid())); - - return result; - } - - /** - * {@inheritDoc} - */ - public String addAttribute(String name, String value) { - if (null != uninserted) { - throw new IllegalStateException("This element has not been added."); - } - - if (null == name) { - throw new IllegalArgumentException("name must not be null"); - } - - if (null == value) { - throw new IllegalArgumentException("value must not be null"); - } - - for (int eachChar = name.length() - 1; eachChar >= 0; eachChar--) { - if (Character.isWhitespace(name.charAt(eachChar))) { - throw new IllegalArgumentException("Attribute names may not contain spaces."); - } - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - // skip past the name portion - int current = loc.startTag.start + 1; - - while (current <= loc.startTag.end) { - char inTagName = getDocument().docContent.charAt(current); - - if (Character.isWhitespace(inTagName) || ('/' == inTagName) || ('>' == inTagName)) { - break; - } - - current++; - } - - // find out if there was a previous value for this name - String oldValue = null; - tagRange oldAttr = getAttributeLoc(name, new charRange(current, loc.startTag.end)); - - // choose which kind of quote to use - char usingQuote = (-1 != value.indexOf('"')) ? '\'' : '\"'; - - // make sure we can use it. - if (('\'' == usingQuote) && (-1 != value.indexOf('\''))) { - throw new IllegalArgumentException("Value contains both \" and \'"); - } - - // build the new attribute string - StringBuilder newStuff = new StringBuilder(" "); - - newStuff.append(name); - newStuff.append("="); - newStuff.append(usingQuote); - newStuff.append(value); - newStuff.append(usingQuote); - - // add it in. - if (!oldAttr.isValid()) { - // we aren't replacing an existing value - getDocument().docContent.insert(current, newStuff.toString()); - - // move all doc locations which follow this one based on how much we - // inserted. - getDocument().adjustLocations(current, newStuff.length()); - } else { - // we are replacing an existing value - oldValue = getDocument().docContent.substring(oldAttr.body.start, oldAttr.body.end + 1); - - getDocument().docContent.delete(oldAttr.body.start, oldAttr.body.end + 1); - getDocument().docContent.insert(oldAttr.body.start, value); - - int delta = value.length() - (oldAttr.body.end - oldAttr.body.start + 1); - - // move all doc locations which follow this one based on how much we - // inserted or deleted. - getDocument().adjustLocations(loc.startTag.start + 1, delta); - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - return oldValue; - } - - /** - * {@inheritDoc} - */ - public String addAttribute(Attribute newAttrib) { - return addAttribute(newAttrib.getName(), newAttrib.getValue()); - } - - /** - * {@inheritDoc} - */ - public Attribute getAttribute(String name) { - if (null != uninserted) { - throw new IllegalStateException("This element has not been added."); - } - - if (paranoidConsistencyChecking) { - checkConsistency(); - } - - // skip past the name portion - int current = loc.startTag.start + 1; - - while (current <= loc.startTag.end) { - char inTagName = getDocument().docContent.charAt(current); - - if (Character.isWhitespace(inTagName) || ('/' == inTagName) || ('>' == inTagName)) { - break; - } - - current++; - } - - // find the attribute matching this name - tagRange attr = getAttributeLoc(name, new charRange(current, loc.startTag.end)); - - if (!attr.isValid()) { - return null; - } - - // build the object - return new Attribute(this, getDocument().docContent.substring(attr.startTag.start, attr.startTag.end + 1) - , - getDocument().docContent.substring(attr.body.start, attr.body.end + 1)); - } - - protected boolean checkConsistency() { - assert loc.isValid(); - - charRange elementRange = new charRange(loc.startTag.start, loc.endTag.end); - - assert elementRange.contains(loc.startTag); - assert elementRange.contains(loc.body); - assert elementRange.contains(loc.endTag); - - if (null != children) { - Iterator eachChild = children.iterator(); - Iterator nextChilds = children.iterator(); - - if (nextChilds.hasNext()) { - nextChilds.next(); - } - - while (eachChild.hasNext()) { - LiteXMLElement aChild = eachChild.next(); - - assert loc.contains(aChild.loc); - - if (nextChilds.hasNext()) { - LiteXMLElement nextChild = nextChilds.next(); - - assert aChild.loc.compareTo(nextChild.loc) < 0; - } else { - assert !eachChild.hasNext(); - } - - aChild.checkConsistency(); - } - } - return true; - } - - /** - * The document we are a part of. - * - * @return The document we are a part of. - */ - LiteXMLDocument getDocument() { - return doc; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/PlainTextDocument.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/PlainTextDocument.java deleted file mode 100644 index 4dc0f944..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/PlainTextDocument.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.document; - - -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; - -import java.io.IOException; -import java.security.ProviderException; - -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.TextElement; -import net.jxta.document.TextDocument; - - -/** - * This class is an implementation of the StructuredDocument interface using - * simple text - */ -public class PlainTextDocument extends PlainTextElement implements StructuredTextDocument { - - private final static class Instantiator implements StructuredDocumentFactory.TextInstantiator { - - /** - * The MIME Media Types which this StructuredDocument is - * capable of emitting. - */ - private static final MimeMediaType[] myTypes = { - MimeMediaType.TEXT_DEFAULTENCODING - }; - - // these are the file extensions which are likely to contain files of - // the type i like. - private static final ExtensionMapping[] myExtensions = { - new ExtensionMapping("txt", myTypes[0]), new ExtensionMapping("text", myTypes[0]), new ExtensionMapping("txt", null) }; - - /** - * Creates new PlainTextDocument - */ - public Instantiator() {} - - /** - * {@inheritDoc} - */ - public MimeMediaType[] getSupportedMimeTypes() { - return (myTypes); - } - - /** - * {@inheritDoc} - */ - public ExtensionMapping[] getSupportedFileExtensions() { - return (myExtensions); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, String doctype) { - return new PlainTextDocument(mimeType, doctype); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, String doctype, String value) { - return new PlainTextDocument(mimeType, doctype, value); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, InputStream source) throws IOException { - throw new ProviderException("PlainTextDocument does not support input"); - } - - /** - * {@inheritDoc} - */ - public StructuredDocument newInstance(MimeMediaType mimeType, Reader source) throws IOException { - throw new ProviderException("PlainTextDocument does not support input"); - } - - } - - public static final StructuredDocumentFactory.TextInstantiator INSTANTIATOR = new Instantiator(); - - private MimeMediaType mimeType = null; - - /** - * Creates new PlainTextDocument - */ - public PlainTextDocument(final MimeMediaType mimeType, String type) { - super(null, type); - doc = this; - parent = this; - - this.mimeType = mimeType; - } - - /** - * Creates new PlainTextDocument with a value for the root element - */ - public PlainTextDocument(final MimeMediaType mimeType, final String type, final String value) { - super(null, type, value); - doc = this; - parent = this; - - this.mimeType = mimeType; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringWriter stringOut = new StringWriter(); - - try { - printNice(stringOut, 0, true); - stringOut.close(); - } catch (IOException caught) { - return null; - } - - return stringOut.toString(); - } - - /** - * get Type - */ - public MimeMediaType getMimeType() { - return mimeType; - } - - /** - * {@inheritDoc} - */ - public String getFileExtension() { - return TextDocumentCommon.Utils.getExtensionForMime(INSTANTIATOR.getSupportedFileExtensions(), getMimeType()); - } - - /** - * {@inheritDoc} - */ - public PlainTextElement createElement(Object key) { - return createElement(key, null); - } - - /** - * {@inheritDoc} - */ - public PlainTextElement createElement(Object key, Object val) { - if (!String.class.isAssignableFrom(key.getClass())) { - throw new ClassCastException(key.getClass().getName() + " not supported by createElement."); - } - - if ((null != val) && !String.class.isAssignableFrom(val.getClass())) { - throw new ClassCastException(val.getClass().getName() + " not supported by createElement."); - } - - return new PlainTextElement(this, (String) key, (String) val); - } - - /** - * {@inheritDoc} - */ - public PlainTextElement createElement(String name) { - return new PlainTextElement(this, name); - } - - /** - * {@inheritDoc} - */ - public PlainTextElement createElement(String name, String val) { - return new PlainTextElement(this, name, val); - } - - /** - * {@inheritDoc} - */ - public InputStream getStream() throws IOException { - // XXX bondolo@jxta.org 20010307 Should be using a pipe - String charset = mimeType.getParameter("charset"); - - if (charset == null) { - return new ByteArrayInputStream(toString().getBytes()); - } else { - return new ByteArrayInputStream(toString().getBytes(charset)); - } - } - - /** - * {@inheritDoc} - */ - public void sendToStream(OutputStream stream) throws IOException { - String charset = mimeType.getParameter("charset"); - - Writer osw; - - if (charset == null) { - osw = new OutputStreamWriter(stream); - } else { - osw = new OutputStreamWriter(stream, charset); - } - - Writer out = new BufferedWriter(osw); - - sendToWriter(out); - out.flush(); - } - - /** - * {@inheritDoc} - */ - public Reader getReader() { - // XXX bondolo@jxta.org 20010307 Should be using a pipe - - return new StringReader(toString()); - } - - /** - * {@inheritDoc} - */ - public void sendToWriter(Writer stream) throws IOException { - printNice(stream, 0, true); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/PlainTextElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/PlainTextElement.java deleted file mode 100644 index af632e99..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/PlainTextElement.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.document; - - -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.Vector; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import java.io.IOException; - -import net.jxta.document.Element; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.TextElement; - -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; - - -/** - * This class is an implementation of the StructuredDocument interface using - * simple text - */ -public class PlainTextElement implements TextElement, Attributable { - protected PlainTextDocument doc; - - protected PlainTextElement parent; - - protected final String name; - - protected final String val; - - private List children = new Vector(); - - private Map attributes = new HashMap(); - - /** - * Creates new PlainTextElement - */ - protected PlainTextElement(PlainTextDocument doc, String name) { - this(doc, name, null); - } - - /** - * Creates new PlainTextElement - */ - protected PlainTextElement(PlainTextDocument doc, String name, String val) { - this.doc = doc; - this.name = name; - this.val = val; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object element) { - if (this == element) { - return true; - } - - if (!(element instanceof PlainTextElement)) { - return false; - } - - PlainTextElement textElement = (PlainTextElement) element; - - if (doc != textElement.doc) { - return false; - } - - if (!getName().equals(textElement.getName())) { - return false; - } - - String val1 = getTextValue(); - String val2 = textElement.getTextValue(); - - if ((null == val1) && (null == val2)) { - return true; - } - - if ((null == val1) || (null == val2)) { - return false; - } - - return val1.equals(val2); - } - - /** - * {@inheritDoc} - */ - public StructuredTextDocument getRoot() { - return (StructuredTextDocument) doc; - } - - /** - * Get the name associated with an element. - * - * @return A string containing the key of this element. - */ - public String getKey() { - return getName(); - } - - /** - * Get the value (if any) associated with an element. - * - * @return A string containing the value of this element, if any, otherwise null. - */ - public String getValue() { - return getTextValue(); - } - - /** - * {@inheritDoc} - */ - public PlainTextElement getParent() { - return parent; - } - - /** - * {@inheritDoc} - */ - public Enumeration getChildren() { - return Collections.enumeration(children); - } - - /** - * {@inheritDoc} - */ - public String getName() { - return name; - } - - /** - * {@inheritDoc} - */ - public String getTextValue() { - return val; - } - - /** - * {@inheritDoc} - */ - public void appendChild(PlainTextElement element) { - if (element.doc != this.doc) { - throw new IllegalArgumentException("Wrong Document"); - } - - element.parent = this; - children.add(element); - } - - /** - * {@inheritDoc} - */ - public Enumeration getChildren(Object key) { - if (key instanceof String) - return getChildren((String) key); - else - throw new ClassCastException(key.getClass().getName() + " not supported by getChildren."); - } - - /** - * {@inheritDoc} - */ - public Enumeration getChildren(String name) { - List result = new ArrayList(); - - for (Iterator eachChild = children.iterator(); eachChild.hasNext();) { - TextElement aChild = (TextElement) eachChild.next(); - - if (name.equals(aChild.getName())) { - result.add(aChild); - } - } - - return Collections.enumeration(result); - } - - /** - * Write the contents of this element and optionally its children. The - * writing is done to a provided java.io.Writer. The writing can optionally - * be indented - * - * @param into The java.io.Writer that the output will be sent to. - * @param indent the number of tabs which will be inserted before each - * line. - * @param recurse if true then also print the children of this element. - */ - protected void printNice(Writer into, int indent, boolean recurse) throws IOException { - - // do indent - for (int eachTab = 0; eachTab < indent; eachTab++) { - into.write("\t"); - } - - // print node name - into.write(name); - - // print attributes - Enumeration attributes = getAttributes(); - - if (attributes.hasMoreElements()) { - into.write(" ( "); - - while (attributes.hasMoreElements()) { - Attribute anAttr = (Attribute) attributes.nextElement(); - - into.write(anAttr.getName() + "=\"" + anAttr.getValue() + "\" "); - } - into.write(")"); - } - - into.write(" : "); - // print node value - if (null != val) { - into.write(val + "\n"); - } else { - into.write("\n"); - } - - // recurse as needed - if (recurse) { - for (Enumeration childrens = getChildren(); childrens.hasMoreElements();) { - ((PlainTextElement) childrens.nextElement()).printNice(into, indent + 1, recurse); - } - } - } - - // Attributable methods - - /** - * {@inheritDoc} - */ - public String addAttribute(String name, String value) { - - String oldAttrValue = (String) attributes.remove(name); - - attributes.put(name, value); - - return oldAttrValue; - } - - /** - * Adds an attribute with the given name and value. Some implementations - * may support only a single value for each distinct name. Others may - * support multiple values for each name. If the value being provided - * replaces some other value then that value is returned otherwise null - * is returned. - * - * @param newAttrib new attribute. - * @return String containing previous value for this name if the value - * is being replaced otherwise null. - */ - public String addAttribute(Attribute newAttrib) { - return addAttribute(newAttrib.getName(), newAttrib.getValue()); - } - - /** - * {@inheritDoc} - */ - public Enumeration getAttributes() { - - Vector attrs = new Vector(); - - for (Iterator eachAttr = attributes.entrySet().iterator(); eachAttr.hasNext();) { - Map.Entry anAttr = (Map.Entry) eachAttr.next(); - - Attribute attr = new Attribute(this, (String) anAttr.getKey(), (String) anAttr.getValue()); - - attrs.addElement(attr); - } - - return attrs.elements(); - } - - /** - * {@inheritDoc} - */ - public Attribute getAttribute(String name) { - String value = (String) attributes.get(name); - - if (null == value) { - return null; - } - - // build the object - return new Attribute(this, name, value); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/TextDocumentCommon.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/TextDocumentCommon.java deleted file mode 100644 index 915de2e7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/document/TextDocumentCommon.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.document; - - -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; - - -/** - * Empty interface we use a container for utils - */ -interface TextDocumentCommon { - - /** - * static utility methods. - */ - static class Utils { - - static String getExtensionForMime(StructuredDocumentFactory.Instantiator.ExtensionMapping[] mappings, MimeMediaType mimeType) { - MimeMediaType cleanMime = new MimeMediaType(mimeType.getMimeMediaType()); - String result = "???"; - - for (int eachMapping = 0; eachMapping < mappings.length; eachMapping++) { - // assign the extension as the result if this is the default - if (null == mappings[eachMapping].getMimeMediaType()) { - result = mappings[eachMapping].getExtension(); - } - - if (mappings[eachMapping].getMimeMediaType().equals(cleanMime)) { - result = mappings[eachMapping].getExtension(); - break; - } - } - - return result; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/BlockingMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/BlockingMessenger.java deleted file mode 100644 index a1daaf15..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/BlockingMessenger.java +++ /dev/null @@ -1,881 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint; - -import java.util.Timer; -import java.util.TimerTask; - -import java.io.IOException; -import java.io.InterruptedIOException; - -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import java.util.logging.Logger; - -import net.jxta.endpoint.AbstractMessenger; -import net.jxta.endpoint.ChannelMessenger; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.MessengerState; -import net.jxta.endpoint.OutgoingMessageEvent; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.util.SimpleSelectable; - -import net.jxta.impl.util.TimeUtils; - -/** - * This class is a near-drop-in replacement for the previous BlockingMessenger class. - * To subclassers (that is, currently, transports) the only difference is that some - * overloaded methods have a different name (class hierarchy reasons made it impossible - * to preserve the names without forcing an API change for applications). - * - * The other difference which is not API visible, is that it implements the - * standard MessengerState behaviour and semantics required by the changes in the endpoint framework. - * - * This the only base messenger class meant to be extended by outside code that is in the impl tree. The - * reason being that what it replaces was there already and that new code should not become dependant upon it. - */ -public abstract class BlockingMessenger extends AbstractMessenger { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(BlockingMessenger.class.getName()); - - /** - * The self destruct timer. - *

      - * When a messenger has become idle, it is closed. As a side effect, it - * makes the owning canonical messenger, if any, subject to removal if it is - * otherwise unreferenced. - */ - private final static transient Timer timer = new Timer("BlockingMessenger self destruct timer", true); - - /* - * Actions that we defer to after returning from event methods. In other - * words, they cannot be done with the lock held, or they require calling - * more event methods. Because this messenger can take only one message at - * a time (saturated while sending), actions do not cascade much. Start can - * lead to connect if the sending fails, but, because we always fail to - * connect, connect will not lead to start. As a result we can get away with - * performing deferred actions recursively. That simplifies the code. - */ - private enum DeferredAction { - /** - * No deferred action. - */ - ACTION_NONE, - - /** - * Must send message. - */ - ACTION_SEND, - - /** - * Must report failure to connect. - */ - ACTION_CONNECT - } - - /** - * The outstanding message. - */ - private Message currentMessage = null; - - /** - * The serviceName override for that message. - */ - private String currentService = null; - - /** - * The serviceParam override for that message. - */ - private String currentParam = null; - - /** - * The exception that caused that message to not be sent. - */ - private Throwable currentThrowable = null; - - /** - * true if we have deliberately closed our one message input queue. - */ - private boolean inputClosed = false; - - /** - * Need to know which group this transport lives in, so that we can suppress - * channel redirection when in the same group. This is currently the norm. - */ - private final PeerGroupID homeGroupID; - - /** - * The current deferred action. - */ - private DeferredAction deferredAction = DeferredAction.ACTION_NONE; - - /** - * Reference to owning object. This is there so that the owning object is not subject to garbage collection - * unless this object here becomes itself unreferenced. That happens when the self destruct timer closed it. - */ - private Object owner = null; - - /** - * The timer task watching over our self destruction requirement. - */ - private final TimerTask selfDestructTask; - - /** - * State lock and engine. - */ - private final BlockingMessengerState stateMachine = new BlockingMessengerState(); - - /** - * legacy artefact: transports need to believe the messenger is not yet closed in order to actually close it. - * So we lie to them just while we run their closeImpl method so that they do not see that the messenger is - * officially closed. - */ - private boolean lieToOldTransports = false; - - /** - * Our statemachine implementation; just connects the standard AbstractMessengerState action methods to - * this object. - */ - private class BlockingMessengerState extends MessengerState { - - protected BlockingMessengerState() { - super(true); - } - - /* - * The required action methods. - */ - - /** - * {@inheritDoc} - */ - @Override - protected void connectAction() { - deferredAction = DeferredAction.ACTION_CONNECT; - } - - /** - * {@inheritDoc} - */ - @Override - protected void startAction() { - deferredAction = DeferredAction.ACTION_SEND; - } - - /** - * {@inheritDoc} - */ - @Override - protected void closeInputAction() { - // we're synchonized here. (invoked from stateMachine). - inputClosed = true; - } - - /** - * {@inheritDoc} - */ - @Override - protected void closeOutputAction() { - // This will break the cnx; thereby causing a down event if we have a send in progress. - // If the cnx does not break before the current message is sent, then the message will be sent successfully, - // resulting in an idle event. Either of these events is enough to complete the shutdown process. - lieToOldTransports = true; - closeImpl(); - lieToOldTransports = false; - - // Disconnect from the timer. - if (selfDestructTask != null) { - selfDestructTask.cancel(); - } - } - - // This is a synchronous action. No synchronization needed: we're already synchronized, here. - // There's a subtlety here: we do not clear the current message. We let sendMessageB or sendMessageN - // deal with it, so that they can handle the status reporting each in their own way. So basically, all we - // do is to set a reason for that message to fail in case we are shutdown from the outside and that message - // is not sent yet. As long as there is a current message, it is guaranteed that there is a thread - // in charge of reporting its status. It is also guaranteed that when failAll is called, the input is - // already closed, and so, we have no obligation of making room for future messages immediately. - // All this aggravation is so that we do not have to create one context wrapper for each message just so - // that we can associate it with its result. Instead we use our single msg and single status model - // throughout. - @Override - protected void failAllAction() { - - if (currentMessage == null) { - return; - } - - if (currentThrowable == null) { - currentThrowable = new IOException("Messenger unexpectedly closed"); - } - } - } - - - /** - * The implementation of channel messenger that getChannelMessenger returns: - * All it does is address rewriting. Even close() is forwarded to the shared messenger. - * The reason is that BlockingMessengers are not really shared; they're transitional - * entities used directly by CanonicalMessenger. GetChannel is used only to provide address - * rewriting when we pass a blocking messenger directly to incoming messenger listeners...this - * practice is to be removed in the future, in favor of making incoming messengers full-featured - * async messengers that can be shared. - */ - private final class BlockingMessengerChannel extends ChannelMessenger { - - public BlockingMessengerChannel(EndpointAddress baseAddress, PeerGroupID redirection, String origService, String origServiceParam) { - - super(baseAddress, redirection, origService, origServiceParam); - - // We tell our super class that we synchronize on the stateMachine object. Althoug it is not obvious, our getState() - // method calls the shared messenger getState() method, which synchronizes on the shared messenger's state machine - // object. So, that's what we must specify. Logic would dictate that we pass it to super(), but it is not itself - // constructed until super() returns. No way around it. - - setStateLock(stateMachine); - } - - /** - * {@inheritDoc} - */ - public int getState() { - return BlockingMessenger.this.getState(); - } - - /** - * {@inheritDoc} - */ - public void resolve() { - BlockingMessenger.this.resolve(); - } - - /** - * {@inheritDoc} - */ - public void close() { - BlockingMessenger.this.close(); - } - - /** - * {@inheritDoc} - * - *

      - * Address rewriting done here. - */ - public boolean sendMessageN(Message msg, String service, String serviceParam) { - return BlockingMessenger.this.sendMessageN(msg, effectiveService(service), effectiveParam(service, serviceParam)); - } - - /** - * {@inheritDoc} - * - *

      - * Address rewriting done here. - */ - public void sendMessageB(Message msg, String service, String serviceParam) throws IOException { - BlockingMessenger.this.sendMessageB(msg, effectiveService(service), effectiveParam(service, serviceParam)); - } - - /** - * {@inheritDoc} - * - *

      - * We're supposed to return the complete destination, including - * service and param specific to that channel. It is not clear, whether - * this should include the cross-group mangling, though. For now, let's - * say it does not. - */ - public EndpointAddress getLogicalDestinationAddress() { - EndpointAddress rawLogical = getLogicalDestinationImpl(); - - if (rawLogical == null) { - return null; - } - return new EndpointAddress(rawLogical, origService, origServiceParam); - } - - // Check if it is worth staying registered - public void itemChanged(Object changedObject) { - - if (!notifyChange()) { - if (haveListeners()) { - return; - } - - BlockingMessenger.this.unregisterListener(this); - - if (!haveListeners()) { - return; - } - - // Ooops collision. We should not have unregistered. Next time, then. In case of collision, the end result - // is always to stay registered. There's no harm in staying registered. - BlockingMessenger.this.registerListener(this); - } - } - - /** - * {@inheritDoc} - *

      - * Always make sure we're registered with the shared messenger. - */ - @Override - protected void registerListener(SimpleSelectable l) { - BlockingMessenger.this.registerListener(this); - super.registerListener(l); - } - } - - private void storeCurrent(Message msg, String service, String param) { - currentMessage = msg; - currentService = service; - currentParam = param; - currentThrowable = null; - } - - /** - * Constructor. - *

      - * We start in the CONNECTED state, we pretend to have a queue of size 1, and we can never re-connect. Although this - * messenger fully respects the asynchronous semantics, it is saturated as soon as one msg is being send, and if not - * saturated, send is actually performed by the invoker thread. So return is not completely immediate. This is a barely - * acceptable implementation, but this is also a transition adapter that is bound to disappear one release from now. The main - * goal is to get things going until transports are adapted. - * - * @param homeGroupID the group that this messenger works for. This is the group of the endpoint service or transport - * that created this messenger. - * @param dest where messages should be addressed to - * @param selfDestruct true if this messenger must self close destruct when idle. Warning: If selfDestruct is used, - * this messenger will remained referenced for as long as isIdleImpl returns false. - */ - - public BlockingMessenger(PeerGroupID homeGroupID, EndpointAddress dest, boolean selfDestruct) { - - super(dest); - - this.homeGroupID = homeGroupID; - - // We tell our superclass that we synchronize our state on the stateMachine object. Logic would dictate that we pass it - // to super(), but it is not itself constructed until super() returns. No way around it. - - setStateLock(stateMachine); - - /* - * Sets up a timer task that will close this messenger if it says to have become idle. It will keep it referenced - * until then. - *

      - * As long as this timer task is scheduled, this messenger is not subject to GC. Therefore, its owner, if any, which is strongly - * referenced, is not subject to GC either. This avoids prematurely closing open connections just because a destination is - * not currently in use, which we would have to do if CanonicalMessengers could be GCed independantly (and which would - * force us to use finalizers, too).

      - * - * Such a mechanism is usefull only if this blocking messenger is expensive to make or holds system resources that require - * an explicit invocation of the close method. Else, it is better to let it be GC'ed along with any refering canonical - * messenger when memory is tight.

      - * - */ - - // - // FIXME 20040413 jice : we trust transports to implement isIdle reasonably, which may be a leap of faith. We - // should probably superimpose a time limit of our own. - // - if (selfDestruct) { - selfDestructTask = new TimerTask() { - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - if (isIdleImpl()) { - close(); - } else { - return; - } - } catch (Throwable uncaught) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in selfDescructTask. ", uncaught); - } - } - cancel(); - } - }; - - timer.schedule(selfDestructTask, TimeUtils.AMINUTE, TimeUtils.AMINUTE); - } else { - selfDestructTask = null; - } - } - - /** - * Sets an owner for this blocking messenger. Owners are normally canonical messengers. The goal of registering the owner is - * to keep that owner reachable as long as this blocking messenger is. Canonical messengers are otherwise softly referenced, - * and so, may be deleted whenever memory is tight. - *

      - * We do not want to use finalizers or the equivalent reference queue mechanism; so we have no idea when a blocking messenger - * is no-longer referenced by any canonical. In addition it may be expensive to make and so we want to keep it for a while - * anyway. As a result, instead of keeping a blocking messenger open as long as there is a canonical, we do the opposite: we - * keep the canonical (owner, here) as long as the blocking messenger is open (and usually beyond, memory allowing). How long - * a blocking messenger will stay around depends upon that messenger's implementation. That may even be left up to the GC, in - * the end (if close is not needed AND the messenger is cheap to make). In that case, the owner is likely the only referrer, - * and so both will have the same lifetime. - * - * @param owner The object that should be kept referenced at least as long as this one. - */ - public void setOwner(Object owner) { - this.owner = owner; - } - - /** - * Assemble a destination address for a message based upon the messenger - * default destination address and the optional provided overrides. - * - * @param service The destination service or {@code null} to use default. - * @param serviceParam The destination service parameter or {@code null} to - * use default. - */ - protected EndpointAddress getDestAddressToUse(String service, String serviceParam) { - EndpointAddress defaultAddress = getDestinationAddress(); - EndpointAddress result; - - if(null == service) { - if(null == serviceParam) { - // Use default service name and service params - result = defaultAddress; - } else { - // use default service name, override service params - result = new EndpointAddress(defaultAddress, defaultAddress.getServiceName(), serviceParam); - } - } else { - if(null == serviceParam) { - // override service name, use default service params (this one is pretty weird and probably not useful) - result = new EndpointAddress(defaultAddress, service, defaultAddress.getServiceParameter()); - } else { - // override service name, override service params - result = new EndpointAddress(defaultAddress, service, serviceParam); - } - } - - return result; - } - - /** - * A transport may call this to cause an orderly closure of its messengers. - */ - protected final void shutdown() { - DeferredAction action; - - synchronized (stateMachine) { - stateMachine.shutdownEvent(); - action = eventCalled(); - } - - // We called an event. State may have changed. - notifyChange(); - - performDeferredAction(action); - } - - /** - * {@inheritDoc} - *

      - * We overload isClosed because many messengers still use super.isClosed() - * as part of their own implementation or don't override it at all. They - * expect it to be true only when all is shutdown; not while we're closing - * gently. - * - * FIXME - jice@jxta.org 20040413: transports should get a deeper retrofit eventually. - */ - @Override - public boolean isClosed() { - return (!lieToOldTransports) && super.isClosed(); - } - - /** - * {@inheritDoc} - *

      - * getLogicalDestinationAddress() requires resolution (it's the address advertised by the other end). - * For a blocking messenger it's easy. We're born resolved. So, just ask the implementor what it is. - */ - public final EndpointAddress getLogicalDestinationAddress() { - return getLogicalDestinationImpl(); - } - - /** - * {@inheritDoc} - * - *

      Some transports historically overload the close method of BlockingMessenger. - * The final is there to make sure we know about it. However, there should be no - * harm done if the unchanged code is renamed to closeImpl; even if it calls super.close(). - * The real problem, however, is transports calling close (was their own, but now it means this one), when - * they want to break. It will make things look like someone just called close, but it will not - * actually break anything. However, that will cause the state machine to go through the close process. - * this will end up calling closeImpl(). That will do. - */ - public final void close() { - DeferredAction action; - - synchronized (stateMachine) { - stateMachine.closeEvent(); - - action = eventCalled(); - } - - // We called an event. State may have changed. - notifyChange(); - - performDeferredAction(action); - } - - /** - * {@inheritDoc} - */ - public void sendMessageB(Message msg, String service, String serviceParam) throws IOException { - - DeferredAction action; - - synchronized (stateMachine) { - try { - while ((currentMessage != null) && !inputClosed) { - stateMachine.wait(); - } - } catch (InterruptedException ie) { - throw new InterruptedIOException(); - } - - if (inputClosed) { - throw new IOException("Messenger is closed. It cannot be used to send messages"); - } - - // We store the four elements of a pending msg separately. We do not want to pour millions of tmp objects on the GC for - // nothing. - - storeCurrent(msg, service, serviceParam); - stateMachine.saturatedEvent(); - action = eventCalled(); - } - - notifyChange(); // We called an event. State may have changed. - performDeferredAction(action); // We called an event. There may be an action. (start, normally). - - // After deferred action, the message was either sent or failed. (done by this thread). - // We can tell because, if failed, the currentMessage is still our msg. - Throwable failure = null; - - synchronized (stateMachine) { - if (currentMessage == msg) { - failure = currentThrowable; - if (failure == null) { - failure = new IOException("Unknown error"); - } - // Ok, let it go, now. - storeCurrent(null, null, null); - } // Else, don't touch currentMsg; it's not our msg. - } - - if (failure == null) { - // No failure. Report ultimate succes. - msg.setMessageProperty(Messenger.class, OutgoingMessageEvent.SUCCESS); - return; - } - - // Failure. See how we can manage to throw it. - if (failure instanceof IOException) { - throw (IOException) failure; - } - if (failure instanceof RuntimeException) { - throw (RuntimeException) failure; - } - if (failure instanceof Error) { - throw (Error) failure; - } - - IOException failed = new IOException("Failure sending message"); - failed.initCause(failure); - throw failed; - } - - /** - * {@inheritDoc} - */ - public final boolean sendMessageN(Message msg, String service, String serviceParam) { - - boolean queued = false; - DeferredAction action = DeferredAction.ACTION_NONE; - boolean closed; - - synchronized (stateMachine) { - closed = inputClosed; - if ((!closed) && (currentMessage == null)) { - // We copy the four elements of a pending msg right here. We do not want to pour millions of tmp objects on the GC. - storeCurrent(msg, service, serviceParam); - stateMachine.saturatedEvent(); - action = eventCalled(); - queued = true; - } - } - - if (queued) { - notifyChange(); // We called an event. State may have changed. - performDeferredAction(action); // We called an event. There may be an action. (start, normally). - - // After deferred action, the message was either sent or failed. (done by this thread). - // We can tell because, if failed, the currentMessage is still our msg. - synchronized (stateMachine) { - if (currentMessage == msg) { - if (currentThrowable == null) { - currentThrowable = new IOException("Unknown error"); - } - msg.setMessageProperty(Message.class, currentThrowable); - // Ok, let it go, now. - storeCurrent(null, null, null); - } else { - msg.setMessageProperty(Message.class, OutgoingMessageEvent.SUCCESS); - // Don't touch the current msg; it's not our msg. - } - } - // Yes, we return true in either case. sendMessageN is supposed to be async. If a message fails - // after it was successfuly queued, the error is not reported by the return value, but only by - // the message property (and select). Just making sure the behaviour is as normal as can be - // even it means suppressing some information. - - return true; - } - - // Not queued. Either closed, or currently sending. If inputClosed, that's what we report. - msg.setMessageProperty(Messenger.class, - closed ? - new OutgoingMessageEvent(msg, new IOException("This messenger is closed. " + "It cannot be used to send messages.")) : - OutgoingMessageEvent.OVERFLOW); - return false; - } - - /** - * {@inheritDoc} - */ - public final void resolve() {// We're born resolved. Don't bother calling the event. - } - - /** - * {@inheritDoc} - */ - public final int getState() { - return stateMachine.getState(); - } - - /** - * {@inheritDoc} - */ - public final Messenger getChannelMessenger(PeerGroupID redirection, String service, String serviceParam) { - - // Our transport is always in the same group. If the channel's target group is the same, no group - // redirection is ever needed. - - return new BlockingMessengerChannel(getDestinationAddress(), - homeGroupID.equals(redirection) ? null : redirection, service, - serviceParam); - } - - /** - * Three exposed methods may need to inject new events in the system: sendMessageN, close, and shutdown. Since they can both - * cause actions, and since connectAction and startAction are deferred, it seems possible that one of the - * actions caused by send, close, or shutdown be called while connectAction or startAction are in progress. - * - * However, the state machine gives us a few guarantees: connectAction and startAction can never nest. We will not be - * asked to perform one while still performing the other. Only the synchronous actions closeInput, closeOutput, or - * failAll can possibly be requested in the interval. We could make more assumptions and simplify the code, but rather - * keep at least some flexibility. - */ - - private void performDeferredAction(DeferredAction action) { - switch (action) { - case ACTION_SEND: - sendIt(); - break; - - case ACTION_CONNECT: - cantConnect(); - break; - } - } - - /** - * A shortHand for a frequently used sequence. MUST be called while synchronized on stateMachine. - * - * @return the deferred action. - */ - private DeferredAction eventCalled() { - DeferredAction action = deferredAction; - - deferredAction = DeferredAction.ACTION_NONE; - stateMachine.notifyAll(); - return action; - } - - /** - * Performs the ACTION_SEND deferred action: sends the one msg in our one msg queue. - * This method *never* sets the outcome message property. This is left to sendMessageN and sendMessageB, because - * sendMessageB does not want to set it in any other case than success, while sendMessageN does it in all cases. - * The problem with that is: how do we communicate the outcome to sendMessage{NB} without having to keep - * the 1 msg queue locked until then (which would be in contradiction with how we interact with the state machine). - * To make it really inexpensive, here's the trick: when a message fails currentMessage and currentFailure remain. - * So the sendMessageRoutine can check them and known that it is its message and not another one that caused the - * failure. If all is well, currentMessage and currentFailure are nulled and if another message is send immediately - * sendMessage is able to see that its own message was processed fully. (this is a small cheat regarding the - * state of saturation after failall, but that's not actually detectable from the outside: input is closed - * before failall anyway. See failall for that part. - */ - private void sendIt() { - - if (currentMessage == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Internal error. Asked to send with no message."); - } - return; - } - - DeferredAction action; - - try { - sendMessageBImpl(currentMessage, currentService, currentParam); - } catch (Throwable any) { - // Did not work. We report the link down and let the state machine tell us when to fail the msg. It is assumed that - // when this happens, the cnx is already down. FIXME - jice@jxta.org 20040413: check with the various kind of funky - // exception. Some may not mean the link is down - synchronized (stateMachine) { - currentThrowable = any; - stateMachine.downEvent(); - action = eventCalled(); - } - notifyChange(); - performDeferredAction(action); // we expect connect but let the state machine decide. - return; - } - - // Worked. - - synchronized (stateMachine) { - storeCurrent(null, null, null); - stateMachine.idleEvent(); - action = eventCalled(); - } - - // We did go from non-idle to idle. Report it. - notifyChange(); - - performDeferredAction(action); // should be none but let the state machine decide. - } - - /** - * Performs the ACTION_CONNECT deferred action: generate a downEvent since we cannot reconnect. - */ - private void cantConnect() { - DeferredAction action; - - synchronized (stateMachine) { - stateMachine.downEvent(); - action = eventCalled(); - } - notifyChange(); - performDeferredAction(action); // should be none but let the state machine decide. - } - - /* - * Abstract methods to be provided by implementer (a transport for example). - * To adapt legacy transport, keep extending BlockingMessenger and just rename your close, isIdle, sendMessage and - * getLogicalDestinationAddress methods to closeImpl, isIdleImpl, sendMessageBImpl, and getLogicalDestinationImpl, respectively. - */ - - /** - * Close connection. May fail current send. - */ - protected abstract void closeImpl(); - - /** - * Send a message blocking as needed until the message is sent. - * - * @param message The message to send. - * @param service The destination service. - * @param param The destination serivce param. - * @throws IOException Thrown for errors encountered while sending the message. - */ - protected abstract void sendMessageBImpl(Message message, String service, String param) throws IOException; - - /** - * return true if this messenger has not been used for a long time. The definition of long time is: "sufficient such that closing it - * is worth the cost of having to re-open". A messenger should self close if it thinks it meets the definition of - * idle. BlockingMessenger leaves the evaluation to the transport but does the work automatically. Important: if - * self destruction is used, this method must work; not just return false. See the constructor. In general, if closeImpl does - * not need to do anything, then self destruction is not needed. - * - * @return {@code true} if theis messenger is, by it's own definition, idle. - */ - protected abstract boolean isIdleImpl(); - - /** - * Obtain the logical destination address from the implementer (a transport for example). - */ - protected abstract EndpointAddress getLogicalDestinationImpl(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/EndpointServiceImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/EndpointServiceImpl.java deleted file mode 100644 index d3db1125..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/EndpointServiceImpl.java +++ /dev/null @@ -1,1961 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.ChannelMessenger; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.MessageFilterListener; -import net.jxta.endpoint.MessagePropagater; -import net.jxta.endpoint.MessageReceiver; -import net.jxta.endpoint.MessageSender; -import net.jxta.endpoint.MessageTransport; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.MessengerEvent; -import net.jxta.endpoint.MessengerEventListener; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.endpoint.ThreadedMessenger; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.impl.endpoint.endpointMeter.EndpointMeter; -import net.jxta.impl.endpoint.endpointMeter.EndpointMeterBuildSettings; -import net.jxta.impl.endpoint.endpointMeter.EndpointServiceMonitor; -import net.jxta.impl.endpoint.endpointMeter.InboundMeter; -import net.jxta.impl.endpoint.endpointMeter.OutboundMeter; -import net.jxta.impl.endpoint.endpointMeter.PropagationMeter; -import net.jxta.impl.endpoint.relay.RelayClient; -import net.jxta.impl.endpoint.router.EndpointRouter; -import net.jxta.impl.endpoint.tcp.TcpTransport; -import net.jxta.impl.meter.MonitorManager; -import net.jxta.impl.util.SequenceIterator; -import net.jxta.logging.Logging; -import net.jxta.meter.MonitorResources; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.AccessPointAdvertisement; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import java.io.IOException; -import java.lang.ref.Reference; -import java.lang.ref.SoftReference; -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; -import java.util.WeakHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This class implements the frontend for all the JXTA endpoint protocols, as - * well as the API for the implementation of the core protocols that use - * directly the EndpointService. It theory it only needs to implement core methods. - * legacy or convenience methods should stay out. However, that would require - * a two-level interface for the service (internal and public). May be later. - */ -public class EndpointServiceImpl implements EndpointService, MessengerEventListener { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(EndpointServiceImpl.class.getName()); - - // // constants //// - - /** - * The Wire Message Format we will use by default. - */ - public static final MimeMediaType DEFAULT_MESSAGE_TYPE = new MimeMediaType("application/x-jxta-msg").intern(); - - /** - * The name of this service. - */ - public static final String ENDPOINTSERVICE_NAME = "EndpointService"; - - /** - * The Message empty namespace. This namespace is reserved for use by - * applications. It will not be used by core protocols. - */ - public static final String MESSAGE_EMPTY_NS = ""; - - /** - * The Message "jxta" namespace. This namespace is reserved for use by - * core protocols. It will not be used by applications. - */ - public static final String MESSAGE_JXTA_NS = "jxta"; - - /** - * Namespace in which the message source address will be placed. - */ - public static final String MESSAGE_SOURCE_NS = MESSAGE_JXTA_NS; - - /** - * Element name in which the message source address will be placed. - */ - public static final String MESSAGE_SOURCE_NAME = "EndpointSourceAddress"; - - /** - * Namespace in which the message destination address will be placed. - */ - public static final String MESSAGE_DESTINATION_NS = MESSAGE_JXTA_NS; - - /** - * Element name in which the message destination address will be placed. - * This element is used for loopback detection during propagate. Only - * propagate messages currently contain this element. - */ - public static final String MESSAGE_DESTINATION_NAME = "EndpointDestinationAddress"; - - /** - * Namespace in which the message source peer address will be placed. - */ - public static final String MESSAGE_SRCPEERHDR_NS = MESSAGE_JXTA_NS; - - /** - * Element name in which the message source peer address will be placed. - * This element is used for loopback detection during propagate. Only - * propagated messages currently contain this element. - */ - public static final String MESSAGE_SRCPEERHDR_NAME = "EndpointHeaderSrcPeer"; - - /** - * Size of the message queue provided by virtual messengers. - */ - private final static int DEFAULT_MESSAGE_QUEUE_SIZE = 20; - - /** - * If {@code true} then the parent endpoint may be used for acquiring - * messengers and for registering listeners. - */ - private final static boolean DEFAULT_USE_PARENT_ENDPOINT = true; - - EndpointServiceMonitor endpointServiceMonitor; - - /** - * the EndpointMeter - */ - private EndpointMeter endpointMeter; - private PropagationMeter propagationMeter; - - /** - * If {@code true} then this service has been initialized. - */ - private boolean initialized = false; - - /** - * tunable: the virtual messenger queue size - */ - private int vmQueueSize = DEFAULT_MESSAGE_QUEUE_SIZE; - - private PeerGroup group = null; - private ID assignedID = null; - private ModuleImplAdvertisement implAdvertisement = null; - - private String localPeerId = null; - private boolean useParentEndpoint = DEFAULT_USE_PARENT_ENDPOINT; - private EndpointService parentEndpoint = null; - private String myServiceName = null; - - /** - * The Message Transports which are registered for this endpoint. This is - * only the message transport registered locally, it does not include - * transports which are used from other groups. - */ - private final Collection messageTransports = new HashSet(); - - /** - * Passive listeners for messengers. Three priorities, so far. - */ - private final Collection[] passiveMessengerListeners = { - Collections.synchronizedList(new ArrayList()), - Collections.synchronizedList(new ArrayList()), - Collections.synchronizedList(new ArrayList()) - }; - - /** - * The set of listener managed by this instance of the endpoint svc. - */ - private final Map incomingMessageListeners = new HashMap(16); - - /** - * The set of shared transport messengers currently ready for use. - */ - private final Map> messengerMap = new WeakHashMap>(32); - /** - * The set of shared transport messengers currently ready for use. - */ - private final Map> directMessengerMap = new WeakHashMap>(32); - - /** - * The filter listeners. - *

      - * We rarely add/remove, never remove without iterating - * and insert objects that are always unique. So using a set - * does not make sense. An array list is the best. - */ - private final Collection incomingFilterListeners = new ArrayList(); - private final Collection outgoingFilterListeners = new ArrayList(); - - /** - * Holder for a filter listener and its conditions - */ - private static class FilterListenerAndMask { - final String namespace; - final String name; - final MessageFilterListener listener; - - public FilterListenerAndMask(MessageFilterListener listener, String namespace, String name) { - this.namespace = namespace; - this.name = name; - this.listener = listener; - } - - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof FilterListenerAndMask) { - FilterListenerAndMask likeMe = (FilterListenerAndMask) target; - - boolean result = (null != namespace) ? (namespace.equals(likeMe.namespace)) : (null == likeMe.namespace); - - result &= (null != name) ? (name.equals(likeMe.name)) : (null == likeMe.name); - result &= (listener == likeMe.listener); - - return result; - } - - return false; - } - - /** - * {@inheritDoc} - *

      - * Added to make PMD shut up.... - */ - @Override - public int hashCode() { - return System.identityHashCode(this); - } - } - - - /** - * A non blocking messenger that obtains a backing (possibly blocking) - * messenger on-demand. - */ - private class CanonicalMessenger extends ThreadedMessenger { - - /** - * If the hint was not used because there already was a transport - * messenger available, then it is saved here for the next time we are - * forced to create a new transport messenger by the breakage of the one - * that's here. - *

      - * The management of hints is a bit inconsistent for now: the hint - * used may be different dependent upon which invocation created the - * current canonical messenger and, although we try to use the hint only - * once (to avoid carrying an invalid hint forever) it may happen that a - * hint is used long after it was suggested. - */ - Object hint; - - /** - * The transport messenger that this canonical messenger currently uses. - */ - Messenger cachedMessenger = null; - - /** - * Create a new CanonicalMessenger. - * - * @param vmQueueSize queue size - * @param destination destination who messages should be addressed to - * @param logicalDestination logical destination - * @param hint route hint - * @param messengerMeter the metering object if any - */ - public CanonicalMessenger(int vmQueueSize, EndpointAddress destination, EndpointAddress logicalDestination, Object hint, OutboundMeter messengerMeter) { - super(group.getPeerGroupID(), destination, logicalDestination, vmQueueSize); - this.hint = hint; - } - - /** - * close this canonical messenger. - */ - @Override - public void close() { - // No way. Not form the outside. - } - - /** - * Drop the current messenger. - */ - @Override - protected void closeImpl() { - if (cachedMessenger != null) { - cachedMessenger.close(); - cachedMessenger = null; - } else { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Internal messenger error: close requested while not connected."); - } - } - } - - /** - * Get a transport messenger to the destination. - *

      - * FIXME 20040413 jice : Do better hint management. - */ - @Override - protected boolean connectImpl() { - if (cachedMessenger != null) { - if ((cachedMessenger.getState() & Messenger.TERMINAL) != 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.SEVERE)) { - LOG.fine("Closing TERMINAL internal messenger : attempting requested connect."); - } - cachedMessenger.close(); - cachedMessenger = null; - } else { - return true; - } - } - - // Consume the hint, if any. - Object theHint = hint; - - hint = null; - cachedMessenger = getLocalTransportMessenger(getDestinationAddress(), theHint); - - if (cachedMessenger == null) { - return false; - } - - // FIXME 20040413 jice : it's not too clean: we assume - // that all transports use BlockingMessenger as the base class for - // their messengers. If they don't we can't force them to hold the - // strong reference to the canonical messenger. - try { - ((BlockingMessenger) cachedMessenger).setOwner(this); - } catch (ClassCastException cce) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Transport messengers must all extend BlockingMessenger for now. " + - cachedMessenger + " may remain open beyond its use."); - } - } - return true; - } - - /** - * {@inheritDoc} - */ - @Override - protected EndpointAddress getLogicalDestinationImpl() { - if (cachedMessenger == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Internal messenger error: logical destination requested while not connected."); - } - return null; - } - return cachedMessenger.getLogicalDestinationAddress(); - } - - /** - * {@inheritDoc} - */ - @Override - protected void sendMessageBImpl(Message msg, String service, String param) throws IOException { - if (cachedMessenger == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Internal messenger error: send requested while not connected."); - } - throw new IOException("Internal messenger error."); - } - - try { - cachedMessenger.sendMessageB(msg, service, param); - } catch (IOException any) { - cachedMessenger = null; - throw any; - } catch (RuntimeException any) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure sending " + msg, any); - } - - throw any; - } - } - } - - /** - * Create a new EndpointService. - */ - public EndpointServiceImpl() { - } - - /** - * {@inheritDoc} - */ - public synchronized void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - if (initialized) { - throw new PeerGroupException("Cannot initialize service more than once"); - } - - this.group = group; - // The selector for the element of the peer adv params that we have to update. - this.assignedID = assignedID; - this.implAdvertisement = (ModuleImplAdvertisement) impl; - - this.localPeerId = group.getPeerID().toString(); - - this.myServiceName = ChannelMessenger.InsertedServicePrefix + group.getPeerGroupID().getUniqueValue().toString(); - - ConfigParams confAdv = group.getConfigAdvertisement(); - XMLElement paramBlock = null; - - if (confAdv != null) { - paramBlock = (XMLElement) confAdv.getServiceParam(assignedID); - } - - if (paramBlock != null) { - // get our two tunables: virtual messenger queue size, and whether to use the parent endpoint - Enumeration param; - - param = paramBlock.getChildren("MessengerQueueSize"); - if (param.hasMoreElements()) { - String textQSz = ((XMLElement) param.nextElement()).getTextValue(); - - try { - Integer requestedSize = Integer.parseInt(textQSz.trim()); - - if (requestedSize > 0) { - vmQueueSize = requestedSize; - } else { - LOG.warning("Illegal MessengerQueueSize : " + textQSz); - } - } catch (NumberFormatException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "could not parse MessengerQueueSize string", e); - } - } - } - - param = paramBlock.getChildren("UseParentEndpoint"); - if (param.hasMoreElements()) { - String textUPE = ((XMLElement) param.nextElement()).getTextValue(); - - useParentEndpoint = textUPE.trim().equalsIgnoreCase("true"); - } - - } - - PeerGroup parentGroup = group.getParentGroup(); - - if (useParentEndpoint && parentGroup != null) { - parentEndpoint = parentGroup.getEndpointService(); - parentEndpoint.addMessengerEventListener(this, EndpointService.LowPrecedence); - } - - initialized = true; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Endpoint Service : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: "); - configInfo.append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration :"); - if (null == parentGroup) { - configInfo.append("\n\t\tHome Group : (none)"); - } else { - configInfo.append("\n\t\tHome Group : ").append(parentGroup.getPeerGroupName()).append(" / ").append( - parentGroup.getPeerGroupID()); - } - configInfo.append("\n\t\tUsing home group endpoint : ").append(parentEndpoint); - configInfo.append("\n\t\tVirtual Messenger Queue Size : ").append(vmQueueSize); - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] args) { - if (!initialized) { - return -1; - } - - // FIXME when Load order Issue is resolved this should fail - // until it is able to get a non-failing service Monitor (or - // null = not monitoring) - // FIXME it is ok because of the hack in StdPeerGroup that starts - // endpoint service first - if (EndpointMeterBuildSettings.ENDPOINT_METERING) { // Fix-Me: Move to startApp() when load order issue is resolved - endpointServiceMonitor = (EndpointServiceMonitor) MonitorManager.getServiceMonitor(group, MonitorResources.endpointServiceMonitorClassID); - - if (endpointServiceMonitor != null) { - endpointMeter = endpointServiceMonitor.getEndpointMeter(); - } - } - - if (parentEndpoint != null) { - Iterator parentMTs = parentEndpoint.getAllMessageTransports(); - - synchronized (this) { - while (parentMTs.hasNext()) { - addProtoToAdv(parentMTs.next()); - } - } - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Endpoint Service started."); - } - - return Module.START_OK; - } - - /** - * {@inheritDoc} - *

      - * The transports and services are going to be stopped as well. When - * they are, they will dereference us and we'll go into oblivion. - */ - public void stopApp() { - if (parentEndpoint != null) { - parentEndpoint.removeMessengerEventListener(this, EndpointService.LowPrecedence); - } - - // Clear up the passiveMessengersListeners - int prec = EndpointService.HighPrecedence; - while (prec >= EndpointService.LowPrecedence) { - passiveMessengerListeners[prec--].clear(); - } - - // Clear up any messengers. - messengerMap.clear(); - directMessengerMap.clear(); - - // Clear up the listeners - incomingMessageListeners.clear(); - - // Forget about any message filters. - incomingFilterListeners.clear(); - outgoingFilterListeners.clear(); - - // Forget any message transports - messageTransports.clear(); - - // Avoid cross-reference problems with the GC - - // group = null; - // parentEndpoint = null; - // parentGroup = null; - - // The above is not really needed and until we have a very orderly - // shutdown, it causes NPEs that are hard to prevent. - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Endpoint Service stopped."); - } - } - - /** - * {@inheritDoc} - */ - public PeerGroup getGroup() { - return group; - } - - /** - * {@inheritDoc} - *

      - * We create a new instance each time because our interface actually - * has state (channel messengers and listener callback adaptor). - */ - public EndpointService getInterface() { - return new EndpointServiceInterface(this); - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return implAdvertisement; - } - - // A vector for statistics between propagateThroughAll and its invoker. - private static class Metrics { - int numFilteredOut = 0; - int numPropagatedTo = 0; - int numErrorsPropagated = 0; - } - - private void propagateThroughAll(Iterator eachProto, Message myMsg, String serviceName, String serviceParam, int initialTTL, Metrics metrics) { - - Message filtered = null; - - while (eachProto.hasNext()) { - MessageTransport aTransport = eachProto.next(); - - try { - if (!(aTransport instanceof MessagePropagater)) { - continue; - } - - MessagePropagater propagater = (MessagePropagater) aTransport; - - if (null == filtered) { - // run process filters only once - filtered = processFilters(myMsg, - propagater.getPublicAddress(), - new EndpointAddress(group.getPeerGroupID(), serviceName, serviceParam), - false); - } - - if (null == filtered) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(" message " + myMsg + " discarded upon filter decision"); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING) { - metrics.numFilteredOut++; - } - break; - } - - propagater.propagate(filtered.clone(), serviceName, serviceParam, initialTTL); - - if (EndpointMeterBuildSettings.ENDPOINT_METERING) { - metrics.numPropagatedTo++; - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed propagating message " + filtered + " on message transport " + aTransport, e); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING) { - metrics.numErrorsPropagated++; - } - } - } - } - - /** - * {@inheritDoc} - */ - public void propagate(Message msg, String serviceName, String serviceParam) { - propagate(msg, serviceName, serviceParam, Integer.MAX_VALUE); - } - - /** - * {@inheritDoc} - */ - public void propagate(Message msg, String serviceName, String serviceParam, int initialTTL) { - long startPropagationTime = 0; - - if (null == serviceName) { - throw new IllegalArgumentException("serviceName may not be null"); - } - - Metrics metrics = null; - - if (EndpointMeterBuildSettings.ENDPOINT_METERING) { - metrics = new Metrics(); - } - - // Keep the orig unchanged for metering reference and caller's benefit, but - // we are forced to clone it here, because we add a header. - msg = msg.clone(); - - if (EndpointMeterBuildSettings.ENDPOINT_METERING) { - startPropagationTime = System.currentTimeMillis(); - } - - // Add our header. - MessageElement srcHdrElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_SRCPEERHDR_NAME, localPeerId, null); - - msg.replaceMessageElement(EndpointServiceImpl.MESSAGE_SRCPEERHDR_NS, srcHdrElement); - - // Do the local transports with the plain address. - Iterator eachProto = getAllLocalTransports(); - - propagateThroughAll(eachProto, msg.clone(), serviceName, serviceParam, initialTTL, metrics); - - // Do the parent transports with a mangled address. - if (parentEndpoint != null) { - eachProto = parentEndpoint.getAllMessageTransports(); - - StringBuilder mangled = new StringBuilder(serviceName); - if (null != serviceParam) { - mangled.append('/'); - mangled.append(serviceParam); - } - - propagateThroughAll(eachProto, msg.clone(), myServiceName, mangled.toString(), initialTTL, metrics); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointServiceMonitor != null)) { - PropagationMeter propagationMeter = endpointServiceMonitor.getPropagationMeter(serviceName, serviceParam); - - propagationMeter.registerPropagateMessageStats(metrics.numPropagatedTo, metrics.numFilteredOut, metrics.numErrorsPropagated, - System.currentTimeMillis() - startPropagationTime); - } - } - - /** - * Process the filters for this message. - */ - private Message processFilters(Message message, EndpointAddress srcAddress, EndpointAddress dstAddress, boolean incoming) { - - Iterator eachFilter = incoming - ? incomingFilterListeners.iterator() - : outgoingFilterListeners.iterator(); - - while (eachFilter.hasNext()) { - FilterListenerAndMask aFilter = eachFilter.next(); - - Message.ElementIterator eachElement = message.getMessageElements(); - - while (eachElement.hasNext()) { - MessageElement anElement = eachElement.next(); - - if ((null != aFilter.namespace) && (!aFilter.namespace.equals(eachElement.getNamespace()))) { - continue; - } - - if ((null != aFilter.name) && (!aFilter.name.equals(anElement.getElementName()))) { - continue; - } - - message = aFilter.listener.filterMessage(message, srcAddress, dstAddress); - - if (null == message) { - return null; - } - } - } - - // If we got here, no filter has rejected the message. Keep processing it. - return message; - } - - private static EndpointAddress demangleAddress(EndpointAddress mangled) { - String serviceName = mangled.getServiceName(); - - if (null == serviceName) { - // not a mangled address - return mangled; - } - - if (!serviceName.startsWith(ChannelMessenger.InsertedServicePrefix)) { - // not a mangled address - return mangled; - } - - String serviceParam = mangled.getServiceParameter(); - - if (null == serviceParam) { - // it has no param, its a null destination. - // XXX bondolo 20050907 I'm not sure this is correct. - return new EndpointAddress(mangled, null, null); - } - - int slashAt = serviceParam.indexOf('/'); - - if (-1 == slashAt) { - // param has no param portion. - return new EndpointAddress(mangled, serviceParam, null); - } - - return new EndpointAddress(mangled, serviceParam.substring(0, slashAt), serviceParam.substring(slashAt + 1)); - } - - /** - * {@inheritDoc} - */ - public void processIncomingMessage(Message msg, EndpointAddress srcAddress, EndpointAddress dstAddress) { - - // check for propagate loopback. - MessageElement srcPeerElement = msg.getMessageElement(EndpointServiceImpl.MESSAGE_SRCPEERHDR_NS, EndpointServiceImpl.MESSAGE_SRCPEERHDR_NAME); - - if (null != srcPeerElement) { - msg.removeMessageElement(srcPeerElement); - String srcPeer = srcPeerElement.toString(); - - if (localPeerId.equals(srcPeer)) { - // This is a loopback. Discard. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(msg + " is a propagate loopback. Discarded"); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.discardedLoopbackDemuxMessage(); - } - - return; - } - } - - if (null == srcAddress) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("null src address, discarding message " + msg); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.invalidIncomingMessage(); - } - - return; - } - - if (null == dstAddress) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("null destination address, discarding message " + msg); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.invalidIncomingMessage(); - } - - return; - } - - // Decode the destination address. - // We want: - // 1 - a version of the address that does not have the grp redirection. - // 2 - a version of the serviceName that includes BOTH the group redirection and the original service name. - // 3 - the original service param; without the original service name stuck to it. - // So, basically we want the original serviceName part stuck to the group mangling, not stuck to the original - // serviceParam. We do that by cut/pasting from both the mangled and demangled versions of the address. - - EndpointAddress demangledAddress = demangleAddress(dstAddress); - String decodedServiceName = demangledAddress.getServiceName(); - String decodedServiceParam = demangledAddress.getServiceParameter(); - - if ((null == decodedServiceName) || (0 == decodedServiceName.length())) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("dest serviceName must not be null, discarding message " + msg); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.invalidIncomingMessage(); - } - - return; - } - - // Do filters for this message: - // FIXME - jice 20040417 : filters are likely broken, now. They do not see messages - // from xports in parent groups. For those messages that are seen, demangled address seems to be the useful one. - msg = processFilters(msg, srcAddress, demangledAddress, true); - - // If processFilters retuns null, the message is to be discarded. - if (msg == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Message discarded during filter processing"); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.incomingMessageFilteredOut(); - } - - return; - } - - // Now that we know the original service name is valid, finish building the decoded version. - if (demangledAddress != dstAddress) { - decodedServiceName = dstAddress.getServiceName() + "/" + decodedServiceName; - } - - // Look up the listener - EndpointListener listener = getIncomingMessageListener(decodedServiceName, decodedServiceParam); - - // No listener? oh well. - - if (listener == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("No listener for \'" + dstAddress + "\' in group " + - group + "\n\tdecodedServiceName :" + - decodedServiceName + "\tdecodedServiceParam :" + - decodedServiceParam); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.noListenerForIncomingMessage(); - } - - return; // noone cares for this message - } - - // call the listener - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - if (null != decodedServiceParam) { - LOG.fine("Calling listener for \'" + decodedServiceName + "/" + decodedServiceParam + "\' with " + msg); - } else { - LOG.fine("Calling listener for \'" + decodedServiceName + "\' with " + msg); - } - } - - listener.processIncomingMessage(msg, srcAddress, demangledAddress); - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.incomingMessageSentToEndpointListener(); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.demuxMessageProcessed(); - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught throwable from listener for " + dstAddress, all); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.errorProcessingIncomingMessage(); - } - } - } - - /** - * {@inheritDoc} - */ - public void demux(Message msg) { - - // Get the message destination - MessageElement dstAddressElement = msg.getMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NS, - EndpointServiceImpl.MESSAGE_DESTINATION_NAME); - - if (null == dstAddressElement) { - // No destination address... Just discard - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning(msg + " has no destination address. Discarded"); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.noDestinationAddressForDemuxMessage(); - } - - return; - } - - msg.removeMessageElement(dstAddressElement); - EndpointAddress dstAddress = new EndpointAddress(dstAddressElement.toString()); - - // Get the message source - MessageElement srcAddressElement = msg.getMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NS, EndpointServiceImpl.MESSAGE_SOURCE_NAME); - - if (null == srcAddressElement) { - // No src address... Just discard - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning(msg + " has no source address. Discarded"); - } - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointMeter != null)) { - endpointMeter.noSourceAddressForDemuxMessage(); - } - - return; - } - - msg.removeMessageElement(srcAddressElement); - EndpointAddress msgScrAddress = new EndpointAddress(srcAddressElement.toString()); - - processIncomingMessage(msg, msgScrAddress, dstAddress); - } - - /** - * {@inheritDoc} - */ - public MessengerEventListener addMessageTransport(MessageTransport transpt) { - - synchronized (messageTransports) { - // check if it is already installed. - if (!messageTransports.contains(transpt)) { - - clearProtoFromAdv(transpt); // just to be safe - messageTransports.add(transpt); - addProtoToAdv(transpt); - - // FIXME: For now, we return this. Later we might return something else, so that we can take - // advantage of the fact that we know that the event is from a local transport. - // That will help cleaning up the incoming messenger mess. - return this; - } - } - - return null; - } - - /** - * {@inheritDoc} - */ - public boolean removeMessageTransport(MessageTransport transpt) { - - boolean removed; - - synchronized (messageTransports) { - removed = messageTransports.remove(transpt); - } - - if (removed) { - clearProtoFromAdv(transpt); - } - - return removed; - } - - /** - * {@inheritDoc} - */ - public Iterator getAllMessageTransports() { - if (null != parentEndpoint) { - return new SequenceIterator(getAllLocalTransports(), parentEndpoint.getAllMessageTransports()); - } else { - return getAllLocalTransports(); - } - } - - /** - * {@inheritDoc} - */ - public MessageTransport getMessageTransport(String name) { - Iterator allTransports = getAllMessageTransports(); - - while (allTransports.hasNext()) { - MessageTransport transpt = allTransports.next(); - - if (transpt.getProtocolName().equals(name)) { - return transpt; - } - } - - return null; - } - - private void addProtoToAdv(MessageTransport proto) { - - boolean relay = false; - - try { - if (!(proto instanceof MessageReceiver)) { - return; - } - - // no value to publish for the router endpoint address - if (proto instanceof EndpointRouter) { - // register the corresponding group to relay connection events - addActiveRelayListener(group); - return; - } - - // register this group to Relay connection events - if (proto instanceof RelayClient) { - relay = true; - ((RelayClient) proto).addActiveRelayListener(group); - } - - // get the list of addresses - Iterator allAddresses = ((MessageReceiver) proto).getPublicAddresses(); - Vector ea = new Vector(); - - while (allAddresses.hasNext()) { - EndpointAddress anEndpointAddress = allAddresses.next(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Adding endpoint address to route advertisement : " + anEndpointAddress); - } - - ea.add(anEndpointAddress.toString()); - } - - PeerAdvertisement padv = group.getPeerAdvertisement(); - StructuredDocument myParam = padv.getServiceParam(assignedID); - - RouteAdvertisement route = null; - - if (myParam != null) { - Enumeration paramChilds = myParam.getChildren(RouteAdvertisement.getAdvertisementType()); - - if (paramChilds.hasMoreElements()) { - // we have an advertisement just add the new access points - XMLElement param = (XMLElement) paramChilds.nextElement(); - - route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(param); - route.addDestEndpointAddresses(ea); - if (relay) { - // need to add the relay info if we have some - Vector hops = ((RelayClient) proto).getActiveRelays(group); - - if (!hops.isEmpty()) { - route.setHops(hops); - } - } - } - } - - if (null == route) { - // None yet, so create a new Route Advertisement - // create the RouteAdvertisement that will contain the route to - // the peer. At this point we only know the peer endpoint addresses - // no hops are known - - // create the destination access point - AccessPointAdvertisement destAP = (AccessPointAdvertisement) AdvertisementFactory.newAdvertisement( - AccessPointAdvertisement.getAdvertisementType()); - - destAP.setPeerID(group.getPeerID()); - destAP.setEndpointAddresses(ea); - - // create the route advertisement - route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - route.setDest(destAP); - - if (relay) { - // need to add the relay info if we have some - Vector hops = ((RelayClient) proto).getActiveRelays(group); - - if (!hops.isEmpty()) { - route.setHops(hops); - } - } - } - - // create the param route - XMLDocument newParam = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - XMLDocument xptDoc = (XMLDocument) route.getDocument(MimeMediaType.XMLUTF8); - - StructuredDocumentUtils.copyElements(newParam, newParam, xptDoc); - - padv.putServiceParam(assignedID, newParam); - - // publish the new advertisement - DiscoveryService discovery = group.getDiscoveryService(); - - if (discovery != null) { - discovery.publish(padv, DiscoveryService.INFINITE_LIFETIME, DiscoveryService.DEFAULT_EXPIRATION); - } - } catch (Exception ex) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Exception adding message transport ", ex); - } - } - } - - private void clearProtoFromAdv(MessageTransport transpt) { - - try { - if (!(transpt instanceof MessageReceiver)) { - return; - } - - // no value to publish the router endpoint address - if (transpt instanceof EndpointRouter) { - // register the corresponding group in the relay - removeActiveRelayListener(group); - return; - } - - // register this group to Relay connection events - if (transpt instanceof RelayClient) { - ((RelayClient) transpt).removeActiveRelayListener(group); - } - - Iterator allAddresses = ((MessageReceiver) transpt).getPublicAddresses(); - Vector ea = new Vector(); - - while (allAddresses.hasNext()) { - EndpointAddress anEndpointAddress = allAddresses.next(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing endpoint address from route advertisement : " + anEndpointAddress); - } - - ea.add(anEndpointAddress.toString()); - } - - PeerAdvertisement padv = group.getPeerAdvertisement(); - XMLDocument myParam = (XMLDocument) padv.getServiceParam(assignedID); - - if (myParam == null) { - return; - } - - Enumeration paramChilds = myParam.getChildren(RouteAdvertisement.getAdvertisementType()); - - if (!paramChilds.hasMoreElements()) { - return; - } - - XMLElement param = (XMLElement) paramChilds.nextElement(); - - RouteAdvertisement route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(param); - - route.removeDestEndpointAddresses(ea); - - // update the new route to a new parm structure. - XMLDocument newParam = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - - XMLDocument xptDoc = (XMLDocument) route.getDocument(MimeMediaType.XMLUTF8); - - StructuredDocumentUtils.copyElements(newParam, newParam, xptDoc); - - // put the parms back. - padv.putServiceParam(assignedID, newParam); - - // publish the new advertisement - DiscoveryService discovery = group.getDiscoveryService(); - - if (discovery != null) { - discovery.publish(padv, DiscoveryService.INFINITE_LIFETIME, DiscoveryService.DEFAULT_EXPIRATION); - } - } catch (Exception ex) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Exception removing messsage transport ", ex); - } - } - } - - /** - * {@inheritDoc} - */ - public boolean addMessengerEventListener(MessengerEventListener listener, int prio) { - int priority = prio; - - if (priority > EndpointService.HighPrecedence) { - priority = EndpointService.HighPrecedence; - } - - if (priority < EndpointService.LowPrecedence) { - priority = EndpointService.LowPrecedence; - } - - return passiveMessengerListeners[priority].add(listener); - } - - /** - * {@inheritDoc} - */ - public boolean removeMessengerEventListener(MessengerEventListener listener, int prio) { - int priority = prio; - - if (priority > EndpointService.HighPrecedence) { - priority = EndpointService.HighPrecedence; - } - if (priority < EndpointService.LowPrecedence) { - priority = EndpointService.LowPrecedence; - } - - return passiveMessengerListeners[priority].remove(listener); - } - - /** - * {@inheritDoc} - */ - public boolean addIncomingMessageListener(EndpointListener listener, String serviceName, String serviceParam) { - - if (null == listener) { - throw new IllegalArgumentException("EndpointListener must be non-null"); - } - - if (null == serviceName) { - throw new IllegalArgumentException("serviceName must not be null"); - } - - if (-1 != serviceName.indexOf('/')) { - throw new IllegalArgumentException("serviceName may not contain '/' characters"); - } - - String address = serviceName; - - if (null != serviceParam) { - address += "/" + serviceParam; - } - - synchronized (incomingMessageListeners) { - if (incomingMessageListeners.containsKey(address)) { - return false; - } - - InboundMeter incomingMessageListenerMeter = null; - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointServiceMonitor != null)) { - incomingMessageListenerMeter = endpointServiceMonitor.getInboundMeter(serviceName, serviceParam); - } - - incomingMessageListeners.put(address, listener); - } - - if (parentEndpoint != null) { - if (serviceName.startsWith(ChannelMessenger.InsertedServicePrefix)) { - // The listener name is already re-written. - // The listener is already a quota listener; we made extra sure of that before tucking it into our local map. - parentEndpoint.addIncomingMessageListener(listener, serviceName, serviceParam); - } else { - parentEndpoint.addIncomingMessageListener(listener, myServiceName, address); - } - } - - return true; - } - - /** - * {@inheritDoc} - */ - public EndpointListener getIncomingMessageListener(String serviceName, String serviceParam) { - - if (null == serviceName) { - throw new IllegalArgumentException("serviceName must not be null"); - } - - EndpointListener listener = null; - - if (null != serviceParam) { - listener = incomingMessageListeners.get(serviceName + "/" + serviceParam); - } - - // Didn't find it with param, maybe there is a generic listener for the service - if (listener == null) { - listener = incomingMessageListeners.get(serviceName); - } - - // Didn't find it still, try the compatibility name. - if (listener == null) { - listener = incomingMessageListeners.get(serviceName + serviceParam); - - if ((null != listener) && Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Found handler only via compatibility listener : " + serviceName + serviceParam); - } - } - - return listener; - } - - /** - * {@inheritDoc} - */ - public EndpointListener removeIncomingMessageListener(String serviceName, String serviceParam) { - if (null == serviceName) { - throw new IllegalArgumentException("serviceName must not be null"); - } - - if (-1 != serviceName.indexOf('/')) { - throw new IllegalArgumentException("serviceName may not contain '/' characters"); - } - - String address = serviceName; - - if (null != serviceParam) { - address += "/" + serviceParam; - } - - EndpointListener removedListener; - synchronized (incomingMessageListeners) { - removedListener = incomingMessageListeners.remove(address); - } - - if (parentEndpoint != null) { - if (serviceName.startsWith(ChannelMessenger.InsertedServicePrefix)) { - parentEndpoint.removeIncomingMessageListener(serviceName, serviceParam); - } else { - parentEndpoint.removeIncomingMessageListener(myServiceName, address); - } - } - return removedListener; - } - - /** - * Returns a local transport that can send to the given address. For now - * this is based only on the protocol name. - * - * @param addr the endpoint address - * @return the transport if the address protocol is supported by this transport - */ - private MessageSender getLocalSenderForAddress(EndpointAddress addr) { - - Iterator localTransports = getAllLocalTransports(); - - while (localTransports.hasNext()) { - MessageTransport transpt = localTransports.next(); - if (!transpt.getProtocolName().equals(addr.getProtocolName())) { - continue; - } - - if (!(transpt instanceof MessageSender)) { - continue; - } - - return (MessageSender) transpt; - } - return null; - } - - /** - * {@inheritDoc} - *

      - * Note: canonical messenger itself does not do any address rewriting. - * Any address rewriting must be specified when getting a channel. However, - * canonical knows the default group redirection for its owning endpoint and - * will automatically skip redirection if it is the same. - */ - - public Messenger getCanonicalMessenger(EndpointAddress addr, Object hint) { - if (addr == null) { - throw new IllegalArgumentException("null endpoint address not allowed."); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - Throwable trace = new Throwable("Stack Trace"); - StackTraceElement elements[] = trace.getStackTrace(); - - int position = 1; - - while (elements[position].getClassName().startsWith("net.jxta.impl.endpoint.EndpointService")) { - position++; - } - - if ((elements.length - 1) == position) { - position--; - } - - LOG.fine("Get Messenger for " + addr + " by " + elements[position]); - } - - // Check the canonical map. - synchronized (messengerMap) { - Reference ref = messengerMap.get(addr); - - if (ref != null) { - Messenger found = ref.get(); - - // If it is USABLE, return it. - if ((found != null) && ((found.getState() & Messenger.USABLE) != 0)) { - return found; - } - - // It has been GCed or is no longer USABLE. Make room for a new one. - messengerMap.remove(addr); - } - - if (getLocalSenderForAddress(addr) != null) { - OutboundMeter messengerMeter = null; - - if (EndpointMeterBuildSettings.ENDPOINT_METERING && (endpointServiceMonitor != null)) { - messengerMeter = endpointServiceMonitor.getOutboundMeter(addr); - } - - // The hint is saved in the canonical messenger and will be used - // when that virtual messenger first faces the need to create a - // transport messenger. As of now, the logical dest is unknown. - Messenger m = new CanonicalMessenger(vmQueueSize, addr, null, hint, messengerMeter); - - messengerMap.put(m.getDestinationAddress(), new SoftReference(m)); - return m; - } - } - - // If we're here, we do not have any such transport. - // Try our ancestors enpoints, if any. - - if (parentEndpoint == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Could not create messenger for : " + addr); - } - return null; - } - - return parentEndpoint.getCanonicalMessenger(addr, hint); - } - - /** - * Return only the message transport registered locally. - */ - protected Iterator getAllLocalTransports() { - List transportList; - - synchronized (messageTransports) { - transportList = new ArrayList(messageTransports); - } - - return transportList.iterator(); - } - - /** - * Returns a messenger for the specified address from one of the Message - * Transports registered with this very endpoint service. Message - * Transports inherited from parent groups will not be used. - * - * @param addr The destination address of the desired Messenger. - * @param hint A hint provided to the Message Transport which may assist it - * in creating the messenger. - * @return A Messenger for the specified destination address or {@code null} - * if no Messenger could be created. - */ - private Messenger getLocalTransportMessenger(EndpointAddress addr, Object hint) { - MessageSender sender = getLocalSenderForAddress(addr); - Messenger messenger = null; - - if (sender != null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Trying address \'" + addr + "\' with : " + sender); - } - messenger = sender.getMessenger(addr, hint); - } - - if (messenger == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Couldn\'t create messenger for : " + addr); - } - } - return messenger; - } - - /** - * {@inheritDoc} - */ - public synchronized void addIncomingMessageFilterListener(MessageFilterListener listener, String namespace, String name) { - if (null == listener) { - throw new IllegalArgumentException("listener must be non-null"); - } - - FilterListenerAndMask aFilter = new FilterListenerAndMask(listener, namespace, name); - - incomingFilterListeners.add(aFilter); - } - - /** - * {@inheritDoc} - */ - public synchronized void addOutgoingMessageFilterListener(MessageFilterListener listener, String namespace, String name) { - if (null == listener) { - throw new IllegalArgumentException("listener must be non-null"); - } - - FilterListenerAndMask aFilter = new FilterListenerAndMask(listener, namespace, name); - - outgoingFilterListeners.add(aFilter); - } - - /** - * {@inheritDoc} - */ - public synchronized MessageFilterListener removeIncomingMessageFilterListener(MessageFilterListener listener, String namespace, String name) { - Iterator eachListener = incomingFilterListeners.iterator(); - - while (eachListener.hasNext()) { - FilterListenerAndMask aFilter = eachListener.next(); - - if (listener == aFilter.listener) { - eachListener.remove(); - return listener; - } - } - - return null; - } - - /** - * {@inheritDoc} - */ - public synchronized MessageFilterListener removeOutgoingMessageFilterListener(MessageFilterListener listener, String namespace, String name) { - Iterator eachListener = outgoingFilterListeners.iterator(); - - while (eachListener.hasNext()) { - FilterListenerAndMask aFilter = eachListener.next(); - - if ((listener == aFilter.listener) - && ((null != namespace) ? namespace.equals(aFilter.namespace) : (null == aFilter.namespace)) - && ((null != name) ? name.equals(aFilter.name) : (null == aFilter.name))) { - eachListener.remove(); - return listener; - } - } - - return null; - } - - /** - * {@inheritDoc} - * - *

      Redistribute the event to those interested. - */ - public boolean messengerReady(MessengerEvent event) { - - // FIXME - jice@jxta.org 20040413: now that we share messengers, we - // should be able to get rid of most of this mess, and in the router, - // and the relay too. - - Messenger messenger = event.getMessenger(); - Messenger messengerForHere; - EndpointAddress connAddr = event.getConnectionAddress(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("New " + messenger + " for : " + - messenger.getDestinationAddress() + " (" + - messenger.getLogicalDestinationAddress() + ")"); - } - - int highestPrec = EndpointService.HighPrecedence; - int lowestPrec = EndpointService.LowPrecedence; - - // If there's no connection address we just pass the messenger around - // everywhere; it is unspecified which group it is for. - // Else, we must figure out if it is for this group, or must be - // passed upStack (if any). - if (connAddr != null) { - String cgServiceName = connAddr.getServiceName(); - - // See if there is a mangling. If not, this means this was sent - // within this group through a local xport, so it is for here. Else - // it may be for here (from below) or for upstack. - - if (cgServiceName == null || !cgServiceName.startsWith(ChannelMessenger.InsertedServicePrefix)) { - // FIXME: jice@jxta.org - 20030512 If we restrict use to "here" - // we make most backchannels useless. So, the statement below is - // commented out. Ideally we should not have to worry about the - // group targetting of connections, only messages. However the - // way the relay and the router have to split messengers makes - // it necessary. This may only be fixed by re-organizing - // globally the management of incoming messengers in the - // endpoint, so that router and relay no-longer need to claim - // exclusive use of messengers. Since relay clients set the - // group properly, their messengers are not affected by this - // branch of the code. - // lowestPrec = EndpointService.LowPrecedence + 1; - } else if (!myServiceName.equals(cgServiceName)) { - // This is for upstack only - highestPrec = EndpointService.LowPrecedence; - } else { - // Mangling present and this is for here (and therefore this is - // from below). We must demangle. Wrapping is figured later, - // since we may also have to wrap if there the - lowestPrec = EndpointService.LowPrecedence + 1; - - String serviceParam = connAddr.getServiceParameter(); - String realService = null; - String realParam = null; - - if (null != serviceParam) { - int slashAt = serviceParam.indexOf('/'); - - if (-1 == slashAt) { - realService = serviceParam; - } else { - realService = serviceParam.substring(0, slashAt); - realParam = serviceParam.substring(slashAt + 1); - } - } - - connAddr = new EndpointAddress(connAddr, realService, realParam); - } - } - - // We make a channel in all cases, the channel will decide if the desired grp redirection - // requires address rewriting or not. - - // As for a MessageWatcher for implementing sendMessage-with-listener, we do not provide one - // mostly because it is difficult to get a hold on the only appropriate one: that of the endpoint - // service interface of the listener's owner. So, incoming messengers will not support the listener-based send API. - // Unless someone adds a watcher by hand. - messengerForHere = event.getMessenger().getChannelMessenger(group.getPeerGroupID(), null, null); - - // Call the listener highest precedence first. The first one that claims - // the messenger wins. - for (int prec = highestPrec + 1; prec-- > lowestPrec;) { - MessengerEvent newMessenger = new MessengerEvent(event.getSource(), - prec == EndpointService.LowPrecedence ? messenger : messengerForHere, connAddr); - - // We need to grab the listeners and release the lock. Otherwise the - // sometimes too long operations performed by the listener creates - // an unnecessary contention. - // The side effect is that a listener can in theory be called after - // remove returned. It is unlikely to be a problem for messenger - // events, but if it is, then we'll have to add reader-writer synch. - Collection allML = new ArrayList(passiveMessengerListeners[prec]); - for (MessengerEventListener listener : allML) { - try { - if (listener.messengerReady(newMessenger)) { - // A listener has taken the messenger. we're done. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(newMessenger + " claimed by " + listener); - } - return true; - } - } catch (Throwable all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught Throwable in listener " + listener, all); - } - } - } - } - - // Note that the messenger was not wanted. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Nobody cared about " + event); - } - return false; - } - - // public MessengerEventListener getMessengerEventListener() { - // return this; - // } - - // try to find the relay service in our - // hierachy of endpoints to register our listener group - // since the group has to register into the relay service. This is not - // very pretty, but the other way was even worth to register the relay - // into the endpoint! - - private void addActiveRelayListener(PeerGroup listeningGroup) { - PeerGroup parentGroup = group.getParentGroup(); - while (parentGroup != null) { - EndpointService parentEndpoint = parentGroup.getEndpointService(); - - for (Iterator it = parentEndpoint.getAllMessageTransports(); it.hasNext();) { - MessageTransport mt = it.next(); - - if ((mt instanceof RelayClient)) { - ((RelayClient) mt).addActiveRelayListener(listeningGroup); - break; - } - } - parentGroup = parentGroup.getParentGroup(); - } - } - - // try to find the relay service in our - // hierachy of endpoints to unregister our listener group - private void removeActiveRelayListener(PeerGroup listeningGroup) { - PeerGroup parentGroup = group.getParentGroup(); - - while (parentGroup != null) { - EndpointService parentEndpoint = parentGroup.getEndpointService(); - - for (Iterator it = parentEndpoint.getAllMessageTransports(); it.hasNext();) { - MessageTransport mt = it.next(); - - if ((mt instanceof RelayClient)) { - ((RelayClient) mt).removeActiveRelayListener(listeningGroup); - break; - } - } - parentGroup = parentGroup.getParentGroup(); - } - } - - /* - * Convenience legacy methods. They are here to reduce the complexity of the class hierarchy but are not supposed to be used. - */ - - /** - * {@inheritDoc} - * - * @deprecated legacy method. - */ - @Deprecated - public boolean ping(EndpointAddress addr) { - throw new UnsupportedOperationException("Legacy method not implemented. Use an interface object."); - } - - /** - * {@inheritDoc} - * - * @deprecated legacy method. - */ - @Deprecated - public boolean getMessenger(MessengerEventListener listener, EndpointAddress addr, Object hint) { - throw new UnsupportedOperationException("Legacy method not implemented. Use an interface object."); - } - - /** - * {@inheritDoc} - *

      - * convenience method not supported here. - */ - public Messenger getMessenger(EndpointAddress addr) { - throw new UnsupportedOperationException("Convenience method not implemented. Use an interface object."); - } - - /** - * {@inheritDoc} - *

      - * convenience method not supported here. - */ - public Messenger getMessengerImmediate(EndpointAddress addr, Object hint) { - throw new UnsupportedOperationException("Convenience method not implemented. Use an interface object."); - } - - /** - * {@inheritDoc} - *

      - * convenience method not supported here. - */ - public Messenger getMessenger(EndpointAddress addr, Object hint) { - throw new UnsupportedOperationException("Convenience method not implemented. Use an interface object."); - } - - /** - * Returns a Direct Messenger that may be used to send messages via this endpoint - * to the specified destination. - * - * @param address the destination address. - * @param hint the messenger hint, if any, otherwise null. - * @param exclusive if true avoids caching the messenger - * @return The messenger or {@code null} is returned if the destination address is not reachable. - * @throws IllegalArgumentException if hint is not of RouteAdvertisement, or PeerAdvertisement type. - */ - public Messenger getDirectMessenger(EndpointAddress address, Object hint, boolean exclusive) { - - if (!exclusive) { - Reference reference = directMessengerMap.get(address); - if (reference != null) { - Messenger messenger = reference.get(); - if (messenger != null && !messenger.isClosed()) { - return messenger; - } - } - } - - // We must have access to a TCP transport to create a direct messenger. - TcpTransport tcpTransport = (TcpTransport) getMessageTransport("tcp"); - - if ((tcpTransport != null) && (hint != null)) { - RouteAdvertisement route; - EndpointAddress direct; - Messenger messenger; - if (hint instanceof RouteAdvertisement) { - route = (RouteAdvertisement) hint; - } else if (hint instanceof PeerAdvertisement) { - route = EndpointUtils.extractRouteAdv((PeerAdvertisement) hint); - } else { - throw new IllegalArgumentException("Unknown route hint object type" + hint); - } - - for (EndpointAddress transportAddr : route.getDestEndpointAddresses()) { - if (transportAddr.getProtocolName().equals("tcp")) { - direct = createDirectAddress(transportAddr, address); - // direct messengers are non self destructive - messenger = tcpTransport.getMessenger(direct, route, false); - if (messenger != null) { - if (!exclusive) { - directMessengerMap.put(address, new WeakReference(messenger)); - } - return messenger; - } - } - } - } - - return null; - } - - /** - * Given a transport address and service address, create a mangled endpoint address - * - * @param transportAddr the transport messenger address - * @param serviceEndpoint the service endpoint - * @return an composite endpoint address - */ - private EndpointAddress createDirectAddress(EndpointAddress transportAddr, EndpointAddress serviceEndpoint) { - //physical transport address - StringBuilder destStr = new StringBuilder(transportAddr.toString()).append("/"); - // EndpointService - destStr.append(ENDPOINTSERVICE_NAME); - //Dest peergroup - destStr.append(":").append(group.getPeerGroupID().getUniqueValue().toString()).append("/"); - //Service endpoint - destStr.append(serviceEndpoint.getServiceName()).append("/").append(serviceEndpoint.getServiceParameter()); - - //return new EndpointAddress(transportAddr, serviceEndpoint.getServiceName(), serviceEndpoint.getServiceParameter()); - return new EndpointAddress(destStr.toString()); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/EndpointServiceInterface.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/EndpointServiceInterface.java deleted file mode 100644 index 8cc33d7f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/EndpointServiceInterface.java +++ /dev/null @@ -1,494 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint; - -import net.jxta.document.Advertisement; -import net.jxta.endpoint.ChannelMessenger; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.ListenerAdaptor; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageFilterListener; -import net.jxta.endpoint.MessageTransport; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.MessengerEventListener; -import net.jxta.id.ID; -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.peergroup.StdPeerGroup; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.ModuleImplAdvertisement; - -import java.lang.ref.Reference; -import java.lang.ref.WeakReference; -import java.util.Iterator; -import java.util.Map; -import java.util.WeakHashMap; - -import net.jxta.platform.Module; - -/** - * Provides an interface object appropriate for applications using the endpoint - * service. The interface provides a number of convenience features and - * implementation necessary for legacy features. - */ -class EndpointServiceInterface implements EndpointService { - - /** - * The service interface that we will be fronting. - */ - private final EndpointServiceImpl theRealThing; - - /** - * The number of active instances of this class. We use this for deciding - * when to instantiate and shutdown the listener adaptor. - */ - private static int activeInstanceCount = 0; - - /** - * Provides emulation of the legacy send-message-with-listener and get-messenger-with-listener APIs. - */ - private static ListenerAdaptor listenerAdaptor; - - /** - * The cache of channels. If a given owner of this EndpointService interface - * object requests channels for the same exact destination multiple times, - * we will return the same channel object as much as possible. We keep - * channels in a weak map, so that when channels are discarded, they - * eventually disappear. Channels that have messages in them are always - * referenced. Therefore, this prevents the creation of more than one - * channel with messages in it for the same destination in the same context - * (owner of interface object - typically one module). This is required to - * properly support the common (and convenient) pattern: - *

      - * m = endpointServiceInterface.getMessenger(); messenger.sendMessage(); m = null; - *

      - * If that was not kept in check, it would be possible to inadvertently - * create an infinite number of channels with pending messages, thus an - * infinite number of messages too. - */ - private final Map> channelCache = new WeakHashMap>(); - - /** - * Builds a new interface object. - * - * @param endpointService the endpoint service that we will front. - */ - public EndpointServiceInterface(EndpointServiceImpl endpointService) { - theRealThing = endpointService; - synchronized (this.getClass()) { - activeInstanceCount++; - if (1 == activeInstanceCount) { - listenerAdaptor = new ListenerAdaptor(Thread.currentThread().getThreadGroup(), ((StdPeerGroup) endpointService.getGroup()).getExecutor()); - } - } - } - - /** - * {@inheritDoc} - *

      - * This is rather heavy-weight if instances are frequently created and - * discarded since finalization significantly delays GC. - */ - @Override - protected void finalize() throws Throwable { - synchronized (this.getClass()) { - activeInstanceCount--; - if (0 == activeInstanceCount) { - listenerAdaptor.shutdown(); - listenerAdaptor = null; - } - } - super.finalize(); - } - - /** - * {@inheritDoc} - *

      - * it is there only to satisfy the requirements of the interface that we - * implement. Ultimately, the API should define two levels of interfaces : - * one for the real service implementation and one for the interface object. - * Right now it feels a bit heavy to so that since the only different - * between the two would be init() and may-be getName(). - */ - public void init(PeerGroup peerGroup, ID id, Advertisement implAdv) { - } - - /** - * {@inheritDoc} - *

      - * This is here for temporary class hierarchy reasons. - * it is ALWAYS ignored. By definition, the interface object - * protects the real object's start/stop methods from being called - */ - public int startApp(String[] arg) { - return Module.START_OK; - } - - /** - * {@inheritDoc} - *

      - * This is here for temporary class hierarchy reasons. - * it is ALWAYS ignored. By definition, the interface object - * protects the real object's start/stop methods from being called - *

      - * This request is currently ignored. - */ - public void stopApp() { - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return theRealThing.getImplAdvertisement(); - } - - /** - * {@inheritDoc} - *

      - * Sort of absurd but this is part of the API we're implementing. - * We would not do a two-level API just for that. - */ - public EndpointService getInterface() { - return this; - } - - /** - * {@inheritDoc} - */ - public PeerGroup getGroup() { - return theRealThing.getGroup(); - } - - /** - * {@inheritDoc} - */ - public Messenger getCanonicalMessenger(EndpointAddress addr, Object hint) { - // XXX: maybe we should enforce the stripping of the address here. - // That would prevent application from making canonical messengers with a variety of service names and - // service params. On the other hand that would cost useless cloning of endp addrs and prevent future - // flexibility regarding QOS params, possibly. Be liberal for now. - return theRealThing.getCanonicalMessenger(addr, hint); - } - - /** - * {@inheritDoc} - */ - public Messenger getMessengerImmediate(EndpointAddress addr, Object hint) { - // Note: for now, the hint is not used for canonicalization (hint != QOS). - synchronized (channelCache) { - Reference existing = channelCache.get(addr); - - if (existing != null) { - Messenger messenger = existing.get(); - if ((messenger != null) && ((messenger.getState() & Messenger.USABLE) != 0)) { - return messenger; - } - } - } - - // We do not have a good one at hand. Make a new one. - - // Use the stripped address to get a canonical msngr; not doing so - // would reduce the sharing to almost nothing. - EndpointAddress plainAddr = new EndpointAddress(addr, null, null); - - Messenger found = theRealThing.getCanonicalMessenger(plainAddr, hint); - - // Address must not be a supported one. - if (found == null) { - return null; - } - - // Get a channel for that servicename and serviceparam. redirect to this group. - - // NOTE: This assumes that theRealThing.getGroup() is really the group where the application that obtained - // this interface object lives. This is the case today because all groups have their own endpoint service. - // In the future, interface objects may refer to a group context that is not necessarily the group where - // "therealThing" lives. When that happens, this interface object will have to know which group it works - // for without asking "theRealThing". - - ChannelMessenger res = (ChannelMessenger) found.getChannelMessenger(theRealThing.getGroup().getPeerGroupID(), - addr.getServiceName(), addr.getServiceParameter()); - - synchronized (channelCache) { - // We have to check again. May be we did all that in parallel with some other thread and it beat - // us to the finish line. In which case, substitute the existing one and throw ours away. - Reference existing = channelCache.get(addr); - - if (existing != null) { - Messenger messenger = existing.get(); - if ((messenger != null) && ((messenger.getState() & Messenger.USABLE) != 0)) { - return messenger; - } - } - // The listenerAdaptor of this interface obj is used to support the sendMessage-with-listener API. - res.setMessageWatcher(listenerAdaptor); - channelCache.put(res.getDestinationAddress(), new WeakReference(res)); - } - return res; - } - - /** - * {@inheritDoc} - */ - public Messenger getMessenger(EndpointAddress addr) { - return getMessenger(addr, null); - } - - /** - * {@inheritDoc} - */ - public Messenger getMessenger(EndpointAddress addr, Object hint) { - - // Get an unresolved messenger (that's immediate). - Messenger messenger = getMessengerImmediate(addr, hint); - - if (messenger == null) { - return null; - } - - // Now ask the messenger to resolve: this legacy blocking API ensures - // that only successfully resolved messengers are ever returned. - messenger.resolve(); - try { - messenger.waitState(Messenger.RESOLVED | Messenger.TERMINAL, TimeUtils.AMINUTE); - } catch (InterruptedException ie) { - Thread.interrupted(); - } - - // check the state - int state = messenger.getState(); - - if ((state & Messenger.TERMINAL) != 0) { - return null; - } - if ((state & Messenger.RESOLVED) == 0) { - // Not failed yet. But too late for us. - return null; - } - return messenger; - } - - /** - * {@inheritDoc} - */ - public void propagate(Message msg, String serviceName, String serviceParam) { - theRealThing.propagate(msg, serviceName, serviceParam, Integer.MAX_VALUE); - } - - /** - * {@inheritDoc} - */ - public void propagate(Message msg, String serviceName, String serviceParam, int initialTTL) { - theRealThing.propagate(msg, serviceName, serviceParam, initialTTL); - } - - /** - * {@inheritDoc} - */ - public void demux(Message msg) { - theRealThing.demux(msg); - } - - /** - * {@inheritDoc} - */ - public void processIncomingMessage(Message message, EndpointAddress source, EndpointAddress destination) { - theRealThing.processIncomingMessage(message, source, destination); - } - - /** - * {@inheritDoc} - */ - @Deprecated - public boolean ping(EndpointAddress addr) { - return null != getMessengerImmediate(addr, null); - } - - /** - * {@inheritDoc} - */ - public MessengerEventListener addMessageTransport(MessageTransport transpt) { - // FIXME TOO: We should probably make the interface refuse to do it. - // But that will have to wait until we have criteria to decide who - // gets an interface object and who gets the real thing. In the - // meantime just do it. - return theRealThing.addMessageTransport(transpt); - } - - /** - * {@inheritDoc} - */ - public boolean removeMessageTransport(MessageTransport transpt) { - // FIXME TOO: We should probably make the interface refuse to do it. - // But that will have to wait until we have criteria to decide who - // gets an interface object and who gets the real thing. In the - // meantime just do it. - return theRealThing.removeMessageTransport(transpt); - } - - /** - * {@inheritDoc} - */ - public Iterator getAllMessageTransports() { - return theRealThing.getAllMessageTransports(); - } - - /** - * {@inheritDoc} - */ - public MessageTransport getMessageTransport(String name) { - return theRealThing.getMessageTransport(name); - } - - /** - * {@inheritDoc} - */ - public boolean addIncomingMessageListener(EndpointListener listener, String serviceName, String serviceParam) { - return theRealThing.addIncomingMessageListener(listener, serviceName, serviceParam); - } - - /** - * {@inheritDoc} - */ - public EndpointListener getIncomingMessageListener(String serviceName, String serviceParam) { - return theRealThing.getIncomingMessageListener(serviceName, serviceParam); - } - - /** - * {@inheritDoc} - */ - public void addIncomingMessageFilterListener(MessageFilterListener listener, String namespace, String name) { - theRealThing.addIncomingMessageFilterListener(listener, namespace, name); - } - - /** - * {@inheritDoc} - */ - public void addOutgoingMessageFilterListener(MessageFilterListener listener, String namespace, String name) { - theRealThing.addOutgoingMessageFilterListener(listener, namespace, name); - } - - /** - * {@inheritDoc} - */ - public MessageFilterListener removeIncomingMessageFilterListener(MessageFilterListener listener, String namespace, String name) { - return theRealThing.removeIncomingMessageFilterListener(listener, namespace, name); - } - - /** - * {@inheritDoc} - */ - public MessageFilterListener removeOutgoingMessageFilterListener(MessageFilterListener listener, String namespace, String name) { - return theRealThing.removeOutgoingMessageFilterListener(listener, namespace, name); - } - - /** - * {@inheritDoc} - */ - public EndpointListener removeIncomingMessageListener(String serviceName, String serviceParam) { - return theRealThing.removeIncomingMessageListener(serviceName, serviceParam); - } - - /** - * {@inheritDoc} - */ - public boolean addMessengerEventListener(MessengerEventListener listener, int prio) { - return theRealThing.addMessengerEventListener(listener, prio); - } - - /** - * {@inheritDoc} - */ - public boolean removeMessengerEventListener(MessengerEventListener listener, int prio) { - return theRealThing.removeMessengerEventListener(listener, prio); - } - - /** - * {@inheritDoc} - * - * @deprecated legacy support - */ - @Deprecated - public boolean getMessenger(MessengerEventListener listener, EndpointAddress addr, Object hint) { - Messenger messenger = getMessengerImmediate(addr, hint); - if (messenger == null) { - return false; - } - - if (!listenerAdaptor.watchMessenger(listener, messenger)) { - return false; - } - - // Make sure that resolution is being attempted if not already in progress. - messenger.resolve(); - return true; - } - - /** - * Returns a Direct Messenger that may be used to send messages via this endpoint to the specified destination. - * - * @param addr the destination address. - * @param hint the messenger hint, if any, otherwise null. - * @param exclusive if true avoids caching the messenger - * @return The messenger or {@code null} is returned if the destination address is not reachable. - */ - public Messenger getDirectMessenger(EndpointAddress addr, Object hint, boolean exclusive) { - return theRealThing.getDirectMessenger(addr, hint, exclusive); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/EndpointUtils.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/EndpointUtils.java deleted file mode 100644 index 2a5c25fb..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/EndpointUtils.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2001-2004 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint; - - -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.XMLElement; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - - -/** - * Utility functions related to the Endpoint Service. - */ -public final class EndpointUtils { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(EndpointUtils.class.getName()); - - /** - * Extracts a route advertisement from a peer advertisement. - * - * @param adv The peer advertisement believed to contain a route advertisement. - * @return The extracted route advertisement or {@code null} if a route - * advertisement could not be extracted. - */ - public static RouteAdvertisement extractRouteAdv(PeerAdvertisement adv) { - - try { - // Get its EndpointService advertisement - XMLElement endpParam = (XMLElement) adv.getServiceParam(PeerGroup.endpointClassID); - - if (endpParam == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No Endpoint Params"); - } - return null; - } - - // get the Route Advertisement element - Enumeration paramChilds = endpParam.getChildren(RouteAdvertisement.getAdvertisementType()); - XMLElement param; - - if (paramChilds.hasMoreElements()) { - param = (XMLElement) paramChilds.nextElement(); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No Route Adv in Peer Adv"); - } - return null; - } - - // build the new route - RouteAdvertisement route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(param); - - // Embedded routes often don't contain the peer id. - route.setDestPeerID(adv.getPeerID()); - - return route; - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to extract radv", e); - } - } - - return null; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/IPUtils.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/IPUtils.java deleted file mode 100644 index 60aafbf6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/IPUtils.java +++ /dev/null @@ -1,511 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint; - - -import java.io.IOException; -import java.net.BindException; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.NetworkInterface; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import javax.net.ServerSocketFactory; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * Utility methods for use by IP based transports. - */ -public final class IPUtils { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(IPUtils.class.getName()); - - final static Random random = new Random(); - - final static String IPV4ANYADDRESS = "0.0.0.0"; - final static String IPV6ANYADDRESS = "::"; - - final static String IPV4LOOPBACK = "127.0.0.1"; - final static String IPV6LOOPBACK = "::1"; - - /** - * Constant which works as the IP "Any Address" value - */ - public final static InetAddress ANYADDRESS; - public final static InetAddress ANYADDRESSV4; - public final static InetAddress ANYADDRESSV6; - - /** - * Constant which works as the IP "Local Loopback" value; - */ - public final static InetAddress LOOPBACK; - public final static InetAddress LOOPBACKV4; - public final static InetAddress LOOPBACKV6; - - /** - * Socket factory to allow changing the way Sockets are created - * and connected. A null value is ok and results in the regular - * connectToFromNoFactory being used. - * - *

      Plugin in a different implementation via setSocketFactory(). - */ - private static SocketFactory socketFactory; - - /** - * Socket factory to allow changing the way Sockets are created - * and connected. A null value is ok and results in the regular - * connectToFromNoFactory being used. - * - *

      Plugin in a different implementation via setSocketFactory(). - */ - private static ServerSocketFactory serverSocketFactory; - - static { - InetAddress GET_ADDRESS = null; - - try { - GET_ADDRESS = InetAddress.getByName(IPV4ANYADDRESS); - } catch (Exception ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("failed to intialize ANYADDRESSV4. Not fatal"); - } - } - - ANYADDRESSV4 = GET_ADDRESS; - - InetAddress GET_ANYADDRESSV6 = null; - - GET_ADDRESS = null; - try { - GET_ADDRESS = InetAddress.getByName(IPV6ANYADDRESS); - } catch (Exception ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("failed to intialize IPV6ANYADDRESS. Not fatal"); - } - } - - ANYADDRESSV6 = GET_ADDRESS; - - ANYADDRESS = (ANYADDRESSV4 == null) ? ANYADDRESSV6 : ANYADDRESSV4; - - GET_ADDRESS = null; - try { - GET_ADDRESS = InetAddress.getByName(IPV4LOOPBACK); - } catch (Exception ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("failed to intialize IPV4LOOPBACK. Not fatal"); - } - } - - LOOPBACKV4 = GET_ADDRESS; - - GET_ADDRESS = null; - try { - GET_ADDRESS = InetAddress.getByName(IPV6LOOPBACK); - } catch (Exception ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("failed to intialize ANYADDRESSV4. Not fatal"); - } - } - - LOOPBACKV6 = GET_ADDRESS; - - LOOPBACK = (LOOPBACKV4 == null) ? LOOPBACKV6 : LOOPBACKV4; - - if (LOOPBACK == null || ANYADDRESS == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("failure initializing statics. Neither IPV4 nor IPV6 seem to work."); - } - - throw new IllegalStateException("failure initializing statics. Neither IPV4 nor IPV6 seem to work."); - } - } - - /** - * This is a static utility class, you don't make instances. - */ - private IPUtils() {} - - /** - * Provide an iterator which returns all of the local InetAddresses for this - * host. - * - * @return iterator of InetAddress which is all of the InetAddress for all - * local interfaces. - */ - public static Iterator getAllLocalAddresses() { - List allAddr = new ArrayList(); - - Enumeration allInterfaces = null; - - try { - allInterfaces = NetworkInterface.getNetworkInterfaces(); - } catch (SocketException caught) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not get local interfaces list", caught); - } - } - - if (null == allInterfaces) { - allInterfaces = Collections.enumeration(Collections.emptyList()); - } - - while (allInterfaces.hasMoreElements()) { - NetworkInterface anInterface = allInterfaces.nextElement(); - - try { - Enumeration allIntfAddr = anInterface.getInetAddresses(); - - while (allIntfAddr.hasMoreElements()) { - InetAddress anAddr = allIntfAddr.nextElement(); - - if (anAddr.isLoopbackAddress() || anAddr.isAnyLocalAddress()) { - continue; - } - - if (!allAddr.contains(anAddr)) { - allAddr.add(anAddr); - } - } - } catch (Throwable caught) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not get addresses for " + anInterface, caught); - } - } - } - - // if nothing suitable was found then return loopback address. - if (allAddr.isEmpty() || Boolean.getBoolean("net.jxta.impl.IPUtils.localOnly")) { - if (null != LOOPBACKV4) { - allAddr.add(LOOPBACKV4); - } - - if (null != LOOPBACKV6) { - allAddr.add(LOOPBACKV6); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Adding loopback interfaces"); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Returning " + allAddr.size() + " addresses."); - } - - return allAddr.iterator(); - } - - /** - * Normalized version of {@link java.net.InetAddress#getHostAddress()} that - * handles IPv6 addresss formatting using the style of IETF RFC 2732 and - * also handles removal of IPv6 scoping identifiers. - * - * @see IETF RFC 2732 MIME : IPv6 Literal Addresses in URL's - * @param anAddress The address to format as a String. - * @return The addresss formatted as a String. - */ - public static String getHostAddress(InetAddress anAddress) { - String hostAddress; - - if (anAddress instanceof Inet6Address) { - hostAddress = anAddress.getHostAddress(); - int percentAt = hostAddress.indexOf('%'); - - if (-1 == percentAt) { - // no scoping identifier. Just add the brackets. - hostAddress = "[" + hostAddress + "]"; - } else { - // Remove scoping identifier. They aren't relevant when published. - hostAddress = "[" + hostAddress.substring(0, percentAt) + "]"; - } - } else { - hostAddress = anAddress.getHostAddress(); - } - - return hostAddress; - } - - /** - * Parses a String containing a SokectAddress formatted as either: - *

      - *

      -     *     <host> ":" <port>
      -     *
      -     *     "[" <numeric_host> "]:" <port>
      -     *  
      - *

      - * @param anAddress The address string to be parsed. - * @return The parsed address. - */ - public static InetSocketAddress parseSocketAddress(String anAddress) { - String hostAddress; - String port; - - if (anAddress.startsWith("[")) { - int endBracketAt = anAddress.indexOf(']'); - int portSeparatorAt = anAddress.lastIndexOf(':'); - - if (-1 == endBracketAt) { - throw new IllegalArgumentException("missing final ]"); - } - - if (-1 == portSeparatorAt) { - throw new IllegalArgumentException("missing port separator"); - } - - if (portSeparatorAt < endBracketAt) { - throw new IllegalArgumentException("missing port"); - } - - hostAddress = anAddress.substring(1, endBracketAt); - port = anAddress.substring(portSeparatorAt); - } else { - int portSeparatorAt = anAddress.lastIndexOf(':'); - - if (-1 == portSeparatorAt) { - throw new IllegalArgumentException("missing port separator"); - } - - hostAddress = anAddress.substring(0, portSeparatorAt); - port = anAddress.substring(portSeparatorAt + 1); - } - - int portNum = Integer.parseInt(port); - - return InetSocketAddress.createUnresolved(hostAddress, portNum); - } - - /** - * Create a client socket using the configured socketFactory or - * connectToFromNoFactory if none is available. - * - * @param inetAddress Destination address - * @param port Destination port - * @param usingInterface Interface to use - * @param localPort local port - * @param timeout timeout in millis - * @return a client socket with the JDK1.4 method connect(). - * @throws IOException if an io error occurs - */ - public static Socket connectToFrom(InetAddress inetAddress, int port, InetAddress usingInterface, int localPort, int timeout) throws IOException { - if (socketFactory != null) { - return socketFactory.createConnection(inetAddress, port, usingInterface, localPort, timeout); - } else { - return connectToFromNoFactory(inetAddress, port, usingInterface, localPort, timeout); - } - } - - /** - * Create a client socket with the JDK1.4 method connect(). - * - * @param inetAddress Destination address - * @param port Destination port - * @param usingInterface Interface to use - * @param localPort local port - * @param timeout timeout in millis - * @return a client socket with the JDK1.4 method connect(). - * @throws IOException if an io error occurs - */ - public static Socket connectToFromNoFactory(InetAddress inetAddress, int port, InetAddress usingInterface, int localPort, int timeout) throws IOException { - - Socket socket = new Socket(); - InetSocketAddress src = new InetSocketAddress(usingInterface, localPort); - InetSocketAddress dst = new InetSocketAddress(inetAddress, port); - - socket.bind(src); - socket.connect(dst, timeout); - - return socket; - } - - /** - * makes connectToFrom create sockets with this factory. - * - * @param sf is the socket factory to use or null if you want the - * default behaviour provided by connectToFromNoFactory(). - */ - public static void setSocketFactory(SocketFactory sf) { - socketFactory = sf; - } - - /** - * returns the socketFactory used by connectToFrom() to create sockets, or - * null if connectToFromNoFactory() is being used. - * - * @return the socket factory used by connectToFrom() or null if - * the connectToFromNoFactory() method is used to create Sockets. - */ - public static SocketFactory getSocketFactory() { - return socketFactory; - } - - /** - * makes connectToFrom create sockets with this factory. - * - * @param sf is the socket factory to use or null if you want the - * default behaviour provided by new SeverSocket(). - */ - public static void setServerSocketFactory(ServerSocketFactory sf) { - serverSocketFactory = sf; - } - - /** - * returns the ServerSocketFactory to create server sockets, or - * null if new SeverSocket() is being used. - * - * @return the socket factory used or null if - * the new SeverSocket() method is used to create ServerSockets. - */ - public static ServerSocketFactory getServerSocketFactory() { - return serverSocketFactory; - } - - /** - * Size of port groups we will probe. - */ - final static int rangesize = 200; - - /** - * Open a ServerSocket in the specified range. - * - *

      - * The method used is done so that the entire range is examined if - * needed while ensuring that the process eventually terminates if no port - * is available. - * - * @param start The lowest numbered port to try. - * @param end The highest numbered port to try. - * @param backlog the allowed backlog of unaccepted connections. - * @param bindAddress the InetAddress to which to bind. - * @return a ServerSocket in the specified range. - * @throws IOException when the socket cannot be opened. (Lame, but that's what ServerSocket says). - */ - public static ServerSocket openServerSocketInRange(int start, int end, int backlog, InetAddress bindAddress) throws IOException { - ServerSocketFactory factory = getServerSocketFactory(); - - if ((start < 1) || (start > 65535)) { - throw new IllegalArgumentException("Invalid start port"); - } - - if ((end < 1) || (end > 65535) || (end < start)) { - throw new IllegalArgumentException("Invalid end port"); - } - - // fill the inRange array. - List inRange = new ArrayList(rangesize); - - for (int eachInRange = 0; eachInRange < rangesize; eachInRange++) { - inRange.add(eachInRange, eachInRange); - } - - // fill the ranges array. - List ranges = new ArrayList(); - int starts = start; - - while (starts <= end) { - ranges.add(starts); - starts += rangesize; - } - - // shuffle the ranges - Collections.shuffle(ranges); - while (!ranges.isEmpty()) { - int range = ranges.remove(0); - - // reshuffle the inRange - Collections.shuffle(inRange); - - for (int eachInRange = 0; eachInRange < rangesize; eachInRange++) { - int tryPort = range + inRange.get(eachInRange); - - if (tryPort > end) { - continue; - } - - try { - ServerSocket result; - - if (null == factory) { - result = new ServerSocket(tryPort, backlog, bindAddress); - } else { - result = factory.createServerSocket(tryPort, backlog, bindAddress); - } - - return result; - } catch (BindException failed) {// this one is busy. try another. - } - } - } - throw new BindException("All ports in range are in use."); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/JxtaMessageMessageElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/JxtaMessageMessageElement.java deleted file mode 100644 index 6084fd32..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/JxtaMessageMessageElement.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint; - - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.MimeMediaType; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.WireFormatMessageFactory; - - -/** - * A Message Element using a JXTA Message as the element data - * - * @see net.jxta.endpoint.Message - * @see net.jxta.endpoint.MessageElement - **/ -public class JxtaMessageMessageElement extends MessageElement { - - /** - * Log4J Logger - **/ - private final static transient Logger LOG = Logger.getLogger(JxtaMessageMessageElement.class.getName()); - - /** - * The Message which is the data for this message element. - **/ - protected final Message msg; - - /** - * A serialized form of the message. - **/ - protected transient net.jxta.endpoint.WireFormatMessage serial; - - /** - * Create a new Message Element. The contents of the provided message are - * not copied during construction. - * - * @param name Name of the MessageElement. May be the empty string ("") if - * the MessageElement is not named. - * @param type Type of the MessageElement. null is the same as specifying - * the type "Application/Octet-stream". - * @param msg A message which will be used as the element content for this - * message. - * @param sig optional message digest/digital signature element or null if - * no signature is desired. - **/ - public JxtaMessageMessageElement(String name, MimeMediaType type, Message msg, MessageElement sig) { - super(name, type, sig); - - this.msg = msg; - } - - /** - * {@inheritDoc} - **/ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof MessageElement) { - if (!super.equals(target)) { - return false; - } - - if (target instanceof JxtaMessageMessageElement) { - JxtaMessageMessageElement likeMe = (JxtaMessageMessageElement) target; - - return super.equals(likeMe) && msg.equals(likeMe.msg); - } else { - // have to do a slow stream comparison. - // XXX 20020615 bondolo@jxta.org the performance of this could be much improved. - try { - MessageElement likeMe = (MessageElement) target; - - InputStream myStream = getStream(); - InputStream itsStream = likeMe.getStream(); - - int mine; - int its; - - do { - mine = myStream.read(); - its = itsStream.read(); - - if (mine != its) { - return false; - } // content didn't match (includes EOF check). - - } while (-1 != mine); - - return true; - } catch (IOException fatal) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "MessageElements could not be compared.", fatal); - } - - IllegalStateException failure = new IllegalStateException("MessageElements could not be compared."); - - failure.initCause(fatal); - - throw failure; - } - } - } - - return false; // not a message element - } - - /** - * {@inheritDoc} - **/ - @Override - public int hashCode() { - int result = super.hashCode() * 6037 + // a prime - msg.hashCode(); - - return (0 != result) ? result : 1; - } - - /** - * {@inheritDoc} - **/ - @Override - public String toString() { - throw new UnsupportedOperationException("Cannot Generate String for this message element type."); - } - - /** - * {@inheritDoc} - **/ - @Override - public long getByteLength() { - initSerial(); - - return serial.getByteLength(); - } - - /** - * {@inheritDoc} - **/ - @Override - public byte[] getBytes(boolean copy) { - initSerial(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream((int) serial.getByteLength()); - - try { - sendToStream(baos); - - baos.close(); - } catch (IOException failed) { - throw new IllegalStateException("failed to generate byte stream"); - } - - return baos.toByteArray(); - } - - /** - * {@inheritDoc} - **/ - public InputStream getStream() throws IOException { - initSerial(); - - return serial.getStream(); - } - - /** - * {@inheritDoc} - **/ - @Override - public void sendToStream(OutputStream sendTo) throws IOException { - initSerial(); - - serial.sendToStream(sendTo); - } - - /** - * Returns a copy of the message which backs this element. - * - * @return Returns a copy of the message which backs this element. - **/ - public Message getMessage() { - return msg.clone(); - } - - /** - * Generates the serialized representation of the message. - **/ - private synchronized void initSerial() { - if (null == serial) { - serial = WireFormatMessageFactory.toWire(msg, type, null); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/LoopbackMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/LoopbackMessenger.java deleted file mode 100644 index 37d0748d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/LoopbackMessenger.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint; - - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.IOException; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; -import net.jxta.impl.peergroup.GenericPeerGroup; -import net.jxta.peergroup.PeerGroup; - - -/** - * This class implements local delivery of messages (for example when the - * InputPipe and the OutputPipe are located on the same peer) - *

      - * The reason this class is useful is that it may not always be possible to - * connect to oneself without actually through the relay. i.e. A peer with outgoing - * only http transport, can not possibly connect to self through the transport. - *

      - * Since transports cannot be relied on to perform a loopback, some layer - * above has to figure out that a message is looping back. - * Since peerid loopback does not explicitly request to go through a real - * transport, and since peerid addressing is the job of the router, it is - * the router that performs loopback. - *

      - * The router could probably perform the loopback by delivering the message - * to its own input queue, that would take a special transport instead of a - * special messenger, which is the same kind of deal but would imply some - * incoming message processing by the router for every message. In - * contrast, the loopback messenger is setup once and the router will never - * sees the messages. That's a good optimization. - *

      - * Alternatively, the endpoint service itself could figure out the - * loopback, but since the API wants to give a messenger to the requestor - * rather than just sending a message, the endpoint would have to setup a - * loopback messenger anyway. So it is pretty much the same. - */ -public class LoopbackMessenger extends BlockingMessenger { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(LoopbackMessenger.class.getName()); - - /** - * The peergroup we are working for, ie. that we will loop back to. - */ - private final PeerGroup group; - - /** - * The endpoint we are working for, ie. that we will loop back to. - */ - private final EndpointService endpoint; - - /** - * The source address of messages sent on this messenger. - */ - private final EndpointAddress srcAddress; - - /** - * The location destination of this messenger. - */ - private final EndpointAddress logicalDestination; - - /** - * Used to ensure that only a single message is demuxed at a time. - */ - private final Lock orderingLock = new ReentrantLock(true); - - /** - * Create a new loopback messenger. - * - * @param group The group context. - * @param ep where messages go - * @param src who messages should be addressed from - * @param dest who messages should be addressed to - * @param logicalDest The logical destination address. - */ - public LoopbackMessenger(PeerGroup group, EndpointService ep, EndpointAddress src, EndpointAddress dest, EndpointAddress logicalDest) { - super(group.getPeerGroupID(), dest, false); - - this.group = group; - endpoint = ep; - srcAddress = src; - logicalDestination = logicalDest; - } - - /** - * {@inheritDoc} - */ - @Override - public EndpointAddress getLogicalDestinationImpl() { - return logicalDestination; - } - - /** - * {@inheritDoc} - */ - @Override - public long getMTU() { - return Long.MAX_VALUE; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isIdleImpl() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public void closeImpl() {} - - /** - * {@inheritDoc} - */ - @Override - public void sendMessageBImpl(final Message message, final String service, final String serviceParam) throws IOException { - - if (isClosed()) { - IOException failure = new IOException("Messenger was closed, it cannot be used to send messages."); - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, failure.getMessage(), failure); - } - throw failure; - } - - orderingLock.lock(); - try { - // Process the message with the appropriate src and dest address - ((GenericPeerGroup)group).getExecutor().execute( new Runnable() { - public void run() { - try { - endpoint.processIncomingMessage(message, srcAddress, getDestAddressToUse(service, serviceParam)); - } catch(Throwable uncaught) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught Throwable in Loopback Messenger ", uncaught); - } - } - } - }); - } finally { - orderingLock.unlock(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/SocketFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/SocketFactory.java deleted file mode 100644 index a1194948..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/SocketFactory.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint; - - -import java.io.IOException; -import java.net.InetAddress; -import java.net.Socket; - - -/** - * Provides pluggable socket creation for JXTA TCP connection (not - * those for HTTP since those are from URLConnection). - * - *

      The motivation for this class was to provide the ability to - * tunnel JXTA TCP through a web proxy but it could be used for other - * things as well. Call IPUtils.setSocketFactory() to configure JXTA - * to use a particular socket factory

      - * - * @author Mike Sample - */ -public interface SocketFactory { - - /** - * creates and returns a connected Socket. - * - * @param inetAddress the destination IP address used to create an - * InetSocketAddress that will be used with the connect() call on - * the created socket. - * - * @param port the destination TCP port used to create an - * InetSocketAddress that will be used with the connect() call on - * the created socket. - * - * @param usingInterface the src (local) IP address used to create - * an InetSocketAddress to which the created socket will be bound - * via bind(). - * - * @param localPort the src (local) TCP port used to create an - * InetSocketAddress to which the created socket will be bound via - * bind(). - * - * @param timeout the time in milliseconds to be used with the - * socket.connect() call. A value of zero means infinite timeout. - * - */ - public Socket createConnection(InetAddress inetAddress, int port, InetAddress usingInterface, int localPort, int timeout) throws IOException; - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/WireFormatMessageBinary.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/WireFormatMessageBinary.java deleted file mode 100644 index 92e35876..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/WireFormatMessageBinary.java +++ /dev/null @@ -1,1280 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint; - - -import net.jxta.document.MimeMediaType; -import net.jxta.endpoint.ByteArrayMessageElement; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.WireFormatMessage; -import net.jxta.endpoint.WireFormatMessageFactory; -import net.jxta.util.LimitInputStream; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.SequenceInputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.nio.ByteBuffer; -import java.text.MessageFormat; -import java.util.Arrays; - - -/** - * A Wire Format Message which encodes the message into MIME Type - * "application/x-jxta-msg". - *

      - *

      This implementation does nothing with encodings. - *

      - *

      This implementation does not use any MIME parameters attached to the - * requesting mime type. - * - * @see net.jxta.endpoint.WireFormatMessageFactory - * @see JXTA Protocols Specification : Binary Message Format - */ -public class WireFormatMessageBinary implements WireFormatMessage { - - /* - * Log4J Logger - */ - private final static transient Logger LOG = Logger.getLogger(WireFormatMessageBinary.class.getName()); - - // Flag bits - protected static final byte HAS_TYPE = 0x01; - protected static final byte HAS_ENCODING = 0x02; - protected static final byte HAS_SIGNATURE = 0x04; - - protected static final int MESSAGE_VERSION = 0; - - /** - * Our Mime Media Type(s) - */ - private static final MimeMediaType[] myTypes = { - MimeMediaType.valueOf("application/x-jxta-msg") }; - - /** - * These are the content encodings we support. - */ - private static final MimeMediaType[] myContentEncodings = { - - // we support raw binary! - null - }; - - /** - * Our instantiator for the factory. - */ - public static final WireFormatMessageFactory.Instantiator INSTANTIATOR = new Instantiator(); - - /** - * Our instantiator. - */ - static class Instantiator implements WireFormatMessageFactory.Instantiator { - - /** - * Creates new WireFormatMessageBinary Instantiator - */ - public Instantiator() {} - - /** - * {@inheritDoc} - */ - public MimeMediaType[] getSupportedMimeTypes() { - return myTypes; - } - - /** - * {@inheritDoc} - */ - public MimeMediaType[] getSupportedContentEncodings() { - return myContentEncodings; - } - - /** - * {@inheritDoc} - */ - public Message fromWire(InputStream is, MimeMediaType type, MimeMediaType contentEncoding) throws IOException { - // FIXME 20020504 bondolo@jxta.org Ignores type and contentEncoding completely. - Message msg = new Message(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Reading " + msg + " from " + is); - } - - DataInputStream dis = new DataInputStream(is); - - HashMap idToNamespace = readHeader(dis); - - int elementCnt = dis.readShort(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Message element count " + elementCnt + " from " + is); - } - - int eachElement = 0; - - do { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Read element " + eachElement + " of " + elementCnt + " from " + is + " for " + msg); - } - - Object[] anElement; - - try { - anElement = readMessageElement(dis, is); - } catch (IOException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE - , - "Failure reading element " + eachElement + " of " + elementCnt + " from " + is + " for " + msg - , - failed); - } - - throw failed; - } - - if (null == anElement) { - break; - } - - String namespace = (String) idToNamespace.get(anElement[0]); - - if (null == namespace) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Element identified a namespace which was not defined for this message."); - } - - throw new IOException("Element identified a namespace which was not defined for this message."); - } - - msg.addMessageElement(namespace, (MessageElement) anElement[1]); - eachElement++; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "Add element (name=\'" + ((MessageElement) anElement[1]).getElementName() + "\') #" + eachElement - + " of #" + elementCnt + " elements from " + dis.toString()); - } - } while (((0 == elementCnt) || (eachElement < elementCnt))); - - if ((elementCnt != 0) && (eachElement != elementCnt)) { - throw new IOException("Found wrong number of elements in message."); - } - - return msg; - } - - public Message fromBuffer(ByteBuffer buffer, MimeMediaType type, MimeMediaType contentEncoding) throws IOException { - // FIXME 20020504 bondolo@jxta.org Ignores type and contentEncoding completely. - Message msg = new Message(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Reading " + msg + " from " + buffer); - } - - HashMap idToNamespace = readHeader(buffer); - - int elementCnt = buffer.getShort(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Message element count " + elementCnt + " from " + buffer); - } - - int eachElement = 0; - - do { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Read element " + eachElement + " of " + elementCnt + " from " + buffer + " for " + msg); - } - - Object[] anElement; - - try { - anElement = readMessageElement(buffer); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - MessageFormat.format("Read element of size {0}, [{1}] {2}", anElement.length, anElement.toString() - , - buffer.toString())); - } - } catch (IOException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE - , - "Failure reading element " + eachElement + " of " + elementCnt + " from " + buffer + " for " + msg - , - failed); - } - throw failed; - } - - if (null == anElement) { - break; - } - - String namespace = (String) idToNamespace.get(anElement[0]); - - if (null == namespace) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Element identified a namespace which was not defined for this message."); - } - throw new IOException("Element identified a namespace which was not defined for this message."); - } - - msg.addMessageElement(namespace, (MessageElement) anElement[1]); - eachElement++; - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "Add element (name=\'" + ((MessageElement) anElement[1]).getElementName() + "\') #" + eachElement - + " of #" + elementCnt + " elements from " + buffer.toString()); - } - } while (((0 == elementCnt) || (eachElement < elementCnt))); - - if ((elementCnt != 0) && (eachElement != elementCnt)) { - throw new IOException("Found wrong number of elements in message."); - } - - return msg; - } - - /** - * {@inheritDoc} - */ - public WireFormatMessage toWire(Message msg, MimeMediaType type, MimeMediaType[] preferedContentEncoding) { - try { - return new WireFormatMessageBinary(msg, type, preferedContentEncoding); - } catch (IOException caught) { - throw new IllegalStateException("Could not build wire format for message due to " + caught.getMessage()); - } - } - - /** - * Read in a message header from the provided data stream. - * - * @param dis the data stream to read from - * @return hashmap containing the namespace id to namespace values - * @throws IOException if EOF or other IOException is encountered - * during the reading of the header. - */ - private static HashMap readHeader(DataInputStream dis) throws IOException { - // Read message signature - char[] msgsig = new char[4]; - - try { - msgsig[0] = (char) dis.readByte(); - } catch (EOFException failed) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.log(Level.FINER, "EOF reading message at first byte of header.", failed); - } - - throw failed; - } - msgsig[1] = (char) dis.readByte(); - msgsig[2] = (char) dis.readByte(); - msgsig[3] = (char) dis.readByte(); - - if (msgsig[0] != 'j' || msgsig[1] != 'x' || msgsig[2] != 'm' || msgsig[3] != 'g') { - IOException failure = new IOException( - "Not a message (incorrect signature '" + msgsig[0] + msgsig[1] + msgsig[2] + msgsig[3] + "') "); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe(failure.toString()); - } - - throw failure; - } - - // Message version - if (dis.readByte() != MESSAGE_VERSION) { - IOException failure = new IOException("Message not version " + MESSAGE_VERSION); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, failure.getMessage(), failure); - } - - throw failure; - } - - int namespaceCnt = dis.readShort(); - - if (namespaceCnt > 253) { - IOException failure = new IOException("Message contains too many namespaces (>253)"); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, failure.getMessage(), failure); - } - - throw failure; - } - - HashMap id2namespace = new HashMap(2 + namespaceCnt); - - id2namespace.put(0, ""); - id2namespace.put(1, "jxta"); - - int id = 2; - - for (int i = 0; i < namespaceCnt; ++i) { - try { - String namespace = readString(dis); - - id2namespace.put(id++, namespace); - } catch (IOException caught) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Error Processing namespace", caught); - } - throw caught; - } - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Read Message Header with " + (namespaceCnt + 2) + " namespaces from " + dis.toString()); - } - - return id2namespace; - } - - /** - * Read in a message header from the provided data stream. - * - * @param buffer the data buffer to read from - * @return hashmap containing the namespace id to namespace values - * @throws IOException if EOF or other IOException is encountered - * during the reading of the header. - */ - private static HashMap readHeader(ByteBuffer buffer) throws IOException { - // Read message signature - char[] msgsig = new char[4]; - - msgsig[0] = (char) buffer.get(); - msgsig[1] = (char) buffer.get(); - msgsig[2] = (char) buffer.get(); - msgsig[3] = (char) buffer.get(); - - if (msgsig[0] != 'j' || msgsig[1] != 'x' || msgsig[2] != 'm' || msgsig[3] != 'g') { - IOException failure = new IOException( - "Not a message (incorrect signature '" + msgsig[0] + msgsig[1] + msgsig[2] + msgsig[3] + "') "); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe(failure.toString()); - } - throw failure; - } - - // Message version - if (buffer.get() != MESSAGE_VERSION) { - IOException failure = new IOException("Message not version " + MESSAGE_VERSION); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, failure.getMessage(), failure); - } - throw failure; - } - - int namespaceCnt = buffer.getShort(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer(MessageFormat.format("Message defines {0} namespaces buffer stats{1}", namespaceCnt, buffer.toString())); - } - - if (namespaceCnt > 253) { - IOException failure = new IOException( - MessageFormat.format("Message contains too many namespaces ({0} >253)", namespaceCnt)); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, failure.getMessage(), failure); - } - - throw failure; - } - - HashMap id2namespace = new HashMap(2 + namespaceCnt); - - id2namespace.put(0, ""); - id2namespace.put(1, "jxta"); - - int id = 2; - - for (int i = 0; i < namespaceCnt; ++i) { - try { - String namespace = readString(buffer); - - id2namespace.put(id++, namespace); - } catch (IOException caught) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Error Processing namespace", caught); - } - throw caught; - } - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Read Message Header with " + (namespaceCnt + 2) + " namespaces from " + buffer.toString()); - } - - return id2namespace; - } - - /** - * Read in a message element from the provided data stream. - * - * @param dis the data stream to read from - * @param is todo - * @return object array containing two objects, index[0] contains an - * Integer which identifies the namespace to which this element belongs - * and index[1] contains a MessageElement. If null is returned then - * the DataInputStream reached EOF before reading the first byte of the - * element. - * @throws IOException if EOF or other IOException is encountered - * during the reading of the element. - */ - private Object[] readMessageElement(DataInputStream dis, InputStream is) throws IOException { - // Read message signature - char[] elsig = new char[4]; - - // if we EOF before the first byte, return null. EOF anywhere else - // and its an error. - try { - elsig[0] = (char) dis.readByte(); - } catch (EOFException allDone) { - return null; - } - - elsig[1] = (char) dis.readByte(); - elsig[2] = (char) dis.readByte(); - elsig[3] = (char) dis.readByte(); - - if (elsig[0] != 'j' || elsig[1] != 'x' || elsig[2] != 'e' || elsig[3] != 'l') { - IOException failure = new IOException( - "Not a message element (incorrect signature '" + elsig[0] + elsig[1] + elsig[2] + elsig[3] + "') "); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, failure.getMessage(), failure); - } - - throw failure; - } - - // Namespace id - int nsid = dis.readByte(); - - // flags - byte flags = dis.readByte(); - - // Name - String name = readString(dis); - - // Mime type - MimeMediaType type; - - if ((flags & HAS_TYPE) != 0) { - String typeString = readString(dis); - - try { - type = new MimeMediaType(typeString); - } catch (IllegalArgumentException uhoh) { - throw new IOException("Bad MIME type in message element header : " + uhoh.getMessage()); - } - } else { - type = MimeMediaType.AOS; - } - - int dataLen = dis.readInt(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "element : nsid = " + nsid + " name = \'" + name + "\' type = \'" + type + "\' flags = " - + Integer.toBinaryString(flags) + " datalen = " + dataLen); - } - - Object[] res = new Object[2]; - - res[0] = nsid & 0x000000FF; - - byte[] value = null; - Message submsg = null; - - // Value - if (type.equalsIngoringParams(myTypes[0])) { - InputStream subis = new LimitInputStream(is, dataLen); - - submsg = WireFormatMessageFactory.fromWire(subis, type, null); - } else { - if (dataLen > Integer.MAX_VALUE) { - // FIXME hamada dataLen is an int, the above expression can never be true - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("WireFormatMessageBinary does not support elements longer than 2GB"); - } - throw new IllegalStateException("WireFormatMessageBinary does not support elements longer than 2GB"); - } - - value = new byte[dataLen]; - - String mayFail = null; - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - mayFail = is.toString(); - } - - try { - dis.readFully(value); - } catch (EOFException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("had tried to read " + dataLen + " from " + mayFail + " which is now " + is); - } - throw failed; - } - } - - MessageElement sig = null; - - if ((flags & HAS_SIGNATURE) != 0) { - Object[] sigRes = readMessageElement(dis, is); - - sig = (MessageElement) sigRes[1]; - } - - if (null != value) { - res[1] = new ByteArrayMessageElement(name, type, value, sig); - } else { - res[1] = new JxtaMessageMessageElement(name, type, submsg, sig); - } - - return res; - } - - /** - * Read in a message element from the provided data stream. - * - * @param buffer the data buffer to read from - * @return object array containing two objects, index[0] contains an - * Integer which identifies the namespace to which this element belongs - * and index[1] contains a MessageElement. If null is returned then - * the DataInputStream reached EOF before reading the first byte of the - * element. - * @throws IOException if EOF or other IOException is encountered - * during the reading of the element. - */ - private Object[] readMessageElement(ByteBuffer buffer) throws IOException { - // Read message signature - char[] elsig = new char[4]; - - // if we EOF before the first byte, return null. EOF anywhere else - // and its an error. - elsig[0] = (char) buffer.get(); - elsig[1] = (char) buffer.get(); - elsig[2] = (char) buffer.get(); - elsig[3] = (char) buffer.get(); - - if (elsig[0] != 'j' || elsig[1] != 'x' || elsig[2] != 'e' || elsig[3] != 'l') { - IOException failure = new IOException( - "Not a message element (incorrect signature '" + elsig[0] + elsig[1] + elsig[2] + elsig[3] + "') "); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, failure.getMessage(), failure); - } - - throw failure; - } - - // Namespace id - int nsid = buffer.get(); - - // flags - byte flags = buffer.get(); - - // Name - String name = readString(buffer); - - // Mime type - MimeMediaType type; - - if ((flags & HAS_TYPE) != 0) { - String typeString = readString(buffer); - - try { - type = new MimeMediaType(typeString); - } catch (IllegalArgumentException uhoh) { - throw new IOException("Bad MIME type in message element header : " + uhoh.getMessage()); - } - } else { - type = MimeMediaType.AOS; - } - - int dataLen = buffer.getInt(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "element : nsid = " + nsid + " name = \'" + name + "\' type = \'" + type + "\' flags = " - + Integer.toBinaryString(flags) + " datalen = " + dataLen); - } - - Object[] res = new Object[2]; - - res[0] = nsid & 0x000000FF; - - byte[] value = null; - Message submsg = null; - - // Value - if (type.equalsIngoringParams(myTypes[0])) { - InputStream subis = new ByteArrayInputStream(buffer.array(), buffer.position(), dataLen); - - submsg = WireFormatMessageFactory.fromWire(subis, type, null); - // buffer.position(buffer.position() + dataLen); - } else { - if (dataLen > Integer.MAX_VALUE) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("WireFormatMessageBinary does not support elements longer than 2GB"); - } - throw new IllegalStateException("WireFormatMessageBinary does not support elements longer than 2GB"); - } - - value = new byte[dataLen]; - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer(MessageFormat.format("expecting {0} bytes, Buffer stats {1}", dataLen, buffer.toString())); - } - buffer.get(value); - } - - MessageElement sig = null; - - if ((flags & HAS_SIGNATURE) != 0) { - Object[] sigRes = readMessageElement(buffer); - - sig = (MessageElement) sigRes[1]; - } - - if (null != value) { - res[1] = new ByteArrayMessageElement(name, type, value, sig); - } else { - res[1] = new JxtaMessageMessageElement(name, type, submsg, sig); - } - - return res; - } - - /** - * Read and construct a string from the data stream. - * - * @param dis the stream to read from - * @return the String which was read. - * @throws IOException if EOF or other IOException is encountered - * during the reading of the string. - */ - private static String readString(DataInputStream dis) throws IOException { - int len = dis.readShort(); - - if (len < 0) { - throw new IOException("Bad string length in message"); - } - - byte[] bytes = new byte[len]; - - dis.readFully(bytes); - return new String(bytes, "UTF8"); - } - - /** - * Read and construct a string from the data stream. - * - * @param buffer the ByteBuffer to read from - * @return the String which was read. - * @throws IOException if EOF or other IOException is encountered - * during the reading of the string. - */ - private static String readString(ByteBuffer buffer) throws IOException { - int len = buffer.getShort(); - - if (len < 0) { - throw new IOException("Bad string length in message"); - } - - byte[] bytes = new byte[len]; - - buffer.get(bytes); - return new String(bytes, "UTF8"); - } - } - - - /** - * Internal representation for a binary format wire message. Implemented - * as an inner class to allow content encodings to be easily mapped on - * top of the streams this class produces. - */ - static class binaryMessageProxy implements WireFormatMessage { - final Message message; - - final MimeMediaType type; - - final List elements = new ArrayList(); - - final Map namespaceIDs = new HashMap(); - - final List namespaces = new ArrayList(); - - byte[] header; - - binaryMessageProxy(Message msg, MimeMediaType type) throws IOException { - message = msg; - - this.type = type; // we may generate different content based upon the type. - - assignNamespaceIds(); - - // build the element proxies - Message.ElementIterator eachElement = message.getMessageElements(); - - while (eachElement.hasNext()) { - MessageElement anElement = eachElement.next(); - byte namespaceid = namespaceIDs.get(eachElement.getNamespace()).byteValue(); - - elements.add(new binaryElementProxy(namespaceid, anElement)); - } - - buildHeader(); - } - - /** - * {@inheritDoc} - */ - public String getFileExtension() { - return "???"; - } - - /** - * {@inheritDoc} - */ - public MimeMediaType getMimeType() { - return type; - } - - /** - * {@inheritDoc} - */ - public ByteBuffer[] getByteBuffers() { - List partBuffers = new ArrayList(); - - partBuffers.add(ByteBuffer.wrap(header)); - - for (binaryElementProxy anElement : elements) { - partBuffers.addAll(Arrays.asList(anElement.getByteBuffers())); - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer(MessageFormat.format("Returning {0} buffers for {1}", partBuffers.size(), message)); - } - - return partBuffers.toArray(new ByteBuffer[partBuffers.size()]); - } - - /** - * {@inheritDoc} - */ - public InputStream getStream() throws IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting stream for " + message); - } - - List streamParts = new ArrayList(); - - streamParts.add(new ByteArrayInputStream(header)); - - for (binaryElementProxy anElement : elements) { - streamParts.add(anElement.getStream()); - } - - InputStream theStream = new SequenceInputStream(Collections.enumeration(streamParts)); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - MessageFormat.format("Returning {0}@{1} for {2}", theStream.getClass().getName() - , - System.identityHashCode(theStream), message)); - } - - return theStream; - } - - /** - * {@inheritDoc} - */ - public void sendToStream(OutputStream sendTo) throws IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + message + " to " + sendTo.getClass().getName() + "@" + System.identityHashCode(sendTo)); - } - - sendTo.write(header); - - Iterator eachElement = elements.listIterator(); - - while (eachElement.hasNext()) { - binaryElementProxy anElement = (binaryElementProxy) eachElement.next(); - - anElement.sendToStream(sendTo); - } - } - - /** - * {@inheritDoc} - */ - public long getByteLength() { - long size = 0; - - size += header.length; - for (binaryElementProxy element : elements) { - binaryElementProxy anElement = element; - - size += anElement.getByteLength(); - } - return size; - } - - /** - * {@inheritDoc} - */ - public MimeMediaType getContentEncoding() { - return null; - } - - /** - * Scans the source message to build a HashMap of the namespaces used - * in the message and assign and id to each namespace. - */ - private void assignNamespaceIds() { - int id = 0; - Iterator namespaces = message.getMessageNamespaces(); - - // insert the predefined namespaces. - namespaceIDs.put("", id++); - this.namespaces.add(""); - namespaceIDs.put("jxta", id++); - this.namespaces.add("jxta"); - - // insert items in the vector if they are not found in the map - while (namespaces.hasNext()) { - String namespace = (String) namespaces.next(); - - if (namespaceIDs.get(namespace) == null) { - namespaceIDs.put(namespace, id++); - this.namespaces.add(namespace); - } - } - - if (id >= 256) { - throw new IllegalStateException("WireFormatMessageBinary does not support more than 255 namespaces"); - } - } - - /** - * Builds the wire format header for the message. - * - * @throws IOException if for some reason the header cannot be built. - */ - private void buildHeader() throws IOException { - ByteArrayOutputStream headerBytes = new ByteArrayOutputStream(256); - DataOutputStream header = new DataOutputStream(headerBytes); - - header.writeBytes("jxmg"); - - header.writeByte(MESSAGE_VERSION); - header.writeShort(namespaces.size() - 2); - - for (int eachNamespace = 2; eachNamespace < namespaces.size(); eachNamespace++) { - byte[] elementName = namespaces.get(eachNamespace).getBytes("UTF8"); - - header.writeShort(elementName.length); - header.write(elementName, 0, elementName.length); - } - - header.writeShort(elements.size()); - - header.flush(); - header.close(); - headerBytes.flush(); - headerBytes.close(); - - this.header = headerBytes.toByteArray(); - } - } - - - /** - * Proxy for a message element. Handles the serialization of the element - * meta information. - */ - static class binaryElementProxy { - final byte namespaceid; - - binaryElementProxy sig; - - MessageElement element; - - byte[] header; - - binaryElementProxy(byte namespaceid, MessageElement element) throws IOException { - this.namespaceid = namespaceid; - - this.element = element; - - MessageElement sig = element.getSignature(); - - if (null != sig) { - this.sig = new binaryElementProxy(namespaceid, sig); - } - - buildHeader(); - } - - void buildHeader() throws IOException { - byte[] elementName = element.getElementName().getBytes("UTF8"); - byte[] elementType = null; - - if (!MimeMediaType.AOS.equals(element.getMimeType())) { - elementType = element.getMimeType().toString().getBytes("UTF8"); - } - - // FIXME 20020504 bondolo@jxta.org Do something with encodings. - ByteArrayOutputStream headerBytes = new ByteArrayOutputStream(256); - DataOutputStream header = new DataOutputStream(headerBytes); - - header.writeBytes("jxel"); - - header.writeByte(namespaceid); - header.writeByte(((null != elementType) ? HAS_TYPE : 0) | ((null != sig) ? HAS_SIGNATURE : 0)); - - header.writeShort(elementName.length); - header.write(elementName, 0, elementName.length); - - if (null != elementType) { - header.writeShort(elementType.length); - header.write(elementType, 0, elementType.length); - } - - // FIXME content encoding should go here - - long dataLen = element.getByteLength(); - - if (dataLen > Integer.MAX_VALUE) { - throw new IllegalStateException("WireFormatMessageBinary does not support elements longer than 4GB"); - } - - header.writeInt((int) dataLen); - - header.flush(); - header.close(); - headerBytes.flush(); - headerBytes.close(); - - this.header = headerBytes.toByteArray(); - } - - public long getByteLength() { - long size = 0; - - size += header.length; - size += element.getByteLength(); - if (null != sig) { - size += sig.getByteLength(); - } - - return size; - } - - public ByteBuffer[] getByteBuffers() { - List partBuffers = new ArrayList(); - - partBuffers.add(ByteBuffer.wrap(header)); - - partBuffers.add(ByteBuffer.wrap(element.getBytes(false))); - - if (null != sig) { - partBuffers.addAll(Arrays.asList(sig.getByteBuffers())); - } - - return partBuffers.toArray(new ByteBuffer[partBuffers.size()]); - } - - public InputStream getStream() throws IOException { - List streamParts = new ArrayList(); - - streamParts.add(new ByteArrayInputStream(header)); - - streamParts.add(element.getStream()); - - if (null != sig) { - streamParts.add(sig.getStream()); - } - - return new SequenceInputStream(Collections.enumeration(streamParts)); - } - - public void sendToStream(OutputStream sendTo) throws IOException { - - sendTo.write(header); - element.sendToStream(sendTo); - if (null != sig) { - sig.sendToStream(sendTo); - } - } - } - - /** - * The message we are serializing. - */ - private final Message msg; - - /** - * The mod count of the message when we started. Used for detecting - * (illegal) modifications. - */ - private final int msgModCount; - - /** - * The mime type of the encoded message. - */ - private final MimeMediaType type; - - /** - * The mime type of the content encoding for this message. - */ - private final MimeMediaType contentEncoding; - - /** - * The serialization peer to the Message. - */ - private final binaryMessageProxy msgProxy; - - /** - * Creates a new instance of WireFormatMessageBinary. Called only by the - * Instantiator. - * - * @param msg the message being serialized - * @param type the mime mediatype being requested. - * @param preferedContentEncodings The ranked content encodings preferred by - * the recipient. - * @throws java.io.IOException if an io error occurs - */ - WireFormatMessageBinary(Message msg, MimeMediaType type, MimeMediaType[] preferedContentEncodings) throws IOException { - if (null == msg) { - throw new IllegalArgumentException("Null message!"); - } - - this.msg = msg; - - this.msgModCount = msg.getMessageModCount(); - - if (null == type) { - throw new IllegalArgumentException("Null mime type!"); - } - - int matchedIdx = -1; - - for (int eachType = 0; eachType < myTypes.length; eachType++) { - if (type.equalsIngoringParams(myTypes[eachType])) { - matchedIdx = eachType; - break; - } - } - - if (-1 == matchedIdx) { - throw new IllegalArgumentException("Unsupported mime type!"); - } - - // FIXME 20020504 bondolo@jxta.org Check the mimetype params to make - // sure we can support them. - this.type = type; - - // FIXME 20020504 bondolo@jxta.org Do something with encodings. - this.contentEncoding = myContentEncodings[0]; - - msgProxy = new binaryMessageProxy(msg, type); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - throw new UnsupportedOperationException("don't do this"); - } - - /* - * The cost of just having a finalize routine is high. The finalizer is - * a bottleneck and can delay garbage collection all the way to heap - * exhaustion. Leave this comment as a reminder to future maintainers. - * Below is the reason why finalize is not needed here. - * - * No critical non-memory resource held. - protected void finalize( ) { - } - - */ - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - throw new UnsupportedOperationException("don't do this"); - } - - /** - * {@inheritDoc} - */ - public String getFileExtension() { - return "???"; - } - - /** - * {@inheritDoc} - */ - public MimeMediaType getMimeType() { - return type; - } - - /** - * {@inheritDoc} - */ - public InputStream getStream() throws IOException { - if (msg.getMessageModCount() != msgModCount) { - throw new IllegalStateException("message was unexpectedly modified!"); - } - - msg.modifiable = false; - try { - InputStream result = msgProxy.getStream(); - - return result; - } finally { - msg.modifiable = true; - } - } - - /** - * {@inheritDoc} - */ - public ByteBuffer[] getByteBuffers() { - if (msg.getMessageModCount() != msgModCount) { - throw new IllegalStateException("message was unexpectedly modified!"); - } - - msg.modifiable = false; - try { - ByteBuffer[] result = msgProxy.getByteBuffers(); - - return result; - } finally { - msg.modifiable = true; - } - } - - /** - * {@inheritDoc} - */ - public void sendToStream(OutputStream sendTo) throws IOException { - if (msg.getMessageModCount() != msgModCount) { - throw new IllegalStateException("message was unexpectedly modified!"); - } - - msg.modifiable = false; - try { - msgProxy.sendToStream(sendTo); - } finally { - msg.modifiable = true; - } - } - - /** - * {@inheritDoc} - */ - public long getByteLength() { - if (msg.getMessageModCount() != msgModCount) { - throw new IllegalStateException("message was unexpectedly modified!"); - } - - return msgProxy.getByteLength(); - } - - /** - * {@inheritDoc} - */ - public MimeMediaType getContentEncoding() { - return contentEncoding; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxDefs.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxDefs.java deleted file mode 100644 index 135c07d0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxDefs.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.cbjx; - - -import net.jxta.id.ID; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; - -import java.net.URI; - - -/** - * the value of the constants used with cbid - */ -public final class CbJxDefs { - - /** - * the name of the algo to compute signature - */ - public static final String signAlgoName = "SHA1WITHRSA"; - - /** - * the name of the algo to digest of message - */ - public static final String hashAlgoName = "SHA-1"; - - /** - * Well known module class identifier: msg transport - */ - public static final ModuleClassID msgtptClassID = (ModuleClassID) - ID.create(URI.create("urn:jxta:uuid-DeadBeefDeafBabaFeedBabe0000001105")); - - /** - * Well known service specification identifier: cbjx Msg Transport - */ - public static final ModuleSpecID cbjxMsgTransportSpecID = (ModuleSpecID) - ID.create(URI.create("urn:jxta:uuid-DeadBeefDeafBabaFeedBabe000000110106")); - - /** - * static utility factory - */ - private CbJxDefs() {} -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxMessageInfo.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxMessageInfo.java deleted file mode 100644 index 7ca0bd15..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxMessageInfo.java +++ /dev/null @@ -1,389 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.cbjx; - - -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.membership.pse.PSEUtils; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * this class defines the xml document used to store message information - * that is useful for the cbjx endpoint - */ -public class CbJxMessageInfo { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(CbJxMessageInfo.class.getName()); - - /** - * the root element for the information's XML document - */ - private static final String DOCTYPE = "CbJxMessageInfo"; - - /** - * the element name for the peer certificate - */ - private static final String tagPeerCert = "PeerCert"; - - /** - * the element name of the destination address - */ - private static final String tagDestination = "DestinationAddress"; - - /** - * the element name of the source address - */ - private static final String tagSource = "SourceAddress"; - - /** - * the element name for the sourceID of the message - */ - private static final String tagSourceID = "SourceID"; - - /** - * the peer root cert - */ - private Certificate rootCert = null; - - /** - * the destination address of the message - */ - private EndpointAddress destinationAddress = null; - - /** - * the source address of the message - */ - private EndpointAddress sourceAddress = null; - - /** - * the source ID of the sender - */ - private ID sourceID = null; - - /** - * creates a new information object - */ - public CbJxMessageInfo() { - super(); - } - - /** - * creates a new Message information by parsing the given stream - * - * @param stream the InputStream source of the info data - * @throws IOException if the info can't be parsed from the stream - */ - public CbJxMessageInfo(InputStream stream, MimeMediaType type) throws IOException { - super(); - - XMLDocument document = (XMLDocument) - StructuredDocumentFactory.newStructuredDocument(type, stream); - - initialize(document); - } - - /** - * retrieve the peer certificate - * - * @return Certificate the peer certificate - */ - public Certificate getPeerCert() { - return rootCert; - } - - /** - * set the peer certificate - * - * @param cert the peer certificate - */ - public void setPeerCert(Certificate cert) { - rootCert = cert; - } - - /** - * retrieve the destination address of the message - * - * @return String the original destination address of the message - */ - public EndpointAddress getDestinationAddress() { - return destinationAddress; - } - - /** - * set the destination address of the message - * - * @param addr the destination address - */ - public void setDestinationAddress(EndpointAddress addr) { - destinationAddress = addr; - } - - /** - * retrieve the original source address of the message - * - * @return String the original source address of the message - */ - public EndpointAddress getSourceAddress() { - return sourceAddress; - } - - /** - * set the source address of the messsage - * - * @param addr the source address - */ - public void setSourceAddress(EndpointAddress addr) { - sourceAddress = addr; - } - - /** - * retrieve the source id of the message - * - * @return String the source id of the sender - */ - public ID getSourceID() { - return sourceID; - } - - /** - * set the source id of the message - * - * @param src the ID of the sender - */ - public void setSourceID(ID src) { - sourceID = src; - } - - /** - * returns a Document containing the information's document tree - * - * @param asMimeType the desired MIME type for the information rendering - * @return Document the Document containing the information's document tree - */ - public Document getDocument(MimeMediaType asMimeType) { - StructuredDocument document = StructuredDocumentFactory.newStructuredDocument(asMimeType, DOCTYPE); - - Element element; - - if (getPeerCert() == null) { - throw new IllegalStateException("Missing Peer Root Certificate"); - } - - try { - String base64cert = PSEUtils.base64Encode(getPeerCert().getEncoded()); - - element = document.createElement(tagPeerCert, base64cert); - document.appendChild(element); - } catch (Exception e) { - throw new IllegalStateException("Bad root cert! " + e); - } - - if (getSourceID() == null) { - throw new IllegalStateException("Missing Source ID"); - } - - element = document.createElement(tagSourceID, getSourceID().toString()); - document.appendChild(element); - - if (getDestinationAddress() == null) { - throw new IllegalStateException("Missing Destination Address"); - } - - element = document.createElement(tagDestination, getDestinationAddress().toString()); - document.appendChild(element); - - if (getSourceAddress() == null) { - throw new IllegalStateException("Missing Source Address"); - } - - element = document.createElement(tagSource, getSourceAddress().toString()); - document.appendChild(element); - - return document; - } - - /** - * Called to handle elements during parsing. - * - * @param elem Element to parse - * @return true if element was handled, otherwise false. - */ - protected boolean handleElement(XMLElement elem) { - if (elem.getName().equals(tagPeerCert)) { - try { - byte[] cert_der = PSEUtils.base64Decode(new StringReader(elem.getTextValue())); - - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - Certificate cert = cf.generateCertificate(new ByteArrayInputStream(cert_der)); - - setPeerCert(cert); - } catch (Exception e) { - throw new IllegalArgumentException("Bad X509 Cert!"); - } - return true; - } - - if (elem.getName().equals(tagDestination)) { - EndpointAddress destination = new EndpointAddress(elem.getTextValue()); - - setDestinationAddress(destination); - return true; - } - - if (elem.getName().equals(tagSource)) { - EndpointAddress source = new EndpointAddress(elem.getTextValue()); - - setSourceAddress(source); - return true; - } - - if (elem.getName().equals(tagSourceID)) { - - try { - URI sourcePeerURL = new URI(elem.getTextValue().trim()); - PeerID sourcePeerID = (PeerID) IDFactory.fromURI(sourcePeerURL); - - setSourceID(sourcePeerID); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerGroupID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a peer id: " + elem.getTextValue()); - } - return true; - } - - return false; - } - - /** - * internal method to process a document into an advertisement. - * - * @param root where to start. - */ - protected void initialize(Element root) { - - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - - String doctype = doc.getName(); - - if (!doctype.equals(DOCTYPE)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.getName()); - } - } - } - - // sanity checking time. - - if (null == rootCert) { - throw new IllegalArgumentException("Document did not contain a root cert element"); - } - - if (null == destinationAddress) { - throw new IllegalArgumentException("Document did not contain a destination address element"); - } - - if (null == sourceAddress) { - throw new IllegalArgumentException("Document did not contain a source address element"); - } - - if (null == sourceID) { - throw new IllegalArgumentException("Document did not contain a source ID element"); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxMessenger.java deleted file mode 100644 index 5d132c0e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxMessenger.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.cbjx; - - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.impl.endpoint.BlockingMessenger; -import net.jxta.logging.Logging; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * This class is the Messenger used to send CbJx Messages - */ -public class CbJxMessenger extends BlockingMessenger { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(CbJxMessenger.class.getName()); - - /** - * the new destination address computed by the CbJx Endpoint - * this address is of the form jxta:///CbJxService/ - */ - private final EndpointAddress newDestAddr; - - /** - * A string which we can lock on while acquiring new messengers. We don't - * want to lock the whole object. - */ - private final Object acquireMessengerLock = new String("Messenger Acquire Lock"); - - /** - * Cached messenger for sending to {@link #newDestAddr} - */ - private Messenger outBoundMessenger = null; - - /** - * The transport we are working for. - */ - private final CbJxTransport transport; - - /** - * constructor - * - * @param dest the destination address - */ - public CbJxMessenger(CbJxTransport transport, EndpointAddress dest, Object hintIgnored) throws IOException { - this(transport, dest); - } - - /** - * constructor - * - * @param dest the destination address - */ - public CbJxMessenger(CbJxTransport transport, EndpointAddress dest) throws IOException { - - // Do not use self destruction. There's nothing we have that can't just let be GC'ed - super(transport.group.getPeerGroupID(), dest, false); - - this.transport = transport; - - newDestAddr = new EndpointAddress("jxta", dest.getProtocolAddress(), CbJxTransport.cbjxServiceName, null); - - outBoundMessenger = transport.endpoint.getMessengerImmediate(newDestAddr, null); - - if (null == outBoundMessenger) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Could not get messenger for " + newDestAddr); - } - - throw new IOException("Could not get messenger for " + newDestAddr); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void closeImpl() { - synchronized (acquireMessengerLock) { - outBoundMessenger.close(); - outBoundMessenger = null; - } - } - - /** - * {@inheritDoc} - */ - @Override - public EndpointAddress getLogicalDestinationImpl() { - return newDestAddr; - } - - /** - * {@inheritDoc} - *

      - * Since CbJx is a virtual transport and consumes very few resources there - * is no point to doing idle teardown. - */ - @Override - public boolean isIdleImpl() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public void sendMessageBImpl(Message msg, String service, String serviceParam) throws IOException { - msg = msg.clone(); - - EndpointAddress destAddressToUse = getDestAddressToUse(service, serviceParam); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Messenger: sending out " + msg + " to: " + destAddressToUse); - } - - // add the cbjx info to the message - msg = transport.addCryptoInfo(msg, destAddressToUse); - - if (isClosed()) { - IOException failure = new IOException("Messenger was closed, it cannot be used to send messages."); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info(failure.toString()); - } - - throw failure; - } - - // and sends out the message - sendTo( msg ); - } - - /** - * Send a message via the underlying messenger. - * - * @param msg The message to send to the remote peer. - * @throws IOException if there was a problem sending the message. - **/ - void sendTo( Message msg ) throws IOException { - - synchronized (acquireMessengerLock) { - if ((null == outBoundMessenger) || outBoundMessenger.isClosed()) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting messenger for " + newDestAddr); - } - - outBoundMessenger = transport.endpoint.getMessengerImmediate(newDestAddr, null); - - if (outBoundMessenger == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Could not get messenger for " + newDestAddr); - } - - throw new IOException("Underlying messenger could not be repaired"); - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + " to endpoint " + newDestAddr); - } - - // Good we have a messenger. Send the message. - outBoundMessenger.sendMessageB(msg, null, null); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxTransport.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxTransport.java deleted file mode 100644 index 142d33af..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/CbJxTransport.java +++ /dev/null @@ -1,692 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.cbjx; - - -import net.jxta.document.Advertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.TextDocument; -import net.jxta.endpoint.ByteArrayMessageElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.MessageFilterListener; -import net.jxta.endpoint.MessageReceiver; -import net.jxta.endpoint.MessageSender; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.endpoint.WireFormatMessage; -import net.jxta.endpoint.WireFormatMessageFactory; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.endpoint.JxtaMessageMessageElement; -import net.jxta.impl.membership.pse.PSECredential; -import net.jxta.impl.membership.pse.PSEMembershipService; -import net.jxta.impl.membership.pse.PSEUtils; -import net.jxta.logging.Logging; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.ModuleImplAdvertisement; - -import java.io.IOException; -import java.security.cert.Certificate; -import java.security.interfaces.RSAPublicKey; -import java.util.Collections; -import java.util.Iterator; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * A JXTA {@link net.jxta.endpoint.MessageTransport} implementation which - * which provides message verification by examining message signatures. A - * virtual transport, the messages are transfered between peers using some - * other message transport. - */ -public class CbJxTransport implements Module, MessageSender, MessageReceiver, EndpointListener { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(CbJxTransport.class.getName()); - - /** - * the name of the cbjx valid element - */ - public static final String CBJX_MSG_NS = "cbjx"; - - /** - * the name of the cbjx crypto element - */ - static final String CBJX_MSG_INFO = "CryptoInfo"; - - /** - * the name of the cbjx body element - */ - static final String CBJX_MSG_BODY = "Body"; - - /** - * the name of the cbjx body element - */ - static final String CBJX_MSG_SIG = "Signature"; - - /** - * the cbjx protocol name - */ - static final String cbjxProtocolName = "cbjx"; - - /** - * the cbjx service name - */ - static final String cbjxServiceName = "CbJxTransport"; - - /** - * the local peer ID - */ - static PeerID localPeerID = null; - - /** - * the endpoint address of this peer - */ - static EndpointAddress localPeerAddr = null; - - /** - * the peer group to which this module belongs - */ - PeerGroup group = null; - - /** - * the endpoint service in my group - */ - EndpointService endpoint = null; - - /** - * the membership service in my group - */ - PSEMembershipService membership = null; - - /** - * Default constructor - */ - public CbJxTransport() {} - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - this.group = group; - - ModuleImplAdvertisement implAdvertisement = (ModuleImplAdvertisement) impl; - - localPeerID = group.getPeerID(); - - CbJxTransport.localPeerAddr = new EndpointAddress(cbjxProtocolName, group.getPeerID().getUniqueValue().toString(), null - , - null); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring CBJX Message Transport : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tPublic Address : ").append(CbJxTransport.localPeerAddr); - - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] arg) { - - endpoint = group.getEndpointService(); - - if (null == endpoint) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - return START_AGAIN_STALLED; - } - - MembershipService groupMembership = group.getMembershipService(); - - if (null == groupMembership) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a membership service"); - } - return START_AGAIN_STALLED; - } - - if (!(groupMembership instanceof PSEMembershipService)) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("CBJX Transport requires PSE Membership Service"); - } - return -1; - } - - membership = (PSEMembershipService) groupMembership; - - if (endpoint.addMessageTransport(this) == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Transport registration refused"); - } - return -1; - } - - // XXX bondolo@jxta.org 20030526 check for errors - - endpoint.addIncomingMessageListener(this, cbjxServiceName, null); - - endpoint.addIncomingMessageFilterListener(new CbJxInputFilter(), null, null); - // endpoint.addOutgoingMessageFilterListener( new CbJxOutputFilter(), null, null ); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("CbJxTransport started"); - } - - return 0; - } - - /** - * {@inheritDoc} - */ - public void stopApp() { - - if (endpoint != null) { - // FIXME 20030516 bondolo@jxta.org remove filters and listener - - endpoint.removeMessageTransport(this); - endpoint = null; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("CbJxTransport stopped"); - } - } - - /** - * {@inheritDoc} - */ - public EndpointAddress getPublicAddress() { - return CbJxTransport.localPeerAddr; - } - - /** - * {@inheritDoc} - */ - public boolean isConnectionOriented() { - // since we rely on other endpoint protocol we are not connection oriented - return false; - } - - /** - * {@inheritDoc} - */ - public boolean allowsRouting() { - // since we are using the endpoint router - // the endpoint router cannot use our endpoint to send messages - return false; - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - return (EndpointService) endpoint.getInterface(); - } - - /** - * {@inheritDoc} - */ - public Object transportControl(Object operation, Object value) { - return null; - } - - /** - * {@inheritDoc} - */ - public Iterator getPublicAddresses() { - return Collections.singletonList(getPublicAddress()).iterator(); - } - - /** - * {@inheritDoc} - */ - public String getProtocolName() { - return cbjxProtocolName; - } - - /** - * {@inheritDoc} - */ - public Messenger getMessenger(EndpointAddress dest, Object hintIgnored) { - try { - return new CbJxMessenger(this, dest, hintIgnored); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to create cbjx messenger", failed); - } - return null; - } - } - - /** - * {@inheritDoc} - */ - @Deprecated - public boolean ping(EndpointAddress addr) { - Messenger messenger = getMessenger(addr, null); - - boolean reachable = (null != messenger); - - if (messenger != null) { - messenger.close(); - } - - return reachable; - } - - /** - * {@inheritDoc} - */ - public void processIncomingMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("processIncomingMessage : Received message from: " + srcAddr); - } - - // extract the Crypto info from the message - MessageElement cryptoElement = message.getMessageElement(CBJX_MSG_NS, CBJX_MSG_INFO); - - if (cryptoElement == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("processIncomingMessage : No \'" + CBJX_MSG_INFO + "\' in the message"); - } - return; - } - message.removeMessageElement(cryptoElement); - - // the cbjx message info - CbJxMessageInfo cryptoInfo = null; - - try { - cryptoInfo = new CbJxMessageInfo(cryptoElement.getStream(), cryptoElement.getMimeType()); - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING - , - "processIncomingMessage : Couldn\'t retrieve CbJxMessageInfo from \'" + CBJX_MSG_INFO + "\' element", e); - } - return; - } - - Message submessage = checkCryptoInfo(message, cryptoElement, cryptoInfo); - - if (null == submessage) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("processIncomingMessage : discarding message from " + srcAddr); - } - return; - } - - // give back the message to the endpoint - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("processIncomingMessage: delivering " + submessage + " to: " + cryptoInfo.getDestinationAddress()); - } - - endpoint.processIncomingMessage(submessage, cryptoInfo.getSourceAddress(), cryptoInfo.getDestinationAddress()); - } catch (Throwable all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "processIncomingMessage: endpoint failed to demux message", all); - } - } - } - - /** - * add the CryptoInfo into the message - * - * @param submessage the message - * @param destAddress the destination - * @return Message the message with the CbJxMessageInfo added - */ - public Message addCryptoInfo(Message submessage, EndpointAddress destAddress) throws IOException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Building CBJX wrapper for " + submessage); - } - - // Remove all existing CbJx Elements from source - Iterator eachCbJxElement = submessage.getMessageElementsOfNamespace(CbJxTransport.CBJX_MSG_NS); - - while (eachCbJxElement.hasNext()) { - MessageElement aMessageElement = (MessageElement) eachCbJxElement.next(); - - eachCbJxElement.remove(); - } - - Message message = new Message(); - - CbJxMessageInfo cryptoInfo = new CbJxMessageInfo(); - - // set the source Id of the message - cryptoInfo.setSourceID(localPeerID); - cryptoInfo.setSourceAddress(localPeerAddr); - cryptoInfo.setDestinationAddress(destAddress); - - // add the root cert into the message info - PSECredential cred = (PSECredential) membership.getDefaultCredential(); - - if (null == cred) { - throw new IOException("No authentication available for message signing."); - } - - Certificate cert = cred.getCertificate(); - - cryptoInfo.setPeerCert(cert); - - // compute the signature of the message body - TextDocument infoDoc = (TextDocument) cryptoInfo.getDocument(MimeMediaType.XMLUTF8); - byte[] infoSignature = null; - - try { - infoSignature = PSEUtils.computeSignature(CbJxDefs.signAlgoName, cred.getPrivateKey(), infoDoc.getStream()); - } catch (Throwable e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "failed to sign " + submessage, e); - } - return null; - } - - // add the cbjx:CryptoInfo into the message - MessageElement infoSigElement = new ByteArrayMessageElement(CBJX_MSG_SIG, MimeMediaType.AOS, infoSignature, null); - - // add the cbjx:CryptoInfo into the message - MessageElement cryptoInfoElement = new TextDocumentMessageElement(CBJX_MSG_INFO, infoDoc, infoSigElement); - - message.addMessageElement(CBJX_MSG_NS, cryptoInfoElement); - - // Compute the signature of the encapsulated message and append it to - // the container. - - // serialize the container - WireFormatMessage subserial = WireFormatMessageFactory.toWire(submessage, WireFormatMessageFactory.DEFAULT_WIRE_MIME, null); - - // calculate the signature - byte[] bodySignature = null; - - try { - bodySignature = PSEUtils.computeSignature(CbJxDefs.signAlgoName, cred.getPrivateKey(), subserial.getStream()); - } catch (Throwable e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "failed to sign" + submessage, e); - } - return null; - } - - subserial = null; - - // Make the signature into an element - MessageElement bodySigElement = new ByteArrayMessageElement(CBJX_MSG_SIG, MimeMediaType.AOS, bodySignature, null); - - // Add the encapsulated body into the container message. - message.addMessageElement(CBJX_MSG_NS - , - new JxtaMessageMessageElement(CBJX_MSG_BODY, new MimeMediaType("application/x-jxta-msg"), submessage - , - bodySigElement)); - - return message; - } - - public Message checkCryptoInfo(Message message, MessageElement cryptoElement, CbJxMessageInfo cryptoInfo) { - - // extract the body element from the message - JxtaMessageMessageElement bodyElement = (JxtaMessageMessageElement) message.getMessageElement(CBJX_MSG_NS, CBJX_MSG_BODY); - - if (null == bodyElement) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("No \'" + CBJX_MSG_BODY + "\' in " + message); - } - return null; - } - message.removeMessageElement(bodyElement); - - // extract the peer certificate - Certificate peerCert = cryptoInfo.getPeerCert(); - - // and from it the public key - // the public key from the message - RSAPublicKey publicKey = (RSAPublicKey) peerCert.getPublicKey(); - - // check the cert validity - try { - peerCert.verify(publicKey); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Invalid peer cert", e); - } - return null; - } - - // check the cbid - try { - net.jxta.impl.id.CBID.PeerID srcPeerID = (net.jxta.impl.id.CBID.PeerID) cryptoInfo.getSourceID(); - - byte[] pub_der = peerCert.getPublicKey().getEncoded(); - net.jxta.impl.id.CBID.PeerID genID = (net.jxta.impl.id.CBID.PeerID) IDFactory.newPeerID(group.getPeerGroupID() - , - pub_der); - - if (!srcPeerID.getUUID().equals(genID.getUUID())) { - // the cbid is not valid. Discard the message - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("CBID of " + message + " is not valid : " + srcPeerID + " != " + genID); - } - return null; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("CBID of the message is valid"); - } - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to verify cbid", e); - } - return null; - } - - // verify the signature of the cryptinfo message - try { - boolean valid = PSEUtils.verifySignature(CbJxDefs.signAlgoName, peerCert, cryptoElement.getSignature().getBytes(false) - , - cryptoElement.getStream()); - - if (!valid) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed to verify the signature of cryptinfo for " + message); - } - return null; - } - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to verify the signature of cryptinfo for " + message, e); - } - return null; - } - - // then verify the signature - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("verifying signature"); - } - - // verify the signature of the message - try { - boolean valid = PSEUtils.verifySignature(CbJxDefs.signAlgoName, peerCert, bodyElement.getSignature().getBytes(false) - , - bodyElement.getStream()); - - if (!valid) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("failed to verify the signature of " + message); - } - return null; - } - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failed to verify the signature of " + message, e); - } - return null; - } - - // the message is valid - return bodyElement.getMessage(); - } - - /** - * this class filters incoming messages. - * it checks if messages are valid and if not discard them - */ - public class CbJxInputFilter implements MessageFilterListener { - public CbJxInputFilter() { - super(); - } - - /** - * {@inheritDoc} - */ - public Message filterMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - if (dstAddr.getProtocolAddress().equals(getProtocolName())) { - // extract the Crypto info from the message - MessageElement cryptoElement = message.getMessageElement(CBJX_MSG_NS, CBJX_MSG_INFO); - - if (cryptoElement == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No \'" + CBJX_MSG_INFO + "\' in the message"); - } - return null; - } - message.removeMessageElement(cryptoElement); - - // the cbjx message info - CbJxMessageInfo cryptoInfo = null; - - try { - cryptoInfo = new CbJxMessageInfo(cryptoElement.getStream(), cryptoElement.getMimeType()); - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Couldn\'t retrieve CbJxMessageInfo from \'" + CBJX_MSG_INFO + "\' element", e); - } - return null; - } - - return checkCryptoInfo(message, cryptoElement, cryptoInfo); - } - - return message; - } - } - - - /** - * this class filters all outgoing messages that are not sent with - * messengers. (that is propagate messages). It adds CbJxInformation - * into to messages. - */ - public class CbJxOutputFilter implements MessageFilterListener { - - /** - * Default constructor - */ - public CbJxOutputFilter() { - super(); - } - - /** - * {@inheritDoc} - */ - public Message filterMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - Message msg = message.clone(); - - if (null == msg.getMessageElement(CBJX_MSG_NS, CBJX_MSG_INFO)) { - try { - msg = addCryptoInfo(msg, dstAddr); - } catch (IOException failed) { - return null; - } - } - - return msg; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/package.html deleted file mode 100644 index 4d04e184..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/cbjx/package.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.endpoint.MessageTransport} implementation which - which provides message verification by examining message signatures. A - virtual transport, the messages are transfered between peers using some - other message transport. - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/ConditionalEndpointMeterBuildSettings.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/ConditionalEndpointMeterBuildSettings.java deleted file mode 100644 index c502900f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/ConditionalEndpointMeterBuildSettings.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * The Sun Project JXTA(TM) Software License - * - * Copyright (c) 2001-2006 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: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at https://jxta.dev.java.net. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * https://jxta.dev.java.net/ - * - * This license is based on the BSD license adopted by the Apache Foundation. - * - */ - - -/* **** THIS IS A GENERATED FILE. DO NOT EDIT. **** */ - -package net.jxta.impl.endpoint.endpointMeter; - -import java.util.ResourceBundle; -import net.jxta.impl.meter.*; - -public class ConditionalEndpointMeterBuildSettings { - public static boolean isRuntimeMetering() { - boolean runtimeMetering = false; - - try { - ResourceBundle userResourceBundle = ResourceBundle.getBundle( "net.jxta.user" ); - String meteringProperty = "net.jxta.meter.conditionalEndpointMetering"; - String meteringValue = userResourceBundle.getString( meteringProperty ); - runtimeMetering = "on".equalsIgnoreCase( meteringValue ); - } catch (Exception ignored) { - } - - return runtimeMetering; - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointMeter.java deleted file mode 100644 index b3f4614a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointMeter.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import net.jxta.peer.*; -import net.jxta.peergroup.*; -import net.jxta.endpoint.*; -import net.jxta.impl.endpoint.*; - -import java.net.*; -import java.util.*; - - -/** - * Aggregate Meter for Endpoint Monitoring - **/ -public class EndpointMeter { - - private EndpointMetric total; - private EndpointMetric delta; - - public EndpointMeter() { - total = new EndpointMetric(); - } - - public EndpointMetric getCumulativeMetrics() { - total.setEndpointUpTime(System.currentTimeMillis() - total.getEndpointStartTime()); - return total; - } - - public synchronized EndpointMetric collectMetrics() { - if (delta != null) { - delta.setEndpointUpTime(System.currentTimeMillis() - total.getEndpointStartTime()); - } - - EndpointMetric oldDelta = delta; - - delta = null; - - return oldDelta; - } - - public void invalidIncomingMessage() { - if (delta == null) { - createDeltaMetric(); - } - - delta.invalidIncomingMessage(); - total.invalidIncomingMessage(); - } - - public void noListenerForIncomingMessage() { - if (delta == null) { - createDeltaMetric(); - } - - delta.noListenerForIncomingMessage(); - total.noListenerForIncomingMessage(); - } - - public void errorProcessingIncomingMessage() { - if (delta == null) { - createDeltaMetric(); - } - - delta.errorProcessingIncomingMessage(); - total.errorProcessingIncomingMessage(); - } - - public void noDestinationAddressForDemuxMessage() { - if (delta == null) { - createDeltaMetric(); - } - - delta.noDestinationAddressForDemuxMessage(); - total.noDestinationAddressForDemuxMessage(); - } - - public void noSourceAddressForDemuxMessage() { - if (delta == null) { - createDeltaMetric(); - } - - delta.noSourceAddressForDemuxMessage(); - total.noSourceAddressForDemuxMessage(); - } - - public void discardedLoopbackDemuxMessage() { - if (delta == null) { - createDeltaMetric(); - } - - delta.discardedLoopbackDemuxMessage(); - total.discardedLoopbackDemuxMessage(); - } - - public void incomingMessageFilteredOut() { - if (delta == null) { - createDeltaMetric(); - } - - delta.incomingMessageFilteredOut(); - total.incomingMessageFilteredOut(); - } - - public void incomingMessageSentToEndpointListener() { - if (delta == null) { - createDeltaMetric(); - } - - delta.incomingMessageSentToEndpointListener(); - total.incomingMessageSentToEndpointListener(); - } - - public void demuxMessageProcessed() { - if (delta == null) { - createDeltaMetric(); - } - - delta.demuxMessageProcessed(); - total.demuxMessageProcessed(); - } - - private void createDeltaMetric() { - delta = new EndpointMetric(total); - } - - @Override - public String toString() { - return "EndpointMeter()"; - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointMeterBuildSettings.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointMeterBuildSettings.java deleted file mode 100644 index dc6809b4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointMeterBuildSettings.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * The Sun Project JXTA(TM) Software License - * - * Copyright (c) 2001-2006 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: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at https://jxta.dev.java.net. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * https://jxta.dev.java.net/ - * - * This license is based on the BSD license adopted by the Apache Foundation. - * - */ - - -/* **** THIS IS A GENERATED FILE. DO NOT EDIT. **** */ - -package net.jxta.impl.endpoint.endpointMeter; - -import net.jxta.impl.meter.*; - -public interface EndpointMeterBuildSettings extends MeterBuildSettings { - public static final boolean ENDPOINT_METERING = ConditionalEndpointMeterBuildSettings.isRuntimeMetering(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointMetric.java deleted file mode 100644 index ee7456a5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointMetric.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import net.jxta.endpoint.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; - -import java.util.*; - - -/** - * Aggregate Metric for Endpoint Monitoring - **/ -public class EndpointMetric implements DocumentSerializable { - private long endpointStartTime; - private long endpointUpTime; - private int invalidIncomingMessage; - private int noListenerForIncomingMessage; - private int errorProcessingIncomingMessage; - private int noDestinationAddressForDemuxMessage; - private int noSourceAddressForDemuxMessage; - private int discardedLoopbackDemuxMessage; - private int incomingMessageFilteredOut; - private int incomingMessageSentToEndpointListener; - private int demuxMessageProcessed; - - public EndpointMetric() { - endpointStartTime = System.currentTimeMillis(); - } - - public EndpointMetric(EndpointMetric prototype) { - endpointStartTime = prototype.endpointStartTime; - } - - void invalidIncomingMessage() { - invalidIncomingMessage++; - } - - void noListenerForIncomingMessage() { - noListenerForIncomingMessage++; - } - - void errorProcessingIncomingMessage() { - errorProcessingIncomingMessage++; - } - - void noDestinationAddressForDemuxMessage() { - noDestinationAddressForDemuxMessage++; - } - - void noSourceAddressForDemuxMessage() { - noSourceAddressForDemuxMessage++; - } - - void discardedLoopbackDemuxMessage() { - discardedLoopbackDemuxMessage++; - } - - void incomingMessageFilteredOut() { - incomingMessageFilteredOut++; - } - - void incomingMessageSentToEndpointListener() { - incomingMessageSentToEndpointListener++; - } - - void demuxMessageProcessed() { - demuxMessageProcessed++; - } - - void setEndpointUpTime(long endpointUpTime) { - this.endpointUpTime = endpointUpTime; - } - - /** Get the time this Endpoint was created, essentially the boot time of the PeerGroup **/ - public long getEndpointStartTime() { - return endpointStartTime; - } - - /** Get the time this Endpoint has been up **/ - public long getEndpointUpTime() { - return endpointUpTime; - } - - /** The number of messages received that had invalid formats **/ - public int getInvalidIncomingMessage() { - return invalidIncomingMessage; - } - - /** The number of messages received that had no listeners **/ - public int getNoListenerForIncomingMessage() { - return noListenerForIncomingMessage; - } - - /** The number of messages whose local listeners threw exceptions **/ - public int getErrorProcessingIncomingMessage() { - return errorProcessingIncomingMessage; - } - - /** The number of messages that couldn't be demuxed because there was no destination address **/ - public int getNoDestinationAddressForDemuxMessage() { - return noDestinationAddressForDemuxMessage; - } - - /** The number of messages that couldn't be demuxed because there was no source address **/ - public int getNoSourceAddressForDemuxMessage() { - return noSourceAddressForDemuxMessage; - } - - /** The number of messages that were discarded because of loopback detection **/ - public int getDiscardedLoopbackDemuxMessage() { - return discardedLoopbackDemuxMessage; - } - - /** The number of messages that were discarded because of filtering **/ - public int getIncomingMessageFilteredOut() { - return incomingMessageFilteredOut; - } - - /** The number of messages that sent to registered listeners **/ - public int getIncomingMessageSentToEndpointListener() { - return incomingMessageSentToEndpointListener; - } - - /** The number of messages that were processed through demux **/ - public int getDemuxMessageProcessed() { - return demuxMessageProcessed; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - if (endpointStartTime != 0) { - DocumentSerializableUtilities.addLong(element, "endpointStartTime", endpointStartTime); - } - if (endpointUpTime != 0) { - DocumentSerializableUtilities.addLong(element, "endpointUpTime", endpointUpTime); - } - if (invalidIncomingMessage != 0) { - DocumentSerializableUtilities.addInt(element, "invalidIncomingMessage", invalidIncomingMessage); - } - if (noListenerForIncomingMessage != 0) { - DocumentSerializableUtilities.addInt(element, "noListenerForIncomingMessage", noListenerForIncomingMessage); - } - if (errorProcessingIncomingMessage != 0) { - DocumentSerializableUtilities.addInt(element, "errorProcessingIncomingMessage", errorProcessingIncomingMessage); - } - if (noDestinationAddressForDemuxMessage != 0) { - DocumentSerializableUtilities.addInt(element, "noDestinationAddressForDemuxMessage" - , - noDestinationAddressForDemuxMessage); - } - if (noSourceAddressForDemuxMessage != 0) { - DocumentSerializableUtilities.addInt(element, "noSourceAddressForDemuxMessage", noSourceAddressForDemuxMessage); - } - if (discardedLoopbackDemuxMessage != 0) { - DocumentSerializableUtilities.addInt(element, "discardedLoopbackDemuxMessage", discardedLoopbackDemuxMessage); - } - if (incomingMessageFilteredOut != 0) { - DocumentSerializableUtilities.addInt(element, "incomingMessageFilteredOut", incomingMessageFilteredOut); - } - if (incomingMessageSentToEndpointListener != 0) { - DocumentSerializableUtilities.addInt(element, "incomingMessageSentToEndpointListener" - , - incomingMessageSentToEndpointListener); - } - if (demuxMessageProcessed != 0) { - DocumentSerializableUtilities.addInt(element, "demuxMessageProcessed", demuxMessageProcessed); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("endpointStartTime")) { - endpointStartTime = DocumentSerializableUtilities.getLong(childElement); - } - if (tagName.equals("endpointUpTime")) { - endpointUpTime = DocumentSerializableUtilities.getLong(childElement); - } - if (tagName.equals("invalidIncomingMessage")) { - invalidIncomingMessage = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("noListenerForIncomingMessage")) { - noListenerForIncomingMessage = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("errorProcessingIncomingMessage")) { - errorProcessingIncomingMessage = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("noDestinationAddressForDemuxMessage")) { - noDestinationAddressForDemuxMessage = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("noSourceAddressForDemuxMessage")) { - noSourceAddressForDemuxMessage = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("invalidIncomingMessage")) { - invalidIncomingMessage = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("discardedLoopbackDemuxMessage")) { - discardedLoopbackDemuxMessage = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("incomingMessageFilteredOut")) { - incomingMessageFilteredOut = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("incomingMessageSentToEndpointListener")) { - incomingMessageSentToEndpointListener = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("demuxMessageProcessed")) { - demuxMessageProcessed = DocumentSerializableUtilities.getInt(childElement); - } - } - - } - - public void mergeMetrics(EndpointMetric other) { - if (other == null) { - return; - } - - endpointStartTime = other.endpointStartTime; - - if (other.endpointUpTime != 0) { - endpointUpTime = other.endpointUpTime; - } - - invalidIncomingMessage += other.invalidIncomingMessage; - noListenerForIncomingMessage += other.noListenerForIncomingMessage; - errorProcessingIncomingMessage += other.errorProcessingIncomingMessage; - noDestinationAddressForDemuxMessage += other.noDestinationAddressForDemuxMessage; - noSourceAddressForDemuxMessage += other.noSourceAddressForDemuxMessage; - discardedLoopbackDemuxMessage += other.discardedLoopbackDemuxMessage; - incomingMessageSentToEndpointListener += other.incomingMessageSentToEndpointListener; - demuxMessageProcessed += other.demuxMessageProcessed; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointServiceMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointServiceMetric.java deleted file mode 100644 index 720eb008..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointServiceMetric.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import net.jxta.document.Element; -import net.jxta.document.TextElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.id.IDFactory; -import net.jxta.meter.MonitorResources; -import net.jxta.meter.ServiceMetric; -import net.jxta.platform.ModuleClassID; -import net.jxta.util.documentSerializable.DocumentSerializableUtilities; -import net.jxta.util.documentSerializable.DocumentSerializationException; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedList; - - -/** - * Basic Service Metric EndpointService Monitoring - */ -public class EndpointServiceMetric implements ServiceMetric { - private LinkedList inboundMetrics = new LinkedList(); - private LinkedList outboundMetrics = new LinkedList(); - private LinkedList propagationMetrics = new LinkedList(); - private EndpointMetric endpointMetric; - private ModuleClassID moduleClassID = MonitorResources.endpointServiceMonitorClassID; - - public EndpointServiceMetric() {} - - public EndpointServiceMetric(ModuleClassID moduleClassID) { - this.moduleClassID = moduleClassID; - } - - public void init(ModuleClassID moduleClassID) { - this.moduleClassID = moduleClassID; - } - - public ModuleClassID getModuleClassID() { - return moduleClassID; - } - - void addInboundMetric(InboundMetric inboundMetric) { - inboundMetrics.add(inboundMetric); - } - - public Iterator getInboundMetrics() { - return inboundMetrics.iterator(); - } - - public InboundMetric getInboundMetric(String serviceName, String serviceParam) { - for (InboundMetric inboundMetric : inboundMetrics) { - if (inboundMetric.matches(serviceName, serviceParam)) { - return inboundMetric; - } - } - - return null; - } - - public Iterator getPropagationMetrics() { - return propagationMetrics.iterator(); - } - - public PropagationMetric getPropagationMetric(String serviceName, String serviceParam) { - for (PropagationMetric propagationMetric : propagationMetrics) { - if (propagationMetric.matches(serviceName, serviceParam)) { - return propagationMetric; - } - } - - return null; - } - - void addPropagationMetric(PropagationMetric propagationMetric) { - propagationMetrics.add(propagationMetric); - } - - void addOutboundMetric(OutboundMetric outboundMetric) { - outboundMetrics.add(outboundMetric); - } - - public Iterator getOutboundMetrics() { - return outboundMetrics.iterator(); - } - - public OutboundMetric getOutboundMetric(EndpointAddress endpointAddress) { - for (OutboundMetric outboundMetric : outboundMetrics) { - if (outboundMetric.matches(endpointAddress)) { - return outboundMetric; - } - } - - return null; - } - - public EndpointMetric getEndpointMetric() { - return endpointMetric; - } - - void setEndpointMetric(EndpointMetric endpointMetric) { - this.endpointMetric = endpointMetric; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - for (Object outboundMetric1 : outboundMetrics) { - OutboundMetric outboundMetric = (OutboundMetric) outboundMetric1; - - DocumentSerializableUtilities.addDocumentSerializable(element, "outboundMetric", outboundMetric); - } - for (Object inboundMetric1 : inboundMetrics) { - InboundMetric inboundMetric = (InboundMetric) inboundMetric1; - - DocumentSerializableUtilities.addDocumentSerializable(element, "inboundMetric", inboundMetric); - } - for (Object propagationMetric1 : propagationMetrics) { - PropagationMetric propagationMetric = (PropagationMetric) propagationMetric1; - - DocumentSerializableUtilities.addDocumentSerializable(element, "propagationMetric", propagationMetric); - } - if (endpointMetric != null) { - DocumentSerializableUtilities.addDocumentSerializable(element, "endpointMetric", endpointMetric); - } - - if (moduleClassID != null) { - DocumentSerializableUtilities.addString(element, "moduleClassID", moduleClassID.toString()); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("inboundMetric")) { - InboundMetric inboundMetric = (InboundMetric) DocumentSerializableUtilities.getDocumentSerializable(childElement - , - InboundMetric.class); - - inboundMetrics.add(inboundMetric); - } - if (tagName.equals("outboundMetric")) { - OutboundMetric outboundMetric = (OutboundMetric) DocumentSerializableUtilities.getDocumentSerializable( - childElement, OutboundMetric.class); - - outboundMetrics.add(outboundMetric); - } - if (tagName.equals("propagationMetric")) { - PropagationMetric propagationMetric = (PropagationMetric) DocumentSerializableUtilities.getDocumentSerializable( - childElement, PropagationMetric.class); - - propagationMetrics.add(propagationMetric); - } - if (tagName.equals("endpointMetric")) { - endpointMetric = (EndpointMetric) DocumentSerializableUtilities.getDocumentSerializable(childElement - , - EndpointMetric.class); - } - try { - if (tagName.equals("moduleClassID")) { - moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI(DocumentSerializableUtilities.getString(childElement))); - } - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Can't decipher ModuleClassID", jex); - } - } - } - - public void mergeMetrics(ServiceMetric otherOne) { - mergeMetrics(otherOne, true, true, true, true); - } - - /** - * Make a deep copy of this metric only including the portions designated in the Filter - * The resulting metric is Safe to modify without danger to the underlying Monitor Metrics - * - * @param endpointServiceMonitorFilter Filter designates constituant parts to be included - * @return a copy of this metric with references to the designated parts - */ - public EndpointServiceMetric deepCopy(EndpointServiceMonitorFilter endpointServiceMonitorFilter) { - EndpointServiceMetric serviceMetric = new EndpointServiceMetric(); - - serviceMetric.moduleClassID = moduleClassID; - - serviceMetric.mergeMetrics(this, true, endpointServiceMonitorFilter.isIncludeInboundMetrics() - , - endpointServiceMonitorFilter.isIncludeOutboundMetrics(), endpointServiceMonitorFilter.isIncludePropagateMetrics()); - return serviceMetric; - } - - public void mergeMetrics(ServiceMetric otherOne, boolean includeEndpointMetrics, boolean includeInboundMetrics, boolean includeOutboundEndpointMetrics, boolean includePropagationMetrics) { - EndpointServiceMetric otherEndpointServiceMetric = (EndpointServiceMetric) otherOne; - - if (includeEndpointMetrics) { - EndpointMetric otherEndpointMetric = otherEndpointServiceMetric.getEndpointMetric(); - - if ((endpointMetric == null) && (otherEndpointMetric != null)) { - endpointMetric = new EndpointMetric(otherEndpointMetric); - } - - if (otherEndpointMetric != null) { - endpointMetric.mergeMetrics(otherEndpointMetric); - } - } - - if (includeInboundMetrics) { - for (Iterator i = otherEndpointServiceMetric.getInboundMetrics(); i.hasNext();) { - InboundMetric otherInboundMetric = i.next(); - InboundMetric inboundMetric = getInboundMetric(otherInboundMetric.getServiceName() - , - otherInboundMetric.getServiceParameter()); - - if (inboundMetric == null) { - inboundMetric = new InboundMetric(otherInboundMetric); - addInboundMetric(inboundMetric); - } - - inboundMetric.mergeMetrics(otherInboundMetric); - } - } - - if (includeOutboundEndpointMetrics) { - for (Iterator i = otherEndpointServiceMetric.getOutboundMetrics(); i.hasNext();) { - OutboundMetric otherOutboundMetric = i.next(); - OutboundMetric outboundMetric = getOutboundMetric(otherOutboundMetric.getEndpointAddress()); - - if (outboundMetric == null) { - outboundMetric = new OutboundMetric(otherOutboundMetric); - addOutboundMetric(outboundMetric); - } - - outboundMetric.mergeMetrics(otherOutboundMetric); - } - } - - if (includeOutboundEndpointMetrics) { - for (Iterator i = otherEndpointServiceMetric.getPropagationMetrics(); i.hasNext();) { - PropagationMetric otherPropagationMetric = i.next(); - PropagationMetric propagationMetric = getPropagationMetric(otherPropagationMetric.getServiceName() - , - otherPropagationMetric.getServiceParameter()); - - if (propagationMetric == null) { - propagationMetric = new PropagationMetric(otherPropagationMetric); - addPropagationMetric(propagationMetric); - } - - propagationMetric.mergeMetrics(otherPropagationMetric); - } - } - } - - /** - * Make a shallow copy of this metric only including the portions designated in the Filter - *

      Note: since this is a shallow copy it is dangerous to modify the submetrics - * - * @param endpointServiceMonitorFilter Filter designates constituant parts to be included - * @return a copy of this metric with references to the designated parts - */ - public EndpointServiceMetric shallowCopy(EndpointServiceMonitorFilter endpointServiceMonitorFilter) { - EndpointServiceMetric endpointServiceMetric = new EndpointServiceMetric(moduleClassID); - - endpointServiceMetric.endpointMetric = endpointMetric; - - if (endpointServiceMonitorFilter.isIncludeInboundMetrics()) { - for (Iterator i = getInboundMetrics(); i.hasNext();) { - InboundMetric inboundMetric = i.next(); - - endpointServiceMetric.addInboundMetric(inboundMetric); - } - } - - if (endpointServiceMonitorFilter.isIncludeOutboundMetrics()) { - for (Iterator i = getOutboundMetrics(); i.hasNext();) { - OutboundMetric outboundMetric = i.next(); - - endpointServiceMetric.addOutboundMetric(outboundMetric); - } - } - - if (endpointServiceMonitorFilter.isIncludePropagateMetrics()) { - for (Iterator i = getPropagationMetrics(); i.hasNext();) { - PropagationMetric propagationMetric = i.next(); - - endpointServiceMetric.addPropagationMetric(propagationMetric); - } - } - - return endpointServiceMetric; - } - - public void diffMetrics(ServiceMetric otherOne) { - throw new RuntimeException("Not Supported"); - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointServiceMonitor.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointServiceMonitor.java deleted file mode 100644 index fac60ea8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointServiceMonitor.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import java.util.Hashtable; -import java.util.Map; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.impl.meter.GenericServiceMonitor; -import net.jxta.meter.ServiceMetric; -import net.jxta.meter.ServiceMonitorFilter; - - -/** - * Standard EndpointService Monitor - **/ -public class EndpointServiceMonitor extends GenericServiceMonitor { - private EndpointServiceMetric cumulativeEndpointServiceMetric; - private final Map inboundMeters = new Hashtable(); - private final Map outboundMeters = new Hashtable(); - private final Map propagationMeters = new Hashtable(); - private final EndpointMeter endpointMeter = new EndpointMeter(); - - public EndpointServiceMonitor() {} - - /** - * {@inheritDoc} - */ - @Override - protected void init() { - cumulativeEndpointServiceMetric = (EndpointServiceMetric) getCumulativeServiceMetric(); - cumulativeEndpointServiceMetric.setEndpointMetric(endpointMeter.getCumulativeMetrics()); - } - - public EndpointMeter getEndpointMeter() { - return endpointMeter; - } - - public synchronized InboundMeter getInboundMeter(String serviceName, String serviceParam) { - String address = serviceName; - - if (null != serviceParam) { - address += "/" + serviceParam; - } - - InboundMeter inboundMeter = inboundMeters.get(address); - - if (inboundMeter == null) { - inboundMeter = new InboundMeter(serviceName, serviceParam); - inboundMeters.put(address, inboundMeter); - cumulativeEndpointServiceMetric.addInboundMetric(inboundMeter.getCumulativeMetrics()); - } - - return inboundMeter; - } - - public synchronized PropagationMeter getPropagationMeter(String serviceName, String serviceParam) { - String address = serviceName; - - if (null != serviceParam) { - address += "/" + serviceParam; - } - - PropagationMeter propagationMeter = propagationMeters.get(address); - - if (propagationMeter == null) { - propagationMeter = new PropagationMeter(serviceName, serviceParam); - propagationMeters.put(address, propagationMeter); - cumulativeEndpointServiceMetric.addPropagationMetric(propagationMeter.getCumulativeMetrics()); - } - - return propagationMeter; - } - - public synchronized OutboundMeter getOutboundMeter(EndpointAddress endpointAddress) { - OutboundMeter outboundMeter = outboundMeters.get(endpointAddress); - - if (outboundMeter == null) { - outboundMeter = new OutboundMeter(endpointAddress); - cumulativeEndpointServiceMetric.addOutboundMetric(outboundMeter.getCumulativeMetrics()); - outboundMeters.put(endpointAddress, outboundMeter); - } - - return outboundMeter; - } - - /** - * {@inheritDoc} - */ - @Override - public ServiceMetric getServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime, int pulseIndex, long reportRate) { - int deltaReportRateIndex = monitorManager.getReportRateIndex(reportRate); - EndpointServiceMetric origEndpointServiceMetric = (EndpointServiceMetric) deltaServiceMetrics[deltaReportRateIndex]; - - if (origEndpointServiceMetric == null) { - return null; - } - - EndpointServiceMonitorFilter endpointServiceMonitorFilter = (EndpointServiceMonitorFilter) serviceMonitorFilter; - - return origEndpointServiceMetric.shallowCopy(endpointServiceMonitorFilter); - } - - /** - * {@inheritDoc} - */ - @Override - public ServiceMetric getCumulativeServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime) { - EndpointServiceMetric origEndpointServiceMetric = (EndpointServiceMetric) cumulativeServiceMetric; - EndpointServiceMonitorFilter endpointServiceMonitorFilter = (EndpointServiceMonitorFilter) serviceMonitorFilter; - - return origEndpointServiceMetric.deepCopy(endpointServiceMonitorFilter); - } - - /** - * {@inheritDoc} - */ - @Override - protected ServiceMetric collectServiceMetrics() { - EndpointServiceMetric endpointServiceMetric = (EndpointServiceMetric) createServiceMetric(); - - boolean anyData = false; - - for (InboundMeter inboundMeter : inboundMeters.values()) { - InboundMetric inboundMetric = inboundMeter.collectMetrics(); // clears delta from meter - - if (inboundMetric != null) { - endpointServiceMetric.addInboundMetric(inboundMetric); - anyData = true; - } - } - - for (OutboundMeter outboundMeter : outboundMeters.values()) { - OutboundMetric outboundMetric = outboundMeter.collectMetrics(); // clears delta from meter - - if (outboundMetric != null) { - endpointServiceMetric.addOutboundMetric(outboundMetric); - anyData = true; - } - } - - for (PropagationMeter propagationMeter : propagationMeters.values()) { - PropagationMetric propagationMetric = propagationMeter.collectMetrics(); // clears delta from meter - - if (propagationMetric != null) { - endpointServiceMetric.addPropagationMetric(propagationMetric); - anyData = true; - } - } - - EndpointMetric endpointMetric = endpointMeter.collectMetrics(); - - if (endpointMetric != null) { - endpointServiceMetric.setEndpointMetric(endpointMetric); - anyData = true; - } - - if (anyData) { - return endpointServiceMetric; - } else { - return null; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointServiceMonitorFilter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointServiceMonitorFilter.java deleted file mode 100644 index 109dbca6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/EndpointServiceMonitorFilter.java +++ /dev/null @@ -1,158 +0,0 @@ - - -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import java.net.*; -import java.util.*; - -import net.jxta.meter.*; -import net.jxta.platform.*; -import net.jxta.document.*; -import net.jxta.id.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.platform.*; -import net.jxta.util.*; - - -public class EndpointServiceMonitorFilter implements ServiceMonitorFilter { - // private boolean reportAllEndpoints = true; - private ModuleClassID moduleClassID = MonitorResources.endpointServiceMonitorClassID; - - private boolean includeOutboundMetrics = true; - private boolean includeInboundMetrics = true; - private boolean includePropagateMetrics = true; - - public EndpointServiceMonitorFilter() {} - - public EndpointServiceMonitorFilter(boolean includeInboundMetrics, boolean includeOutboundMetrics, boolean includePropagateMetrics) { - this.includeInboundMetrics = includeInboundMetrics; - this.includeOutboundMetrics = includeOutboundMetrics; - this.includePropagateMetrics = includePropagateMetrics; - } - - public void init(ModuleClassID moduleClassID) { - this.moduleClassID = moduleClassID; - } - - public void setIncludeInboundMetrics(boolean metrics) { - includeInboundMetrics = metrics; - } - - public void setIncludeOutboundMetrics(boolean metrics) { - includeOutboundMetrics = metrics; - } - - public void setIncludePropagateMetrics(boolean metrics) { - includePropagateMetrics = metrics; - } - - public boolean isIncludeOutboundMetrics() { - return includeOutboundMetrics; - } - - public boolean isIncludeInboundMetrics() { - return includeInboundMetrics; - } - - public boolean isIncludePropagateMetrics() { - return includePropagateMetrics; - } - - public ModuleClassID getModuleClassID() { - return moduleClassID; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - DocumentSerializableUtilities.addBoolean(element, "includeOutboundMetrics", includeOutboundMetrics); - DocumentSerializableUtilities.addBoolean(element, "includeInboundMetrics", includeInboundMetrics); - DocumentSerializableUtilities.addBoolean(element, "includePropagateMetrics", includePropagateMetrics); - if (moduleClassID != null) { - DocumentSerializableUtilities.addString(element, "moduleClassID", moduleClassID.toString()); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("includeOutboundMetrics")) { - includeOutboundMetrics = DocumentSerializableUtilities.getBoolean(childElement); - } - if (tagName.equals("includeInboundMetrics")) { - includeInboundMetrics = DocumentSerializableUtilities.getBoolean(childElement); - } - if (tagName.equals("includePropagateMetrics")) { - includePropagateMetrics = DocumentSerializableUtilities.getBoolean(childElement); - } - - if (tagName.equals("moduleClassID")) { - try { - moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI(DocumentSerializableUtilities.getString(childElement))); - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Couldn't uderstand ModuleClassID", jex); - } - } - } - } - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/InboundMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/InboundMeter.java deleted file mode 100644 index 48dffd20..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/InboundMeter.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import net.jxta.endpoint.Message; - - -/** - * Meter corresponding to a registered EndpointListener - **/ -public class InboundMeter { - private String serviceName; - private String serviceParameter; - - private InboundMetric totals; - private InboundMetric delta; - - public InboundMeter(String serviceName, String serviceParameter) { - this.serviceName = serviceName; - this.serviceParameter = serviceParameter; - this.totals = new InboundMetric(this); - } - - private void createDeltaMetric() { - delta = new InboundMetric(this); - } - - public void inboundMessageQueued(Message message) { - if (delta == null) { - createDeltaMetric(); - } - - delta.inboundMessageQueued(message); - totals.inboundMessageQueued(message); - } - - public void inboundMessageDropped(Message message, long time) { - if (delta == null) { - createDeltaMetric(); - } - - delta.inboundMessageDropped(message, time); - totals.inboundMessageDropped(message, time); - } - - public void inboundMessageDeQueued(Message message, long time) { - if (delta == null) { - createDeltaMetric(); - } - - delta.inboundMessageDeQueued(message, time); - totals.inboundMessageDeQueued(message, time); - } - - public void inboundMessageProcessed(Message message, long time) { - if (delta == null) { - createDeltaMetric(); - } - - delta.inboundMessageProcessed(message, time); - totals.inboundMessageProcessed(message, time); - } - - String getServiceName() { - return serviceName; - } - - String getServiceParameter() { - return serviceParameter; - } - - @Override - public String toString() { - return "InboundMeter(" + serviceName + "//" + serviceParameter + ")"; - } - - public InboundMetric getCumulativeMetrics() { - return totals; - } - - public synchronized InboundMetric collectMetrics() { - InboundMetric prevDelta = delta; - - delta = null; - return prevDelta; - } - - /* Fix-Me: delete after next build.. unused - public synchronized InboundMetric addDeltaToTotals(long reportingDelta) { // returns delta - if (delta != null) { - totals.mergeMetrics(delta); - InboundMetric oldDelta = delta; - delta = null; - return oldDelta; - } else - return null; - } - */ -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/InboundMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/InboundMetric.java deleted file mode 100644 index 754a0ced..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/InboundMetric.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import net.jxta.endpoint.*; -import net.jxta.impl.endpoint.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; - -import java.util.*; - - -/** - * Meter corresponding to inbound queue for registered EndpointListeners ServiceName/ServiceParam pair - **/ -public class InboundMetric implements DocumentSerializable { - private String serviceName; - private String serviceParameter; - - private String serviceIdString; // internally used to speed up Hashing - - private int numInboundQueued; - private int numInboundDropped; - private long timeToDropInbound; - private int numInboundDeQueued; - private long timeInInboundQueue; - private int numInboundProcessed; - private long timeToProcessInbound; - - public InboundMetric(InboundMeter inboundMeter) { - this.serviceName = inboundMeter.getServiceName(); - this.serviceParameter = inboundMeter.getServiceParameter(); - - serviceIdString = serviceName + serviceParameter; - } - - public InboundMetric(InboundMetric prototype) { - this.serviceName = prototype.getServiceName(); - this.serviceParameter = prototype.getServiceParameter(); - - serviceIdString = serviceName + serviceParameter; - } - - public InboundMetric() {} - - /** The Service Name for this Metric **/ - public String getServiceName() { - return serviceName; - } - - /** The Service Parameter for this Metric **/ - public String getServiceParameter() { - return serviceParameter; - } - - /** The Number of Inbound Messages Queued **/ - public int getNumInboundQueued() { - return numInboundQueued; - } - - /** The Number of Inbound Messages Dropped **/ - public int getNumInboundDropped() { - return numInboundDropped; - } - - /** The Sum of time for all dropped messages from queue **/ - public long getTimeToDropInbound() { - return timeToDropInbound; - } - - /** The Number of Inbound Messages Dequeued **/ - public int getNumInboundDeQueued() { - return numInboundDeQueued; - } - - /** The Sum of time in queue for messages in queue **/ - public long getTimeInInboundQueue() { - return timeInInboundQueue; - } - - public int getNumInboundProcessed() { - return numInboundProcessed; - } - - /** The Sum of time for local listeners to process messages **/ - public long getTimeToProcessInbound() { - return timeToProcessInbound; - } - - /** The Average of time in queue for messages **/ - public long getAverageTimeInInboundQueue() { - return (numInboundDeQueued == 0) ? 0 : (timeInInboundQueue / numInboundDeQueued); - } - - /** The Average of time in queue for dropped messages **/ - public long getAverageInboundDropTime() { - return (numInboundDropped == 0) ? 0 : (timeToDropInbound / numInboundDropped); - } - - /** The Average clock time for local listeners to process messages **/ - public long getAverageInboundProcessTime() { - return (numInboundProcessed == 0) ? 0 : (timeToProcessInbound / numInboundProcessed); - } - - @Override - public boolean equals(Object obj) { - - if (obj instanceof InboundMetric) { - InboundMetric other = (InboundMetric) obj; - - return serviceIdString.equals(other.serviceIdString); - } else { - return false; - } - } - - public boolean matches(String serviceName, String serviceParam) { - if (serviceName.equals(getServiceName())) { - if (serviceParam == null && getServiceParameter() == null) { - return true; - } else if (serviceParam != null && getServiceParameter() != null) { - return serviceParam.equals(getServiceParameter()); - } - } - return false; - } - - @Override - public int hashCode() { - return serviceIdString.hashCode(); - } - - void inboundMessageQueued(Message message) { - numInboundQueued++; - } - - void inboundMessageDropped(Message message, long time) { - numInboundDropped++; - timeToDropInbound += time; - } - - void inboundMessageDeQueued(Message message, long time) { - numInboundDeQueued++; - timeInInboundQueue += time; - } - - void inboundMessageProcessed(Message message, long time) { - numInboundProcessed++; - timeToProcessInbound += time; - } - - public void mergeMetrics(InboundMetric other) { - numInboundQueued += other.numInboundQueued; - numInboundDropped += other.numInboundDropped; - timeToDropInbound += other.timeToDropInbound; - numInboundDeQueued += other.numInboundDeQueued; - timeInInboundQueue += other.timeInInboundQueue; - numInboundProcessed += other.numInboundProcessed; - timeToProcessInbound += other.timeToProcessInbound; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - - DocumentSerializableUtilities.addString(element, "serviceName", serviceName); - DocumentSerializableUtilities.addString(element, "serviceParam", serviceParameter); - - if (numInboundQueued != 0) { - DocumentSerializableUtilities.addInt(element, "numInboundQueued", numInboundQueued); - } - - if (numInboundDropped != 0) { - DocumentSerializableUtilities.addInt(element, "numInboundDropped", numInboundDropped); - } - - if (timeToDropInbound != 0) { - DocumentSerializableUtilities.addLong(element, "timeToDropInbound", timeToDropInbound); - } - - if (numInboundDeQueued != 0) { - DocumentSerializableUtilities.addInt(element, "numInboundDeQueued", numInboundDeQueued); - } - - if (timeInInboundQueue != 0) { - DocumentSerializableUtilities.addLong(element, "timeInInboundQueue", timeInInboundQueue); - } - - if (numInboundProcessed != 0) { - DocumentSerializableUtilities.addInt(element, "numInboundProcessed", numInboundProcessed); - } - - if (timeToProcessInbound != 0) { - DocumentSerializableUtilities.addLong(element, "timeToProcessInbound", timeToProcessInbound); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("serviceName")) { - serviceName = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("serviceParam")) { - serviceParameter = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("numInboundQueued")) { - numInboundQueued = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numInboundDropped")) { - numInboundDropped = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("timeToDropInbound")) { - timeToDropInbound = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numInboundDeQueued")) { - numInboundDeQueued = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("timeInInboundQueue")) { - timeInInboundQueue = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numInboundProcessed")) { - numInboundProcessed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("timeToProcessInbound")) { - timeToProcessInbound = DocumentSerializableUtilities.getLong(childElement); - } - } - - serviceIdString = serviceName + serviceParameter; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/IncomingMessageListenerMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/IncomingMessageListenerMeter.java deleted file mode 100644 index 4c08d222..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/IncomingMessageListenerMeter.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import net.jxta.endpoint.Message; - - -public interface IncomingMessageListenerMeter { - public void inboundMessageQueued(Message message); - public void inboundMessageDropped(Message message, long time); - public void inboundMessageDeQueued(Message message, long time); - public void inboundMessageProcessed(Message message, long time); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/MessengerMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/MessengerMeter.java deleted file mode 100644 index 28dccf3b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/MessengerMeter.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import net.jxta.endpoint.*; - - -public interface MessengerMeter { - public void outboundMessageQueued(Message message); - public void outboundMessageDropped(Message message, long time); - public void outboundMessageFailed(Message message, long time); - public void outboundMessageDeQueued(Message message, long time); - public void outboundMessageProcessed(Message message, long time); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/OutboundMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/OutboundMeter.java deleted file mode 100644 index 6ee9e4ec..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/OutboundMeter.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import net.jxta.endpoint.*; - - -/** - * Meter corresponding to a messages demuxed to registered listeners - **/ -public class OutboundMeter { - private EndpointAddress endpointAddress; - - private OutboundMetric totals; - private OutboundMetric delta; - - public OutboundMeter(EndpointAddress endpointAddress) { - this.endpointAddress = endpointAddress; - totals = new OutboundMetric(this); - } - - private void createDeltaMetric() { - delta = new OutboundMetric(this); - } - - public void outboundMessageQueued(Message message) { - if (delta == null) { - createDeltaMetric(); - } - - delta.outboundMessageQueued(message); - totals.outboundMessageQueued(message); - } - - public void outboundMessageDropped(Message message, long time) { - if (delta == null) { - createDeltaMetric(); - } - - delta.outboundMessageDropped(message, time); - totals.outboundMessageDropped(message, time); - } - - public void outboundMessageFailed(Message message, long time) { - if (delta == null) { - createDeltaMetric(); - } - - delta.outboundMessageFailed(message, time); - totals.outboundMessageFailed(message, time); - } - - public void outboundMessageDeQueued(Message message, long time) { - if (delta == null) { - createDeltaMetric(); - } - - delta.outboundMessageDeQueued(message, time); - totals.outboundMessageDeQueued(message, time); - } - - public void outboundMessageProcessed(Message message, long time) { - if (delta == null) { - createDeltaMetric(); - } - - delta.outboundMessageProcessed(message, time); - totals.outboundMessageProcessed(message, time); - } - - EndpointAddress getEndpointAddress() { - return endpointAddress; - } - - @Override - public String toString() { - return "OutboundMeter(" + endpointAddress + ")"; - } - - public OutboundMetric getCumulativeMetrics() { - return totals; - } - - public synchronized OutboundMetric collectMetrics() { - OutboundMetric prevDelta = delta; - - delta = null; - return prevDelta; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/OutboundMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/OutboundMetric.java deleted file mode 100644 index 250398ab..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/OutboundMetric.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import net.jxta.endpoint.*; -import net.jxta.impl.endpoint.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; - -import java.util.*; - - -/** - * Metric corresponding to a message queue to for outbound messengers based upon an endpoint address - **/ -public class OutboundMetric implements DocumentSerializable { - private EndpointAddress endpointAddress; - - private int numOutboundQueued; - private int numOutboundDropped; - private long timeToDropOutbound; - private int numOutboundDeQueued; - private long timeInOutboundQueue; - private int numOutboundProcessed; - private long timeToProcessOutbound; - private int numOutboundFailed; - private long timeOutboundToFail; - - public OutboundMetric(OutboundMeter outboundMeter) { - this.endpointAddress = outboundMeter.getEndpointAddress(); - } - - public OutboundMetric(OutboundMetric prototype) { - this.endpointAddress = prototype.getEndpointAddress(); - } - - public OutboundMetric() {} - - /** The Endpoint address for this outbound message queue **/ - public EndpointAddress getEndpointAddress() { - return endpointAddress; - } - - /** The Number of Outbound Messages Queued **/ - public int getNumOutboundQueued() { - return numOutboundQueued; - } - - /** The Number of Outbound Messages Dropped from Queue **/ - public int getNumOutboundDropped() { - return numOutboundDropped; - } - - /** The Sum of the times in queue for all dropped messages **/ - public long getTimeToDropOutbound() { - return timeToDropOutbound; - } - - /** The Number of Outbound Messages DeQueued **/ - public int getNumOutboundDeQueued() { - return numOutboundDeQueued; - } - - /** The Sum of the times in queue for all messages **/ - public long getTimeInOutboundQueue() { - return timeInOutboundQueue; - } - - /** The Number of Outbound Messages Processed Successfully **/ - public int getNumOutboundProcessed() { - return numOutboundProcessed; - } - - /** The Sum of the times from sending to handling by messenger **/ - public long getTimeToProcessOutbound() { - return timeToProcessOutbound; - } - - /** The Number of Outbound Messages Failed in sending **/ - public int getNumOutboundFailed() { - return numOutboundFailed; - } - - /** The Sum of the times in queue for all failed messages **/ - public long getTimeOutboundToFail() { - return timeOutboundToFail; - } - - /** The Average of the times in queue for all messages **/ - public long getAverageTimeInOutboundQueue() { - return (numOutboundDeQueued == 0) ? 0 : (timeInOutboundQueue / numOutboundDeQueued); - } - - /** The Average of the times in queue for all dropped messages **/ - public long getAverageOutboundDropTime() { - return (numOutboundDropped == 0) ? 0 : (timeToDropOutbound / numOutboundDropped); - } - - /** The Average of the times from sending to handling by messenger **/ - public long getAverageOutboundProcessTime() { - return (numOutboundProcessed == 0) ? 0 : (timeToProcessOutbound / numOutboundProcessed); - } - - @Override - public boolean equals(Object obj) { - - if (obj instanceof OutboundMetric) { - OutboundMetric other = (OutboundMetric) obj; - - return endpointAddress.equals(other.endpointAddress); - } else { - return false; - } - } - - public boolean matches(EndpointAddress otherAddress) { - return getEndpointAddress().equals(otherAddress); - } - - @Override - public int hashCode() { - return endpointAddress.hashCode(); - } - - void outboundMessageQueued(Message message) { - numOutboundQueued++; - } - - void outboundMessageDropped(Message message, long time) { - numOutboundDropped++; - timeToDropOutbound += time; - } - - void outboundMessageFailed(Message message, long time) { - numOutboundFailed++; - timeOutboundToFail += time; - } - - void outboundMessageDeQueued(Message message, long time) { - numOutboundDeQueued++; - timeInOutboundQueue += time; - } - - void outboundMessageProcessed(Message message, long time) { - numOutboundProcessed++; - timeToProcessOutbound += time; - } - - public void mergeMetrics(OutboundMetric other) { - - numOutboundQueued += other.numOutboundQueued; - numOutboundDropped += other.numOutboundDropped; - timeToDropOutbound += other.timeToDropOutbound; - numOutboundDeQueued += other.numOutboundDeQueued; - timeInOutboundQueue += other.timeInOutboundQueue; - numOutboundProcessed += other.numOutboundProcessed; - timeToProcessOutbound += other.timeToProcessOutbound; - numOutboundFailed += other.numOutboundFailed; - timeOutboundToFail += other.timeOutboundToFail; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - - DocumentSerializableUtilities.addString(element, "endpointAddress", endpointAddress.toString()); - - if (numOutboundQueued != 0) { - DocumentSerializableUtilities.addInt(element, "numOutboundQueued", numOutboundQueued); - } - - if (numOutboundDropped != 0) { - DocumentSerializableUtilities.addInt(element, "numOutboundDropped", numOutboundDropped); - } - - if (timeToDropOutbound != 0) { - DocumentSerializableUtilities.addLong(element, "timeToDropOutbound", timeToDropOutbound); - } - - if (numOutboundDeQueued != 0) { - DocumentSerializableUtilities.addInt(element, "numOutboundDeQueued", numOutboundDeQueued); - } - - if (timeInOutboundQueue != 0) { - DocumentSerializableUtilities.addLong(element, "timeInOutboundQueue", timeInOutboundQueue); - } - - if (numOutboundProcessed != 0) { - DocumentSerializableUtilities.addInt(element, "numOutboundProcessed", numOutboundProcessed); - } - - if (timeToProcessOutbound != 0) { - DocumentSerializableUtilities.addLong(element, "timeToProcessOutbound", timeToProcessOutbound); - } - - if (numOutboundFailed != 0) { - DocumentSerializableUtilities.addInt(element, "numOutboundFailed", numOutboundFailed); - } - - if (timeOutboundToFail != 0) { - DocumentSerializableUtilities.addLong(element, "timeOutboundToFail", timeOutboundToFail); - } - - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("endpointAddress")) { - String endpointAddressString = DocumentSerializableUtilities.getString(childElement); - - endpointAddress = new EndpointAddress(endpointAddressString); - } else if (tagName.equals("numOutboundQueued")) { - numOutboundQueued = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numOutboundDropped")) { - numOutboundDropped = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("timeToDropOutbound")) { - timeToDropOutbound = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numOutboundDeQueued")) { - numOutboundDeQueued = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("timeInOutboundQueue")) { - timeInOutboundQueue = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numOutboundProcessed")) { - numOutboundProcessed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("timeToProcessOutbound")) { - timeToProcessOutbound = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numOutboundFailed")) { - numOutboundFailed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("timeOutboundToFail")) { - timeOutboundToFail = DocumentSerializableUtilities.getLong(childElement); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/PropagationMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/PropagationMeter.java deleted file mode 100644 index 5a2153c7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/PropagationMeter.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -/** - * Meter corresponding to a propagated messages - **/ -public class PropagationMeter { - private String serviceName; - private String serviceParameter; - - private PropagationMetric totals; - private PropagationMetric delta; - - public PropagationMeter(String serviceName, String serviceParameter) { - this.serviceName = serviceName; - this.serviceParameter = serviceParameter; - this.totals = new PropagationMetric(this); - } - - private void createDeltaMetric() { - delta = new PropagationMetric(this); - } - - public void registerPropagateMessageStats(int numPropagatedTo, int numFilteredOut, int numErrorsPropagated, long propagationTime) { - if (delta == null) { - createDeltaMetric(); - } - - delta.registerPropagateMessageStats(numPropagatedTo, numFilteredOut, numErrorsPropagated, propagationTime); - totals.registerPropagateMessageStats(numPropagatedTo, numFilteredOut, numErrorsPropagated, propagationTime); - } - - String getServiceName() { - return serviceName; - } - - String getServiceParameter() { - return serviceParameter; - } - - @Override - public String toString() { - return "PropagationMeter(" + serviceName + "//" + serviceParameter + ")"; - } - - public PropagationMetric getCumulativeMetrics() { - return totals; - } - - public synchronized PropagationMetric collectMetrics() { - PropagationMetric prevDelta = delta; - - delta = null; - return prevDelta; - } - - /* Fix-Me: delete after next build.. unused - public synchronized PropagationMetric addDeltaToTotals(long reportingDelta) { // returns delta - if (delta != null) { - totals.mergeMetrics(delta); - PropagationMetric oldDelta = delta; - delta = null; - return oldDelta; - } else - return null; - } - */ -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/PropagationMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/PropagationMetric.java deleted file mode 100644 index 8bf71be1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/endpointMeter/PropagationMetric.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.endpointMeter; - - -import net.jxta.endpoint.*; -import net.jxta.impl.endpoint.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; - -import java.util.*; - - -/** - * Metric corresponding to a propagated messages - * Meter corresponding to propagated to a ServiceName/ServiceParam pair - **/ -public class PropagationMetric implements DocumentSerializable { - private String serviceName; - private String serviceParameter; - - private String serviceIdString; // for Hashing - int numPropagations; - int numPropagatedTo; - int numFilteredOut; - int numErrorsPropagated; - long propagationTime; - - public PropagationMetric() { - serviceIdString = serviceName + serviceParameter; - } - - public PropagationMetric(PropagationMeter propagationMeter) { - this.serviceName = propagationMeter.getServiceName(); - this.serviceParameter = propagationMeter.getServiceParameter(); - - serviceIdString = serviceName + serviceParameter; - } - - public PropagationMetric(PropagationMetric prototype) { - this.serviceName = prototype.getServiceName(); - this.serviceParameter = prototype.getServiceParameter(); - - serviceIdString = serviceName + serviceParameter; - } - - void registerPropagateMessageStats(int numPropagatedTo, int numFilteredOut, int numErrorsPropagated, long propagationTime) { - this.numPropagations++; - this.numPropagatedTo += numPropagatedTo; - this.numFilteredOut += numFilteredOut; - this.numErrorsPropagated += numErrorsPropagated; - this.propagationTime += propagationTime; - } - - /** The Endpoint address for this outbound message queue **/ - public String getServiceName() { - return serviceName; - } - - /** The Endpoint address for this outbound message queue **/ - public String getServiceParameter() { - return serviceParameter; - } - - /** The Number of Propagated Messages **/ - public int getNumPropagations() { - return numPropagations; - } - - /** Total number of transports messagess were propagated to **/ - public int getNumPropagatedTo() { - return numPropagatedTo; - } - - /** The Number of Filtered out Messages **/ - - /** The Average of number of Transports propagated To from propagation to transport **/ - public int getAverageNumTransports() { - return (numPropagatedTo == 0) ? 0 : (numPropagations / numPropagatedTo); - } - - public int getNumFilteredOut() { - return numFilteredOut; - } - - /** The Number of Errors propagating Messages **/ - public int getNumErrorsPropagated() { - return numErrorsPropagated; - } - - /** The Sum of (clock) times from propagation to transport **/ - public long getPropagationTime() { - return propagationTime; - } - - /** The Average of (clock) times from propagation to transport **/ - public long getAveragePropagationTime() { - return (numPropagatedTo == 0) ? 0 : (propagationTime / numPropagatedTo); - } - - @Override - public boolean equals(Object obj) { - - if (obj instanceof PropagationMetric) { - PropagationMetric other = (PropagationMetric) obj; - - return serviceIdString.equals(other.serviceIdString); - } else { - return false; - } - } - - public boolean matches(String serviceName, String serviceParam) { - if (serviceName.equals(getServiceName())) { - if (serviceParam == null && getServiceParameter() == null) { - return true; - } else if (serviceParam != null && getServiceParameter() != null) { - return serviceParam.equals(getServiceParameter()); - } - } - return false; - } - - @Override - public int hashCode() { - return serviceIdString.hashCode(); - } - - String getServiceIdString() { - return serviceIdString; - } - - public void mergeMetrics(PropagationMetric other) { - numPropagatedTo += other.numPropagatedTo; - numFilteredOut += other.numFilteredOut; - numErrorsPropagated += other.numErrorsPropagated; - propagationTime += other.propagationTime; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - - DocumentSerializableUtilities.addString(element, "serviceName", serviceName); - DocumentSerializableUtilities.addString(element, "serviceParam", serviceParameter); - - if (numPropagations != 0) { - DocumentSerializableUtilities.addInt(element, "numPropagations", numPropagatedTo); - } - - if (numPropagatedTo != 0) { - DocumentSerializableUtilities.addInt(element, "numPropagatedTo", numPropagatedTo); - } - - if (numFilteredOut != 0) { - DocumentSerializableUtilities.addInt(element, "numFilteredOut", numFilteredOut); - } - - if (numErrorsPropagated != 0) { - DocumentSerializableUtilities.addInt(element, "numErrorsPropagated", numErrorsPropagated); - } - - if (propagationTime != 0) { - DocumentSerializableUtilities.addLong(element, "propagationTime", propagationTime); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("serviceName")) { - serviceName = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("serviceParam")) { - serviceParameter = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("numPropagations")) { - numPropagations = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPropagatedTo")) { - numPropagatedTo = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numFilteredOut")) { - numFilteredOut = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("propagationTime")) { - propagationTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numErrorsPropagated")) { - numErrorsPropagated = DocumentSerializableUtilities.getInt(childElement); - } - } - - serviceIdString = serviceName + serviceParameter; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/mcast/McastTransport.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/mcast/McastTransport.java deleted file mode 100644 index 8a0dfd9a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/mcast/McastTransport.java +++ /dev/null @@ -1,887 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.mcast; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MulticastSocket; -import java.net.SocketException; -import java.net.URI; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Executor; -import java.util.logging.Level; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.MimeMediaType; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.MessagePropagater; -import net.jxta.endpoint.MessengerEventListener; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.endpoint.WireFormatMessage; -import net.jxta.endpoint.WireFormatMessageFactory; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.logging.Logging; -import net.jxta.meter.MonitorResources; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.TransportAdvertisement; - -import net.jxta.impl.endpoint.EndpointServiceImpl; -import net.jxta.impl.endpoint.IPUtils; -import net.jxta.impl.endpoint.msgframing.MessagePackageHeader; -import net.jxta.impl.endpoint.transportMeter.TransportBindingMeter; -import net.jxta.impl.endpoint.transportMeter.TransportMeter; -import net.jxta.impl.endpoint.transportMeter.TransportMeterBuildSettings; -import net.jxta.impl.endpoint.transportMeter.TransportServiceMonitor; -import net.jxta.impl.meter.MonitorManager; -import net.jxta.impl.peergroup.StdPeerGroup; -import net.jxta.impl.protocol.TCPAdv; - -/** - * This class implements the IP Multicast Message Transport. - *

      - * Important Note: This implementation was formerly a portion of the TCP - * Message Transport and currently uses the TCP Transport's configuration - * advertisement. - * - * @see net.jxta.endpoint.MessageTransport - * @see net.jxta.endpoint.MessagePropagater - * @see net.jxta.endpoint.EndpointService - * @see JXTA Protocols Specification : Standard JXTA Transport Bindings - */ -public class McastTransport implements Runnable, Module, MessagePropagater { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(McastTransport.class.getName()); - - /** - * Well known service class identifier: mcast message transport - */ - public final static ModuleClassID MCAST_TRANSPORT_CLASSID = - ModuleClassID.create(URI.create("urn:jxta:uuid-0C801F65D38F421C9884D706B337B81105")); - - /** - * Well known service spec identifier: mcast message transport - */ - public final static ModuleSpecID MCAST_TRANSPORT_SPECID = - ModuleSpecID.create(URI.create("urn:jxta:uuid-0C801F65D38F421C9884D706B337B8110106")); - - /** - * The Protocol name we will use for our endpoint addresses. - */ - private String protocolName = "mcast"; - - /** - * Our Source Addres. - */ - private EndpointAddress ourSrcAddr = null; - - /** - * The Source Address Element we attach to all of the messages we send. - */ - private MessageElement msgSrcAddrElement = null; - - /** - * The name of the local interface that we bind to. - */ - private String interfaceAddressStr; - - /** - * The address of the local interface address that be bind to. - */ - private InetAddress usingInterface; - - /** - * If {@code true} then we are closed otherwise {@code false} - */ - private boolean isClosed = false; - - /** - * The name of multicast address we will send/receive upon. - */ - private String multicastAddress = "224.0.1.85"; - - /** - * The multicast address we will send/receive upon. - */ - private InetAddress multicastInetAddress; - - /** - * The port number will send/receive upon. - */ - private int multicastPort = 1234; - - /** - * The "return address" we will advertise. - */ - private EndpointAddress publicAddress = new EndpointAddress(protocolName, multicastAddress + ":" + Integer.toString(multicastPort), null, null); - - /** - * The maximum size of multicast messages we will send and the size of the - * {@code DatagramPacket}s we will allocate. - */ - private int multicastPacketSize = 16384; - - /** - * The socket we use to send and receive. - */ - private MulticastSocket multicastSocket = null; - - /** - * Daemon thread which services the multicast socket and receives datagrams. - */ - private Thread multicastThread = null; - - /** - * Thread pooling/queing multicast datagram processor. - */ - private DatagramProcessor multicastProcessor; - - /** - * The peer group we are working for. - */ - private PeerGroup group = null; - - /** - * The Module Class ID we were assigned in init(). - */ - private ID assignedID = null; - - /** - * The impl advertisement we were provided in init(). - */ - private ModuleImplAdvertisement implAdvertisement = null; - - /** - * The endpoint service we are working for. - */ - private EndpointService endpoint = null; - - private TransportMeter multicastTransportMeter; - private TransportBindingMeter multicastTransportBindingMeter; - private transient boolean disabled = false; - - /** - * Construct a new McastTransport instance - */ - public McastTransport() { - } - - /** - * {@inheritDoc} - */ - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof McastTransport) { - McastTransport likeMe = (McastTransport) target; - return getProtocolName().equals(likeMe.getProtocolName()) && getPublicAddress().equals(likeMe.getPublicAddress()); - } - return false; - } - - /** - * {@inheritDoc} - */ - public int hashCode() { - return getPublicAddress().hashCode(); - } - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - this.group = group; - this.assignedID = assignedID; - this.implAdvertisement = (ModuleImplAdvertisement) impl; - - ConfigParams configAdv = group.getConfigAdvertisement(); - - // Get out invariable parameters from the implAdv - XMLElement param = (XMLElement) implAdvertisement.getParam(); - - if (param != null) { - Enumeration list = param.getChildren("Proto"); - if (list.hasMoreElements()) { - XMLElement pname = list.nextElement(); - protocolName = pname.getTextValue(); - } - } - - // Get our peer-defined parameters in the configAdv - param = (XMLElement) configAdv.getServiceParam(PeerGroup.tcpProtoClassID); - if (null == param) { - throw new IllegalArgumentException(TransportAdvertisement.getAdvertisementType() + " could not be located."); - } - - Enumeration tcpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType()); - - // get the TransportAdv - if (tcpChilds.hasMoreElements()) { - param = tcpChilds.nextElement(); - Attribute typeAttr = param.getAttribute("type"); - - if (!TCPAdv.getAdvertisementType().equals(typeAttr.getValue())) { - throw new IllegalArgumentException("transport adv is not a " + TCPAdv.getAdvertisementType()); - } - - if (tcpChilds.hasMoreElements()) { - throw new IllegalArgumentException("Multiple transport advs detected for " + assignedID); - } - } else { - throw new IllegalArgumentException(TransportAdvertisement.getAdvertisementType() + " could not be located."); - } - - Advertisement paramsAdv = null; - try { - paramsAdv = AdvertisementFactory.newAdvertisement(param); - } catch (NoSuchElementException notThere) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Could not find parameter document", notThere); - } - } - - if (!(paramsAdv instanceof TCPAdv)) { - throw new IllegalArgumentException("Provided Advertisement was not a " + TCPAdv.getAdvertisementType()); - } - - TCPAdv adv = (TCPAdv) paramsAdv; - - // Check if we are disabled. If so, don't bother with the rest of config. - if (!adv.getMulticastState()) { - disabled = true; - return; - } - - // Determine the local interface to use. If the user specifies one, use - // that. Otherwise, use the all the available interfaces. - interfaceAddressStr = adv.getInterfaceAddress(); - if (interfaceAddressStr != null) { - try { - usingInterface = InetAddress.getByName(interfaceAddressStr); - } catch (UnknownHostException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Invalid address for local interface address, using default"); - } - usingInterface = IPUtils.ANYADDRESS; - } - } else { - usingInterface = IPUtils.ANYADDRESS; - } - - // Start the servers - - // Only the outgoing interface matters. - // Verify that ANY interface does not in fact mean LOOPBACK only. - // If that's the case, we want to make that explicit, so that - // consistency checks regarding the allowed use of that interface work - // properly. - if (usingInterface.equals(IPUtils.ANYADDRESS)) { - boolean localOnly = true; - Iterator eachLocal = IPUtils.getAllLocalAddresses(); - while (eachLocal.hasNext()) { - InetAddress anAddress = eachLocal.next(); - if (!anAddress.isLoopbackAddress()) { - localOnly = false; - break; - } - } - - if (localOnly) { - usingInterface = IPUtils.LOOPBACK; - } - } - - ourSrcAddr = new EndpointAddress(group.getPeerID(), null, null); - msgSrcAddrElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NAME, ourSrcAddr.toString(), null); - - // Get the multicast configuration. - multicastAddress = adv.getMulticastAddr(); - multicastPort = adv.getMulticastPort(); - - // XXX 20070711 bondolo We resolve the address only once. Perhaps we should do this dynamically? - try { - multicastInetAddress = InetAddress.getByName(multicastAddress); - } catch (UnknownHostException notValid) { - IllegalArgumentException failed = new IllegalArgumentException("Invalid or unknown host name :" + multicastAddress); - failed.initCause(notValid); - throw failed; - } - - assert multicastInetAddress.isMulticastAddress(); - publicAddress = new EndpointAddress(protocolName, multicastAddress + ":" + Integer.toString(multicastPort), null, null); - multicastPacketSize = adv.getMulticastSize(); - - // Create the multicast input socket - try { - multicastSocket = new MulticastSocket(new InetSocketAddress(usingInterface, multicastPort)); - } catch (IOException failed) { - throw new PeerGroupException("Could not open multicast socket", failed); - } - - try { - // Surprisingly, "true" means disable.... - multicastSocket.setLoopbackMode(false); - } catch (SocketException ignored) { - // We may not be able to set loopback mode. It is inconsistent - // whether an error will occur if the set fails. - } - - // Tell tell the world about our configuration. - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring IP Multicast Message Transport : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params:"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID: ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration:"); - configInfo.append("\n\t\tProtocol: ").append(protocolName); - configInfo.append("\n\t\tInterface address: ").append(interfaceAddressStr == null ? "(unspecified)" : interfaceAddressStr); - configInfo.append("\n\t\tMulticast Addr: ").append(multicastAddress); - configInfo.append("\n\t\tMulticast Port: ").append(multicastPort); - configInfo.append("\n\t\tMulticast Packet Size: ").append(multicastPacketSize); - - configInfo.append("\n\tBound To :"); - configInfo.append("\n\t\tUsing Interface: ").append(usingInterface.getHostAddress()); - - configInfo.append("\n\t\tMulticast Server Bind Addr: ").append(multicastSocket.getLocalSocketAddress()); - configInfo.append("\n\t\tPublic Address: ").append(publicAddress); - - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public synchronized int startApp(String[] arg) { - if (disabled) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("IP Multicast Message Transport disabled."); - } - return Module.START_DISABLED; - } - - endpoint = group.getEndpointService(); - if (null == endpoint) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - return Module.START_AGAIN_STALLED; - } - - isClosed = false; - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - TransportServiceMonitor transportServiceMonitor = (TransportServiceMonitor) MonitorManager.getServiceMonitor(group, - MonitorResources.transportServiceMonitorClassID); - - if (transportServiceMonitor != null) { - multicastTransportMeter = transportServiceMonitor.createTransportMeter("Multicast", publicAddress); - multicastTransportBindingMeter = getMulticastTransportBindingMeter(publicAddress); - // Since multicast is connectionless, force it to appear outbound connected - multicastTransportBindingMeter.connectionEstablished(true, 0); - // Since multicast is connectionless, force it to appear inbound connected - multicastTransportBindingMeter.connectionEstablished(false, 0); - } - } - - // We're fully ready to function. - MessengerEventListener messengerEventListener = endpoint.addMessageTransport(this); - if (messengerEventListener == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Transport registration refused"); - } - return -1; - } - - // Cannot start before registration - multicastProcessor = new DatagramProcessor(((StdPeerGroup) group).getExecutor()); - multicastThread = new Thread(group.getHomeThreadGroup(), this, "IP Multicast Listener for " + publicAddress); - multicastThread.setDaemon(true); - multicastThread.start(); - - try { - multicastSocket.joinGroup(multicastInetAddress); - } catch (IOException soe) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Could not join multicast group, setting Multicast off"); - } - return -1; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("IP Multicast Message Transport started."); - } - - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - public synchronized void stopApp() { - if (isClosed || disabled) { - return; - } - - isClosed = true; - - if (multicastSocket != null) { - multicastSocket.close(); - multicastSocket = null; - } - - if (null != multicastProcessor) { - multicastProcessor.stop(); - multicastProcessor = null; - } - - endpoint.removeMessageTransport(this); - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (multicastTransportBindingMeter != null)) { - // Since multicast is connectionless, force it to appear outbound disconnected - multicastTransportBindingMeter.connectionClosed(true, 0); - // Since multicast is connectionless, force it to appear inbound disconnected - multicastTransportBindingMeter.connectionClosed(false, 0); - } - } - - /** - * {@inheritDoc} - */ - public String getProtocolName() { - return protocolName; - } - - /** - * {@inheritDoc} - */ - public EndpointAddress getPublicAddress() { - return publicAddress; - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - return (EndpointService) endpoint.getInterface(); - } - - /** - * {@inheritDoc} - */ - public Object transportControl(Object operation, Object Value) { - return null; - } - - /** - * {@inheritDoc} - *

      - * Handles incoming multicasts and enqueues them with the datagram processor. - */ - public void run() { - - try { - while (!isClosed) { - byte[] buffer = new byte[multicastPacketSize]; - DatagramPacket packet = new DatagramPacket(buffer, buffer.length); - - try { - multicastSocket.receive(packet); - - if (isClosed) { - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("multicast message received from :" + packet.getAddress().getHostAddress()); - } - - // This operation is blocking and may take a long time to - // return. As a result we may lose datagram packets because - // we are not calling - // {@link MulticastSocket#receive(DatagramPacket)} often - // enough. - multicastProcessor.put(packet); - } catch (InterruptedException woken) { - Thread.interrupted(); - } catch (InterruptedIOException woken) { - Thread.interrupted(); - } catch (Exception e) { - if (isClosed) { - return; - } - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE) && (!isClosed)) { - LOG.log(Level.SEVERE, "failure during multicast receive", e); - } - break; - } - } - } catch (Throwable all) { - if (isClosed) { - return; - } - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - multicastThread = null; - } - } - - /** - * {@inheritDoc} - *

      - * Synchronized to not allow concurrent IP multicast: this naturally bounds - * the usage of ip-multicast boolean be linear and not exponential. - */ - public synchronized boolean propagate(Message message, String pName, String pParams, int initalTTL) { - long sendStartTime = System.currentTimeMillis(); - int numBytesInPacket = 0; - - try { - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NS, msgSrcAddrElement); - - // First build the destination and source addresses - EndpointAddress destAddr = new EndpointAddress(publicAddress, pName, pParams); - MessageElement dstAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NAME, destAddr.toString(), null); - - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NS, dstAddressElement); - - WireFormatMessage serialed = WireFormatMessageFactory.toWire(message, WireFormatMessageFactory.DEFAULT_WIRE_MIME, null); - MessagePackageHeader header = new MessagePackageHeader(); - - header.setContentTypeHeader(serialed.getMimeType()); - header.setContentLengthHeader(serialed.getByteLength()); - - ByteArrayOutputStream buffer = new ByteArrayOutputStream(multicastPacketSize); - - buffer.write('J'); - buffer.write('X'); - buffer.write('T'); - buffer.write('A'); - header.sendToStream(buffer); - serialed.sendToStream(buffer); - buffer.flush(); - buffer.close(); - numBytesInPacket = buffer.size(); - - if ((buffer.size() > multicastPacketSize) && Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Multicast datagram exceeds multicast size."); - } - - DatagramPacket packet = new DatagramPacket(buffer.toByteArray(), numBytesInPacket, multicastInetAddress, multicastPort); - - multicastSocket.send(packet); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sent Multicast message to :" + pName + "/" + pParams); - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (multicastTransportBindingMeter != null)) { - multicastTransportBindingMeter.messageSent(true, message, System.currentTimeMillis() - sendStartTime, numBytesInPacket); - } - return true; - } catch (IOException e) { - if (TransportMeterBuildSettings.TRANSPORT_METERING && (multicastTransportBindingMeter != null)) { - multicastTransportBindingMeter.sendFailure(true, message, System.currentTimeMillis() - sendStartTime, numBytesInPacket); - } - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Multicast socket send failed", e); - } - return false; - } - } - - /** - * Handle a byte buffer from a multi-cast. - * - * @param packet the message packet. - */ - void processMulticast(DatagramPacket packet) { - int size = packet.getLength(); - byte[] buffer = packet.getData(); - - long messageReceiveBeginTime = System.currentTimeMillis(); - - try { - if (size < 4) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("damaged multicast discarded"); - } - throw new IOException("damaged multicast discarded : too short"); - } - - if (('J' != buffer[0]) || ('X' != buffer[1]) || ('T' != buffer[2]) || ('A' != buffer[3])) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("damaged multicast discarded"); - } - throw new IOException("damaged multicast discarded : incorrect signature"); - } - - ByteBuffer bbuffer = ByteBuffer.wrap(buffer, 4, size - 4); - MessagePackageHeader header = new MessagePackageHeader(); - - if (!header.readHeader(bbuffer)) { - throw new IOException("Failed to read framing header"); - } - - MimeMediaType msgMime = header.getContentTypeHeader(); - // TODO 20020730 bondolo@jxta.org Do something with content-coding here. - - // read the message! - Message msg = WireFormatMessageFactory.fromBuffer(bbuffer, msgMime, null); - - // Extract the source and destination - MessageElement srcAddrElem = msg.getMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NS, EndpointServiceImpl.MESSAGE_SOURCE_NAME); - if (null == srcAddrElem) { - throw new IOException("No Source Address in " + msg); - } - - msg.removeMessageElement(srcAddrElem); - - EndpointAddress srcAddr = new EndpointAddress(srcAddrElem.toString()); - - if (srcAddr.equals(ourSrcAddr)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Discard loopback multicast message"); - } - return; - } - - MessageElement dstAddrElem = msg.getMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NS, EndpointServiceImpl.MESSAGE_DESTINATION_NAME); - if (null == dstAddrElem) { - throw new IOException("No Destination Address in " + msg); - } - - msg.removeMessageElement(dstAddrElem); - - EndpointAddress dstAddr = new EndpointAddress(dstAddrElem.toString()); - - // Handoff the message to the EndpointService Manager - endpoint.processIncomingMessage(msg, srcAddr, dstAddr); - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (multicastTransportBindingMeter != null)) { - multicastTransportBindingMeter.messageReceived(false, msg, messageReceiveBeginTime - System.currentTimeMillis(), size); - } - } catch (Exception e) { - if (TransportMeterBuildSettings.TRANSPORT_METERING && (multicastTransportBindingMeter != null)) { - multicastTransportBindingMeter.receiveFailure(false, messageReceiveBeginTime - System.currentTimeMillis(), size); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Discard incoming multicast message", e); - } - } - } - - TransportBindingMeter getMulticastTransportBindingMeter(EndpointAddress destinationAddress) { - if (multicastTransportMeter != null) { - return multicastTransportMeter.getTransportBindingMeter(group.getPeerID(), destinationAddress); - } else { - return null; - } - } - - /** - * Handles incoming datagram packets. This implementation uses the peer - * group Executor service to process the datagram packets, but limits the - * number of concurrent tasks. - */ - private class DatagramProcessor implements Runnable { - - /** - * The maximum number of datagrams we will simultaneously process. - */ - private static final int MAX_SIMULTANEOUS_PROCESSING = 5; - - /** - * The executor to which we will issue tasks. - */ - final Executor executor; - - /** - * Queue of datagrams waiting to be executed. The queue is quite small. - * The goal is not to cache datagrams in memory. If we can't keep up it - * is better that we drop messages. - */ - final BlockingQueue queue = new ArrayBlockingQueue(MAX_SIMULTANEOUS_PROCESSING + 1); - - /** - * The number of executor tasks we are currently using. - */ - int currentTasks = 0; - - /** - * If {@code true} then this processor has been stopped. - */ - volatile boolean stopped = false; - - /** - * Default constructor - * @param executor the threadpool - */ - DatagramProcessor(Executor executor) { - this.executor = executor; - } - - /** - * Stops this thread - */ - void stop() { - queue.clear(); - stopped = true; - } - - /** - * Puts a datagram on the queue. The enqueue operation is blocking and - * may take a significant amount of time. - * - * @param packet the datagram - * @throws InterruptedException if interrupted - */ - void put(DatagramPacket packet) throws InterruptedException { - boolean execute = false; - - if (stopped) { - return; - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.log(Level.FINER, "Queuing incoming datagram packet : " + packet); - } - - // push the datagram - queue.put(packet); - - // See if we can start a new executor. - synchronized (this) { - if (!stopped && (currentTasks < MAX_SIMULTANEOUS_PROCESSING)) { - currentTasks++; - execute = true; - } - } - - // If it's ok, start a new executor outside of the synchronization. - if (execute) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINER, "Starting new executor datagram processing task"); - } - executor.execute(this); - } - } - - /** - * {@inheritDoc} - */ - public void run() { - try { - DatagramPacket packet; - while (!stopped && (null != (packet = queue.poll()))) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.log(Level.FINER, "Processing incoming datagram packet : " + packet); - } - processMulticast(packet); - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable", all); - } - } finally { - synchronized (this) { - currentTasks--; - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/mcast/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/mcast/package.html deleted file mode 100644 index 0fc08814..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/mcast/package.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - -A JXTA {@link net.jxta.endpoint.MessageTransport} implementation which uses raw -IP multicast datagrams. - -@see net.jxta.endpoint.EndpointService -@see net.jxta.endpoint.MessageTransport -@see net.jxta.endpoint.MessagePropagater -@see net.jxta.endpoint.Message -@see JXTA Protocols - Specification : Standard JXTA Transport Bindings - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/msgframing/MessagePackageHeader.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/msgframing/MessagePackageHeader.java deleted file mode 100644 index c679feaa..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/msgframing/MessagePackageHeader.java +++ /dev/null @@ -1,605 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.msgframing; - - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.text.MessageFormat; -import java.util.ListIterator; - -import net.jxta.document.MimeMediaType; - - -/** - * Header Package for Messages. Analogous to HTTP Headers. - */ -public class MessagePackageHeader { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(MessagePackageHeader.class.getName()); - - /** - * Standard header name for content-length - */ - private final static String CONTENT_LENGTH = "content-length"; - - /** - * Standard header name for content-type - */ - private final static String CONTENT_TYPE = "content-type"; - - /** - * The maximum size of Header data buffers we will emit. - */ - private final static int MAX_HEADER_LEN = 1024; - - /** - * Used for storing individual header elements. - */ - public static class Header { - - final String name; - final byte[] value; - - public Header(String name, byte[] value) { - this.name = name; - - assert value.length <= 65535; - - this.value = value; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return MessageFormat.format("{0} := {1}", name, value); - } - - public String getName() { - return name; - } - - public byte[] getValue() { - return value; - } - - public String getValueString() { - try { - return new String(value, "UTF-8"); - } catch (UnsupportedEncodingException never) { - // utf-8 is a required encoding. - throw new Error("UTF-8 encoding support missing!"); - } - } - } - - /** - * The individual header elements in the order they were read. - */ - private final List

      headers = new ArrayList
      (); - - /** - * Creates a new instance of MessagePackageHeader. Used for outgoing messages. - */ - public MessagePackageHeader() {} - - /** - * Creates a new instance of MessagePackageHeader. Used for incoming messages. - * - * @param in The stream from which the headers will be read. - * @throws java.io.IOException if an io error occurs. - */ - public MessagePackageHeader(InputStream in) throws IOException { - boolean sawEmpty = false; - boolean sawLength = false; - boolean sawType = false; - DataInput di = new DataInputStream(in); - - // todo 20021014 bondolo@jxta.org A framing signature would help here. - - do { - byte headerNameLength = di.readByte(); - - if (0 == headerNameLength) { - sawEmpty = true; - } else { - byte[] headerNameBytes = new byte[headerNameLength]; - - di.readFully(headerNameBytes); - - String headerNameString = new String(headerNameBytes, "UTF-8"); - - if (headerNameString.equalsIgnoreCase(CONTENT_LENGTH)) { - if (sawLength) { - throw new IOException("Duplicate content-length header"); - } - sawLength = true; - } - - if (headerNameString.equalsIgnoreCase(CONTENT_TYPE)) { - if (sawType) { - throw new IOException("Duplicate content-type header"); - } - sawType = true; - } - - int headerValueLength = di.readUnsignedShort(); - - byte[] headerValueBytes = new byte[headerValueLength]; - - di.readFully(headerValueBytes); - - headers.add(new Header(headerNameString, headerValueBytes)); - - } - } while (!sawEmpty); - - if (!sawLength) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Content Length header was missing"); - } - throw new IOException("Content Length header was missing"); - } - - if (!sawType) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Content Type header was missing"); - } - throw new IOException("Content Type header was missing"); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - - result.append('['); - - Iterator
      eachHeader = getHeaders(); - - while (eachHeader.hasNext()) { - Header aHeader = eachHeader.next(); - - result.append(" {"); - result.append(aHeader); - result.append('}'); - - if (eachHeader.hasNext()) { - result.append(','); - } - } - - result.append(']'); - - return result.toString(); - } - - /** - * Returns number of header elements otherwise -1 - * - * @param buffer the byte buffer - * @return number of header elements - */ - private int getHeaderCount(ByteBuffer buffer) { - int pos = buffer.position(); - int limit = buffer.limit(); - int headerCount = 0; - boolean sawZero = false; - - while (pos < limit) { - // get header name length - int len = buffer.get(pos) & 0xFF; - - pos += 1; - - if (0 == len) { - sawZero = true; - break; - } - - // advance past name - pos += len; - - if ((pos + 2) >= limit) { - // not enough data - break; - } - - // get value length - len = buffer.getShort(pos) & 0xFFFF; - pos += 2; - - // advance past value - pos += len; - - headerCount++; - } - - return sawZero ? headerCount : -1; - } - - /** - * Reads a Header from a ByteBuffer - * - * @param buffer the input buffer - * @return {@code true} If the header block was completely read. - * @throws IOException if an io error is encountered - */ - public boolean readHeader(ByteBuffer buffer) throws IOException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Parsing Package Header from byte buffer :{0}", buffer.toString())); - } - - int count = getHeaderCount(buffer); - - if (count < 0) { - return false; - } - for (int i = 1; i <= count; i++) { - byte headerNameLength = buffer.get(); - byte[] headerNameBytes = new byte[headerNameLength]; - - buffer.get(headerNameBytes); - String headerNameString = new String(headerNameBytes, "UTF-8"); - int headerValueLength = buffer.getShort() & 0x0FFFF; // unsigned - byte[] headerValueBytes = new byte[headerValueLength]; - - buffer.get(headerValueBytes); - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer(MessageFormat.format("Adding Name {0}: {1}", headerNameString, headerValueBytes)); - } - headers.add(new Header(headerNameString, headerValueBytes)); - } - - // get the end-of-pkg - buffer.get(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer(MessageFormat.format("Parsed {0} header elements, buffer stats :{1}", count, buffer.toString())); - } - return true; - } - - /** - * Add a header. - * - * @param name The header name. The UTF-8 encoded representation of this - * name may not be longer than 255 bytes. - * @param value The value for the header. May not exceed 65535 bytes in - * length. - */ - public void addHeader(String name, byte[] value) { - if (name.length() > 255) { - throw new IllegalArgumentException("name may not exceed 255 bytes in length."); - } - - if (value.length > 65535) { - throw new IllegalArgumentException("value may not exceed 65535 bytes in length."); - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Add header :" + name + "(" + name.length() + ") with " + value.length + " bytes of value"); - } - - headers.add(new Header(name, value)); - } - - /** - * Add a header. - * - * @param name The header name. The UTF-8 encoded representation of this - * name may not be longer than 255 bytes. - * @param value The value for the header. May not exceed 65535 bytes in - * length. - */ - public void addHeader(String name, String value) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Add header :" + name + "(" + name.length() + ") with " + value.length() + " chars of value"); - } - - try { - addHeader(name, value.getBytes("UTF-8")); - } catch (UnsupportedEncodingException never) { - // utf-8 is a required encoding. - throw new IllegalStateException("UTF-8 encoding support missing!"); - } - } - - /** - * Replace a header. Replaces all existing headers with the same name. - * - * @param name The header name. The UTF-8 encoded representation of this - * name may not be longer than 255 bytes. - * @param value The value for the header. May not exceed 65535 bytes in - * length. - */ - public void replaceHeader(String name, byte[] value) { - if (name.length() > 255) { - throw new IllegalArgumentException("name may not exceed 255 bytes in length."); - } - - if (value.length > 65535) { - throw new IllegalArgumentException("value may not exceed 65535 bytes in length."); - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Replace header :" + name + "(" + name.length() + ") with " + value.length + " bytes of value"); - } - - Header newHeader = new Header(name, value); - ListIterator
      eachHeader = getHeaders(); - boolean replaced = false; - - while (eachHeader.hasNext()) { - Header aHeader = eachHeader.next(); - - if (aHeader.getName().equalsIgnoreCase(name)) { - eachHeader.set(newHeader); - replaced = true; - } - } - - if(!replaced) { - headers.add(newHeader); - } - } - - /** - * Replace a header. Replaces all existing headers with the same name - * - * @param name The header name. The UTF-8 encoded representation of this - * name may not be longer than 255 bytes. - * @param value The value for the header. May not exceed 65535 bytes in - * length. - */ - public void replaceHeader(String name, String value) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Replace header :" + name + "(" + name.length() + ") with " + value.length() + " chars of value"); - } - - try { - replaceHeader(name, value.getBytes("UTF-8")); - } catch (UnsupportedEncodingException never) { - // utf-8 is a required encoding. - throw new IllegalStateException("UTF-8 encoding support missing!"); - } - } - - /** - * Gets all of the headers. This iterator provides access to the live - * data of this instance. Modifying the headers using {@code add()}, - * {@code set()}, {@code remove()} is permitted. - * - * @return all of the headers - */ - public ListIterator
      getHeaders() { - return headers.listIterator(); - } - - /** - * Gets all of the headers matching the specified name - * - * @param name the name of the header we are seeking. - */ - public Iterator
      getHeader(String name) { - List
      matchingHeaders = new ArrayList
      (); - - for (Header aHeader : headers) { - if (name.equals(aHeader.getName())) { - matchingHeaders.add(aHeader); - } - } - return matchingHeaders.iterator(); - } - - /** - * Write this group of header elements to a stream. - * - * @param out the stream to send the headers to. - * @throws java.io.IOException if an io error occurs - */ - public void sendToStream(OutputStream out) throws IOException { - Iterator
      eachHeader = getHeaders(); - DataOutput dos = new DataOutputStream(out); - - // todo 20021014 bondolo@jxta.org A framing signature would help here - - while (eachHeader.hasNext()) { - Header aHeader = eachHeader.next(); - - byte[] nameBytes = aHeader.getName().getBytes("UTF-8"); - byte[] value = aHeader.getValue(); - - assert nameBytes.length <= 255; - assert value.length <= 65535; - - dos.write(nameBytes.length); - dos.write(nameBytes); - dos.writeShort(value.length); - dos.write(value); - } - - // write empty header - dos.write(0); - } - - /** - * Return a ByteBuffer representing this group of header elements. - * - * @return ByteBuffer representing this Header - */ - public ByteBuffer getByteBuffer() { - // note: according to the spec this may exceed MAX_HEADER_LEN, - // but since there are practically only 3 header elements used - // it's safe to assume this implemention detail. - ByteBuffer buffer = ByteBuffer.allocate(MAX_HEADER_LEN); - - for (Header header : headers) { - byte[] name; - - try { - name = header.getName().getBytes("UTF-8"); - } catch (UnsupportedEncodingException never) { - throw new Error("Required UTF-8 encoding not available."); - } - - byte[] value = header.getValue(); - - assert name.length <= 255; - assert value.length <= 65535; - - buffer.put((byte) name.length); - buffer.put(name); - buffer.putShort((short) value.length); - buffer.put(value); - } - - // write empty header - buffer.put((byte) 0); - buffer.flip(); - - return buffer; - } - - /** - * Convenience method setting the "{@code content-length}" header. - * - * @param length length of the message. - */ - public void setContentLengthHeader(long length) { - byte[] lengthAsBytes = new byte[8]; - - for (int eachByte = 0; eachByte < 8; eachByte++) { - lengthAsBytes[eachByte] = (byte) (length >> ((7 - eachByte) * 8L)); - } - - replaceHeader(CONTENT_LENGTH, lengthAsBytes); - } - - /** - * Convenience method for getting the "{@code content-length}" header. - * - * @return length from the header or -1 if there was no - * {@code content-length} header element. - */ - public long getContentLengthHeader() { - Iterator
      it = getHeader(CONTENT_LENGTH); - - if (!it.hasNext()) { - return -1L; - } - Header header = it.next(); - byte[] lengthAsBytes = header.getValue(); - - long lengthAsLong = 0L; - - for (int eachByte = 0; eachByte < 8; eachByte++) { - lengthAsLong |= ((long) (lengthAsBytes[eachByte] & 0xff)) << ((7 - eachByte) * 8L); - } - - return lengthAsLong; - } - - /** - * Convenience method for setting the "{@code content-type}" header. - * - * @param type type of the message. - */ - public void setContentTypeHeader(MimeMediaType type) { - replaceHeader(CONTENT_TYPE, type.toString()); - } - - /** - * Convenience method for getting the "{@code content-type}" header. - * - * @return type from the header or "{@code application/octet-stream}" if - * there was no {@code content-type} header. - */ - public MimeMediaType getContentTypeHeader() { - Iterator
      it = getHeader(CONTENT_TYPE); - - if (!it.hasNext()) { - // return the generic type. Better than returning "null". - return MimeMediaType.AOS; - } - Header header = it.next(); - - return MimeMediaType.valueOf(header.getValueString()); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/msgframing/WelcomeMessage.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/msgframing/WelcomeMessage.java deleted file mode 100644 index 6bce09d2..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/msgframing/WelcomeMessage.java +++ /dev/null @@ -1,529 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.msgframing; - - -import java.io.EOFException; -import java.io.InputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.ByteBuffer; -import java.nio.BufferUnderflowException; -import java.util.Arrays; -import java.util.List; -import java.text.MessageFormat; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * Contains a JXTA connection Welcome Message. The Welcome Message is sent by - * both participant peers as the first interchange on newly opened connections. - *

      - *

      The Welcome Message contains the following information: - *

        - *
      • The address to which the local peer believes it is connected.
      • - *
      • The local peer's return address, the source address.
      • - *
      • The local peer's peer id.
      • - *
      • A flag which controls propagation behaviour for this conneciton.
      • - *
      - * - * @see JXTA Protocols Specification : TCP/IP Message Transport - */ -public class WelcomeMessage { - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(WelcomeMessage.class.getName()); - - /** - * The Welcome Message Signature/Preamble - */ - private final static String GREETING = "JXTAHELLO"; - - /** - * A space for separating elements of the welcome message. - */ - private final static String SPACE = " "; - - /** - * Version string for Welcome Message Version 1.1 - */ - private final static String WELCOME_VERSION_1_1 = "1.1"; - - /** - * Version string for Welcome Message Version 3.0 - */ - private final static String WELCOME_VERSION_3_0 = "3.0"; - - /** - * The current welcome message version. This is the only version we will emit. - */ - private final static String CURRENTVERSION = WELCOME_VERSION_1_1; - - /** - * The destination address that we believe we are connecting to. - */ - private EndpointAddress destinationAddress; - - /** - * Our return address, the purported source address of this connection. - */ - private EndpointAddress publicAddress; - - /** - * Our peerid, the logical return address. - */ - private ID peerID; - - /** - * This connection does not wish to receive any propagation/broadcast/notifications. - */ - private boolean noPropagate; - - /** - * The preferred binary wire message format version. - */ - private int preferredMessageVersion; - - /** - * The welcome message version we are supporting - */ - private String versionString; - - /** - * The welcome message as a text string. - */ - private String welcomeString; - - /** - * The welcome message as UTF-8 byte stream. - */ - private byte[] welcomeBytes; - private final int MAX_LEN = 4096; - - /** - * Default constructor - */ - public WelcomeMessage() {} - - /** - * Creates a new instance of WelcomeMessage for our Welcome Message. - * - * @param destAddr The destination address that we believe we are connecting to. - * @param publicaddress Our return address, the purported source address of this connection. - * @param peerid Our peerid, the logical return address. - * @param dontPropagate If true this connection does not wish to receive any propagation/broadcast/notifications. - */ - public WelcomeMessage(EndpointAddress destAddr, EndpointAddress publicaddress, ID peerid, boolean dontPropagate) { - this(destAddr, publicaddress, peerid, dontPropagate, 0); - } - - /** - * Creates a new instance of WelcomeMessage for our Welcome Message. - * - * @param destAddr The destination address that we believe we are connecting to. - * @param publicaddress Our return address, the purported source address of this connection. - * @param peerid Our peerid, the logical return address. - * @param dontPropagate If true this connection does not wish to receive any propagation/broadcast/notifications. - * @param preferredMsgVersion Binary Wire Messsage format we prefer. - */ - public WelcomeMessage(EndpointAddress destAddr, EndpointAddress publicaddress, ID peerid, boolean dontPropagate, int preferredMsgVersion) { - destinationAddress = destAddr; - publicAddress = publicaddress; - peerID = peerid; - noPropagate = dontPropagate; - versionString = CURRENTVERSION; - preferredMessageVersion = preferredMsgVersion; - - welcomeString = GREETING + SPACE + destAddr.toString() + SPACE + publicAddress.toString() + SPACE + peerID.toString() - + SPACE + (noPropagate ? "1" : "0") + SPACE + versionString; - - try { - welcomeBytes = welcomeString.getBytes("UTF-8"); - } catch (UnsupportedEncodingException never) {// all implementations must support utf-8 - } - } - - /** - * Creates a new instance of WelcomeMessage for another peer's Welcome Message - * - * @param in The InputStream to read the welcome message from. - * @throws IOException If there is a problem reading the welcome header. - */ - public WelcomeMessage(InputStream in) throws IOException { - welcomeBytes = new byte[MAX_LEN]; - int readAt = 0; - boolean sawCR = false; - boolean sawCRLF = false; - - // read the welcome message - do { - int c = in.read(); - - switch (c) { - case -1: - throw new EOFException("Stream terminated before end of welcome message"); - - case '\r': - if (sawCR) { - welcomeBytes[readAt++] = (byte) 0x0D; - } - sawCR = true; - break; - - case '\n': - if (sawCR) { - sawCRLF = true; - } else { - welcomeBytes[readAt++] = (byte) 0x0A; - } - break; - - default: - welcomeBytes[readAt++] = (byte) c; - sawCR = false; - } - - if (readAt == welcomeBytes.length) { - throw new IOException("Invalid welcome message, too long"); - } - - } while (!sawCRLF); - - byte[] truncatedBytes = new byte[readAt]; - - System.arraycopy(welcomeBytes, 0, truncatedBytes, 0, readAt); - welcomeBytes = truncatedBytes; - welcomeString = new String(welcomeBytes, "UTF-8"); - parseWelcome(welcomeString); - } - - /** - * Attempts to init a welcome object from a socketChannel - * - * @param buffer the data buffer - * @return null if incomplete welcome was received - * @throws IOException if an io error occurs - */ - public boolean read(ByteBuffer buffer) throws IOException { - int limit = buffer.limit(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Reading a buffer of size :{0}", limit)); - } - if (limit == 0) { - throw new IOException(MessageFormat.format("Invalid welcome message. Invalid length {0}", limit)); - } - int eomPos = findEom(buffer, 0, limit); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Buffer size :{0} Welcome End-Of-Message pos :{1}", limit, eomPos)); - } - if (eomPos < 0) { - return false; - } - welcomeBytes = new byte[eomPos]; - try { - buffer.get(welcomeBytes, 0, eomPos); - // skip - buffer.position(eomPos + 2); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("buffer stats :{0}", buffer.toString())); - } - } catch (BufferUnderflowException buf) { - // not enough data, signal for another read - return false; - } - welcomeString = new String(welcomeBytes, "UTF-8"); - parseWelcome(welcomeString); - return true; - } - - /** - * returns position of position in buffer, otherwise -1 - * - * @param buffer the byte buffer - * @param offset The offset within the buffer array - * @param length the length - * @return terminating position, or -1 if none found - */ - private int findEom(ByteBuffer buffer, int offset, int length) { - - int lastOffset = length - 2; // we are looking for 2 chars. - - for (int j = offset; j <= lastOffset; j++) { - byte c = buffer.get(j); - - if (c == '\r') { - c = buffer.get(j + 1); - - if (c == '\n') { - return j; - } - } - } - - return -1; - } - - private void parseWelcome(String welcomeString) throws IOException { - List thePieces = Arrays.asList(welcomeString.split("\\s")); - - if (0 == thePieces.size()) { - throw new IOException("Invalid welcome message, did not contain any tokens."); - } - - if (thePieces.size() < 5) { - throw new IOException("Invalid welcome message, did not contain enough tokens."); - } - - if (!GREETING.equals(thePieces.get(0))) { - throw new IOException("Invalid welcome message, did not start with greeting"); - } - - try { - destinationAddress = new EndpointAddress(thePieces.get(1)); - } catch (IllegalArgumentException badAddress) { - IOException failed = new IOException("Invalid welcome message, bad destination address"); - - failed.initCause(badAddress); - throw failed; - } - - try { - publicAddress = new EndpointAddress(thePieces.get(2)); - } catch (IllegalArgumentException badAddress) { - IOException failed = new IOException("Invalid welcome message, bad publicAddress address"); - - failed.initCause(badAddress); - throw failed; - } - - try { - URI peerURI = new URI(thePieces.get(3)); - - peerID = IDFactory.fromURI(peerURI); - } catch (URISyntaxException badURI) { - IOException failed = new IOException("Invalid welcome message, bad peer id"); - - failed.initCause(badURI); - throw failed; - } - - versionString = thePieces.get(thePieces.size() - 1); - - if (WELCOME_VERSION_1_1.equals(versionString)) { - if (6 != thePieces.size()) { - throw new IOException("Invalid welcome message, incorrect number of tokens."); - } - - String noPropagateStr = thePieces.get(4); - - if (noPropagateStr.equals("1")) { - noPropagate = true; - } else if (noPropagateStr.equals("0")) { - noPropagate = false; - } else { - throw new IOException("Invalid welcome message, illegal value for propagate flag"); - } - - // preferred message version is not set in - preferredMessageVersion = 0; - } else if (WELCOME_VERSION_3_0.equals(versionString)) { - if (7 != thePieces.size()) { - throw new IOException("Invalid welcome message, incorrect number of tokens."); - } - - String noPropagateStr = thePieces.get(4); - - if (noPropagateStr.equals("1")) { - noPropagate = true; - } else if (noPropagateStr.equals("0")) { - noPropagate = false; - } else { - throw new IOException("Invalid welcome message, illegal value for propagate flag"); - } - - String preferredVersionStr = thePieces.get(5); - - try { - preferredMessageVersion = Integer.valueOf(preferredVersionStr); - } catch (IllegalArgumentException failed) { - IOException failure = new IOException("Invalid welcome message, illegal value for preferred message version"); - - failure.initCause(failed); - - throw failure; - } - } else { - // Unrecognized Welcome message version. Use default values. - noPropagate = false; - preferredMessageVersion = 0; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Successfuly parsed a welcome message :" + getWelcomeString()); - } - } - - /** - * Write the welcome message to the provided stream. - * - * @param theStream The OutputStream to which to write the welcome message. - * @throws IOException If there is a problem writing the welcome message. - */ - public void sendToStream(OutputStream theStream) throws IOException { - theStream.write(welcomeBytes); - theStream.write('\r'); - theStream.write('\n'); - } - - /** - * Write the welcome to a socket channel - * - * @return A ByteBuffer of the welcome message - * @throws java.io.IOException if an io error occurs - */ - public ByteBuffer getByteBuffer() throws IOException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Sending welcome message of size:{0}", welcomeBytes.length + 2)); - } - ByteBuffer buffer = ByteBuffer.allocate(welcomeBytes.length + 2); - - buffer.put(welcomeBytes); - buffer.put((byte) '\r'); - buffer.put((byte) '\n'); - buffer.flip(); - return buffer; - } - - /** - * Return the peerid associated with the Welcome Message. - * - * @return The peer ID from the Welcome Message. - */ - public ID getPeerID() { - return peerID; - } - - /** - * Return the source address associated with the Welcome Message. - * - * @return The source address from the Welcome Message. - */ - public EndpointAddress getPublicAddress() { - return publicAddress; - } - - /** - * Return the destination address associated with the Welcome Message. - * - * @return The destination address from the Welcome Message. - */ - public EndpointAddress getDestinationAddress() { - return destinationAddress; - } - - /** - * Return the propagation preference from the Welcome Message. - * - * @return true if no propagation is desired - * otherwise false - */ - public boolean dontPropagate() { - return noPropagate; - } - - /** - * Return the preferred message version from the Welcome Message. - * - * @return The preferred Message Version. - */ - public int getPreferredMessageVersion() { - return preferredMessageVersion; - } - - /** - * Return the version associated with the Welcome Message. - * - * @return The version from the Welcome Message. - */ - public String getWelcomeVersion() { - return versionString; - } - - /** - * Return a String containing the Welcome Message. - * - * @return a String containing the Welcome Message. - */ - public String getWelcomeString() { - return welcomeString; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/package.html deleted file mode 100644 index acd637cf..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/package.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.endpoint.EndpointService} implementation which - implements the standard JXTA Endpoint Service. - - @see JXTA Protocols Specification : Endpoint Service - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayClient.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayClient.java deleted file mode 100644 index ab5ac489..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayClient.java +++ /dev/null @@ -1,1351 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.relay; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.MessageReceiver; -import net.jxta.endpoint.MessageSender; -import net.jxta.endpoint.MessageTransport; -import net.jxta.endpoint.Messenger; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.protocol.RelayConfigAdv; -import net.jxta.impl.util.SeedingManager; -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.util.URISeedingManager; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.AccessPointAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * RelayClient manages the relationship with the RelayServer(s) - * - */ -public class RelayClient implements MessageReceiver, Runnable { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(RelayClient.class.getName()); - - private final static long DEFAULT_EXPIRATION = 20L * TimeUtils.AMINUTE; - - private final PeerGroup group; - private final String serviceName; - private EndpointService endpoint; - private final EndpointAddress publicAddress; - private final String groupName; - private final String peerId; - - private final int maxServers; - private final long leaseLengthToRequest; - private final long messengerPollInterval; - - private Thread thread = null; - - private volatile boolean closed = false; - - /** - *
        - *
      • Values are {@link net.jxta.peergroup.PeerGroup}.
      • - *
      - */ - private final List activeRelayListeners = new ArrayList(); - - /** - *
        - *
      • Keys are {@link net.jxta.endpoint.EndpointAddress}.
      • - *
      • Values are {@link net.jxta.protocol.RouteAdvertisement}.
      • - *
      - */ - private final Map activeRelays = new Hashtable(); - - /** - * Our source for relay servers. - */ - private final SeedingManager seedingManager; - - RelayServerConnection currentServer = null; - - public RelayClient(PeerGroup group, String serviceName, RelayConfigAdv relayConfig) { - this.group = group; - this.groupName = group.getPeerGroupID().getUniqueValue().toString(); - - this.serviceName = serviceName; - - maxServers = (-1 != relayConfig.getMaxRelays()) ? relayConfig.getMaxRelays() : RelayTransport.DEFAULT_MAX_SERVERS; - leaseLengthToRequest = (-1 != relayConfig.getClientLeaseDuration()) - ? relayConfig.getClientLeaseDuration() - : RelayTransport.DEFAULT_LEASE; - messengerPollInterval = (-1 != relayConfig.getMessengerPollInterval()) - ? relayConfig.getMessengerPollInterval() - : RelayTransport.DEFAULT_POLL_INTERVAL; - - URISeedingManager uriSeedingManager = new URISeedingManager(relayConfig.getAclUri(), relayConfig.getUseOnlySeeds(), group, serviceName); - - for (EndpointAddress aSeeder : Arrays.asList(relayConfig.getSeedRelays())) { - uriSeedingManager.addSeed(aSeeder.toURI()); - } - - for (URI aSeed : Arrays.asList(relayConfig.getSeedingURIs())) { - uriSeedingManager.addSeedingURI(aSeed); - } - - this.seedingManager = uriSeedingManager; - - // sanity check - - peerId = group.getPeerID().getUniqueValue().toString(); - publicAddress = new EndpointAddress(RelayTransport.protocolName, peerId, null, null); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Relay Client"); - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID : ").append(group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tService Name : ").append(serviceName); - configInfo.append("\n\t\tPublic Address : ").append(publicAddress); - configInfo.append("\n\t\tMax Relay Servers : ").append(maxServers); - configInfo.append("\n\t\tMax Lease Length : ").append(leaseLengthToRequest).append("ms."); - configInfo.append("\n\t\tMessenger Poll Interval : ").append(messengerPollInterval).append("ms."); - LOG.config(configInfo.toString()); - } - } - - public synchronized boolean startClient() { - endpoint = group.getEndpointService(); - - if (endpoint.addMessageTransport(this) == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Transport registration refused"); - } - return false; - } - - // start the client thread - thread = new Thread(group.getHomeThreadGroup(), this, "Relay Client Worker Thread for " + publicAddress); - thread.setDaemon(true); - thread.start(); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Started client : " + publicAddress.toString()); - } - - return true; - } - - public synchronized void stopClient() { - if (closed) { - return; - } - - closed = true; - - endpoint.removeMessageTransport(this); - - // make sure the thread is not running - Thread tempThread = thread; - - thread = null; - if (tempThread != null) { - tempThread.interrupt(); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Stopped client : " + publicAddress.toString()); - } - - } - - /** - * {@inheritDoc} - */ - public Iterator getPublicAddresses() { - - return Collections.singletonList(publicAddress).iterator(); - } - - /** - * {@inheritDoc} - */ - public String getProtocolName() { - return RelayTransport.protocolName; - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - return endpoint; - } - - /** - * {@inheritDoc} - */ - public Object transportControl(Object operation, Object Value) { - return null; - } - - /** - * Logic for the relay client - * - *
        - *
      1. Pick a relay server to try
      2. - *
      3. try getting a messenger to relay server, if can not get messenger, start over
      4. - *
      5. use the messenger to send a connect message
      6. - *
      7. wait for a response, if there is no response or a disconnect response, start over
      8. - *
      9. while still connected - *
          - *
        1. renew the lease as needed and keep the messenger connected
        2. - *
            - *
          - * - *

          FIXME 20041102 bondolo The approach used here is really, really - * stupid. The calls to connectToRelay() will not return if a - * connection to a relay is achieved. This makes continued iteration over - * seeds after return incredibly silly. connectToRelay() only - * returns when it can NO LONGER CONNECT to the relay. The only - * hack I can think of to subvert this is to stop iteration of advs/seeds - * if connectToRelay() takes a long time. bizarre. - */ - public void run() { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Start relay client thread"); - } - - try { - long nextConnectAttemptAt = 0; - - RdvAdvertisement referral = null; - List allSeeds = null; - long gotLastSeedsAt = 0; - - // run until the service is stopped - while (!closed) { - // Attempt to use any referral immediately. - if (null != referral) { - RouteAdvertisement relayRoute = referral.getRouteAdv(); - - relayRoute.setDestPeerID(referral.getPeerID()); - - referral = connectToRelay(new RelayServerConnection(this, relayRoute)); - - continue; - } - - // Sleep until it is time for the next connection attempt. - long untilNextConnectAttempt = TimeUtils.toRelativeTimeMillis(nextConnectAttemptAt); - - if (untilNextConnectAttempt > 0) { - try { - Thread.sleep(untilNextConnectAttempt); - } catch (InterruptedException e) { - // ignore interrupted exception - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Thread Interrupted ", e); - } - - continue; - } - } - - // Don't allow next connection attempt to start any sooner than this. - nextConnectAttemptAt = TimeUtils.toAbsoluteTimeMillis(30 * TimeUtils.ASECOND); - - // Get seeds if we need them or the ones we have are old. - if ((TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), gotLastSeedsAt) > (5 * TimeUtils.AMINUTE)) - || allSeeds.isEmpty()) { - allSeeds = new ArrayList(Arrays.asList(seedingManager.getActiveSeedRoutes())); - gotLastSeedsAt = TimeUtils.timeNow(); - } - - // Try seeds until we get a connection, a referral or are closed. - while ((null == referral) && !allSeeds.isEmpty() && !closed) { - RouteAdvertisement aSeed = allSeeds.remove(0); - - if (null == aSeed.getDestPeerID()) { - // It is an incomplete route advertisement. We are going to assume that it is only a wrapper for a single ea. - Vector seed_eas = aSeed.getDest().getVectorEndpointAddresses(); - - if (!seed_eas.isEmpty()) { - EndpointAddress aSeedHost = new EndpointAddress(seed_eas.get(0)); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Attempting relay connect to : " + aSeedHost); - } - - referral = connectToRelay(new RelayServerConnection(this, aSeedHost)); - } - } else { - // We have a full route, send it to the virtual address of the route! - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Attempting relay connect to : " + aSeed.getDestPeerID()); - } - - referral = connectToRelay(new RelayServerConnection(this, aSeed)); - } - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - thread = null; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("stop client thread"); - } - } - } - - protected boolean isRelayConnectDone() { - return (thread == null || Thread.currentThread() != thread); - } - - /** - * @param server The relay server to connect to - * @return The advertisement of an alternate relay server to try. - */ - RdvAdvertisement connectToRelay(RelayServerConnection server) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Connecting to " + server); - } - - RdvAdvertisement referral = null; - - // make this the current server - currentServer = server; - - // try getting a messenger to the relay peer - if (!server.createMessenger(leaseLengthToRequest)) { - return referral; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("got messenger " + server); - } - - // check the peerId of the relay peer - if (server.logicalAddress != null && "jxta".equals(server.logicalAddress.getProtocolName())) { - server.peerId = server.logicalAddress.getProtocolAddress(); - } - - // make sure that the peerId was found. - if (server.peerId == null) { - if (server.messenger != null) { - server.sendDisconnectMessage(); - server.messenger.close(); - } - return referral; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("got peerId " + server); - } - - synchronized (this) { - // wait for a response from the server - // There is no real damage other than bandwidth usage in sending - // a message on top of the connection request, so we realy do not - // wait very long before doing it. - long requestTimeoutAt = TimeUtils.toAbsoluteTimeMillis(5 * TimeUtils.ASECOND); - - while (currentServer != null && currentServer.leaseLength == 0 && !isRelayConnectDone()) { - long waitTimeout = requestTimeoutAt - System.currentTimeMillis(); - - if (waitTimeout <= 0) { - // did not receive the response in time ? - break; - } - - try { - wait(waitTimeout); - } catch (InterruptedException e) { - // ignore interrupt - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "wait got interrupted early ", e); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("wait done"); - } - } - } - - if (currentServer == null) { - return server.alternateRelayAdv; - } - - if (isRelayConnectDone()) { - if (currentServer.messenger != null) { - currentServer.messenger.close(); - } - currentServer = null; - return server.alternateRelayAdv; - } - - // If we did not get a lease in the first 5 secs, maybe it is because - // the server knows us from a previous session. Then it will wait for - // a lease renewal message before responding, not just the connection. - // Send one and wait another 15. - if (currentServer.leaseLength == 0) { - - currentServer.sendConnectMessage(leaseLengthToRequest); - - synchronized (this) { - - // wait for a response from the server - long requestTimeoutAt = TimeUtils.toAbsoluteTimeMillis(15 * TimeUtils.ASECOND); - - while (currentServer != null && currentServer.leaseLength == 0 && !isRelayConnectDone()) { - long waitTimeout = requestTimeoutAt - System.currentTimeMillis(); - - if (waitTimeout <= 0) { - // did not receive the response in time ? - break; - } - - try { - wait(waitTimeout); - } catch (InterruptedException e) { - // ignore interrupt - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "wait got interrupted early ", e); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("wait done"); - } - } - } - } - - // If we had a messenger but are going to give up that relay server because it is - // not responsive or rejected us. Make sure that the messenger is closed. - if (currentServer == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("did not get connect from " + server); - } - // return any alternate relay advertisements - return server.alternateRelayAdv; - } - - if (currentServer.relayAdv == null || currentServer.leaseLength == 0 || isRelayConnectDone()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("did not get connect from " + server); - } - if (currentServer.messenger != null) { - currentServer.sendDisconnectMessage(); - currentServer.messenger.close(); - } - currentServer = null; - - // return any alternate relay advertisements - return server.alternateRelayAdv; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Connected to " + server); - } - - RouteAdvertisement holdAdv = server.relayAdv; - EndpointAddress holdDest = server.logicalAddress; - - // register this relay server - addActiveRelay(holdDest, holdAdv); - - // maintain the relay server connection - referral = maintainRelayConnection(server); - - // unregister this relay server - removeActiveRelay(holdDest, holdAdv); - - return referral; - } - - // FIXME: jice@jxta.org 20030212. This is junk code: that should be a - // method of RelayServerConnection and at least not refer to currentServer - // other than to assign the reference. - protected RdvAdvertisement maintainRelayConnection(RelayServerConnection server) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("maintainRelayConnection() start " + currentServer); - } - - if (server == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RelayConnection() failed at start " + currentServer); - } - return null; - } - - synchronized (this) { - long currentTime = System.currentTimeMillis(); - long renewLeaseAt = currentServer.leaseObtainedAt + currentServer.leaseLength / 3; - long waitTimeout = 0; - - // This will be true if we need to do the first lease renewal early - // (that is at the time of the next connection check). - // We'll do that if we did not know the relay server's adv (seed). - // In that case we told the relay server to send us its own - // adv, else we told it to send us some alternate adv (we have to - // chose). In the former case, we want to do a lease connect - // request soon so that the server has an opportunity to send us - // the alternate adv that we did not get during initial connection. - - boolean earlyRenew = currentServer.seeded; - - while (currentServer != null && !isRelayConnectDone()) { - // calculate how long to wait - waitTimeout = renewLeaseAt - currentTime; - - // check that the waitTimeout is not greater than the messengerPollInterval - // We want to make sure that we poll. Most of the time it cost nothing. - // Also, if we urgently need to renew our lease we may wait - // less, but if we fail to get our lease renewed in time, the - // delay may become negative. In that case we do not want - // to start spinning madly. The only thing we can do is just - // wait some arbitrary length of time for the lease to be - // renewed. (If that gets badly overdue, we should probably - // give up on that relay server, though). - if (waitTimeout > messengerPollInterval || waitTimeout <= 0) { - waitTimeout = messengerPollInterval; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("waitTimeout=" + waitTimeout + " server=" + currentServer); - } - - try { - wait(waitTimeout); - } catch (InterruptedException e) { - Thread.interrupted(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("wait done, server=" + currentServer); - } - - // make sure the server did not disconnect while waiting - if (currentServer == null) { - break; - } - - // get the current time - currentTime = System.currentTimeMillis(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("check messenger " + currentServer); - } - - // check if the messenger is still open - if (currentServer.messenger.isClosed()) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Server connection broken"); - } - - // See if we can re-open, that happens often. - // That's a reason to renew the connection, - // Not a reason to give up on the server yet. - // Note we do not renew the lease. This is a transient - // and if the server forgot about us, it will respond - // to the connection alone. Otherwise, we'd rather avoid - // getting a response, since in some cases http connections - // close after each received message. - if (!currentServer.createMessenger(currentServer.leaseLength)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Server connection NOT re-established"); - } - // lost connection to relay server - currentServer = null; - break; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Server connection re-established"); - } - - // getMessenger asks for a new lease. - // In the meantime, we'll just assume our old lease is - // still current and that the messenger breakage was just - // a transient. - if (!isRelayConnectDone()) { - continue; - } - } - - // We've been asked to leave. Be nice and tell the - // server about it. - if (isRelayConnectDone()) { - break; - } - - // check if the lease needs to be renewed - renewLeaseAt = currentServer.leaseObtainedAt + currentServer.leaseLength / 3; - if (currentTime >= renewLeaseAt || earlyRenew) { - - earlyRenew = false; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("renew lease " + currentServer); - } - - // If we do not receive any response to our lease renewals - // (that is the response is overdue badly), then we give - // up and try another relayServer. We give up after 4 minutes - // because if we go as far as 5 we start overshooting other - // timeouts such as the local peer becoming a rdv in a sub-group. - // This later timeout is usually set to 5 minutes or more. - - if ((currentTime > currentServer.leaseObtainedAt + currentServer.leaseLength / 3 + 4 * TimeUtils.AMINUTE) - || (!currentServer.sendConnectMessage(leaseLengthToRequest))) { - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("renew lease failed" + currentServer); - } - if (currentServer.messenger != null) { - currentServer.messenger.close(); - } - currentServer.messenger = null; - currentServer.peerId = null; - currentServer.leaseLength = 0; - currentServer.leaseObtainedAt = 0; - currentServer.relayAdv = null; - currentServer = null; - break; - } - } - } - } - - if (isRelayConnectDone() && currentServer != null) { - currentServer.sendDisconnectMessage(); - if (currentServer.messenger != null) { - currentServer.messenger.close(); - } - currentServer.messenger = null; - currentServer.peerId = null; - currentServer.leaseLength = 0; - currentServer.leaseObtainedAt = 0; - currentServer.relayAdv = null; - // Make sure that we will not suggest an alternate - // since we're asked to terminate. - currentServer.alternateRelayAdv = null; - - currentServer = null; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("maintainRelayConnection() terminated " + currentServer); - } - - return server.alternateRelayAdv; - } - - protected synchronized void handleResponse(Message message, EndpointAddress dstAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("handleResponse " + currentServer); - } - - // ignore all responses if there is not a current server - if (currentServer == null) { - return; - } - - // get the request, make it lowercase so that case is ignored - String response = RelayTransport.getString(message, RelayTransport.RESPONSE_ELEMENT); - - if (response == null) { - return; - } - response = response.toLowerCase(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("response = " + response); - } - - // check if a relay advertisement was included - RdvAdvertisement relayAdv = null; - - MessageElement advElement = message.getMessageElement(RelayTransport.RELAY_NS, RelayTransport.RELAY_ADV_ELEMENT); - - if (null != advElement) { - try { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(advElement); - Advertisement adv = AdvertisementFactory.newAdvertisement(asDoc); - - if (adv instanceof RdvAdvertisement) { - relayAdv = (RdvAdvertisement) adv; - } - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Could not read Relay RdvAdvertisement", e); - } - } - } - - // WATCHOUT: this is not a pid, just the unique string portion. - String serverPeerId = dstAddr.getServiceParameter(); - - // only process the request if a client peer id was sent - if (serverPeerId == null) { - return; - } - - // ignore all responses that are not from the current server - if (!serverPeerId.equals(currentServer.peerId)) { - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("serverPeerId = " + serverPeerId); - } - - // Figure out which response it is - if (RelayTransport.CONNECTED_RESPONSE.equals(response)) { - // Connect Response - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("connected response for " + currentServer); - } - - String responseLeaseString = RelayTransport.getString(message, RelayTransport.LEASE_ELEMENT); - - long responseLease = 0; - - if (responseLeaseString != null) { - try { - responseLease = Long.parseLong(responseLeaseString); - } catch (NumberFormatException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "could not parse response lease string", e); - } - } - } - - // make sure the lease is valid - if (responseLease <= 0) { - // invalid lease value - return; - } - - // update the lease values - currentServer.leaseLength = responseLease; - currentServer.leaseObtainedAt = System.currentTimeMillis(); - - // Since we got the lease, if we requested a queue flush, it's - // now done. We never send it with a new messenger creation, but - // when the server already has us as a client it does not respond - // to connections through messenger creation, so we're sure we - // will have to send an explicit connect message before we get - // a response. So, we're sure it's done if it was needed. - currentServer.flushNeeded = false; - - if (relayAdv != null) { - // Set it only if it is the server's own. Else it got - // published. Still set alternateRelayAdv so that we - // can return something that could be usefull when this - // connection breaks. - PeerID pidOfAdv = relayAdv.getPeerID(); - String pidOfAdvUnique = pidOfAdv.getUniqueValue().toString(); - - if (currentServer.peerId.equals(pidOfAdvUnique)) { - currentServer.relayAdv = relayAdv.getRouteAdv(); - // Fix the embedded route adv ! - currentServer.relayAdv.setDestPeerID(pidOfAdv); - } else { - currentServer.alternateRelayAdv = relayAdv; - } - } - - notifyAll(); - - } else if (RelayTransport.DISCONNECTED_RESPONSE.equals(response)) { - // Disconnect Response - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("disconnected from " + currentServer); - } - - // If our request was denied, the adv that came back is - // always an alternate one. - currentServer.alternateRelayAdv = relayAdv; - - if (currentServer.messenger != null) { - currentServer.messenger.close(); - } - currentServer.messenger = null; - currentServer.peerId = null; - currentServer.leaseLength = 0; - currentServer.leaseObtainedAt = 0; - currentServer.relayAdv = null; - currentServer = null; - notifyAll(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("response handled for " + currentServer); - } - } - - static class RelayServerConnection { - final RelayClient client; - - Messenger messenger = null; - EndpointAddress logicalAddress = null; - String peerId = null; - long leaseLength = 0; - long leaseObtainedAt = 0; - - // If seeded out of a raw address, we have relayAddress. - // relayAdv comes only later. - public RouteAdvertisement relayAdv = null; - EndpointAddress relayAddress = null; - - RdvAdvertisement alternateRelayAdv = null; - boolean seeded = false; - boolean flushNeeded = true; // true until we know it's been done - - protected RelayServerConnection(RelayClient client, EndpointAddress addr) { - this.client = client; - relayAddress = new EndpointAddress(addr, null, null); - seeded = true; - } - - protected RelayServerConnection(RelayClient client, RouteAdvertisement relayAdv) { - this.client = client; - this.relayAdv = relayAdv; - } - - protected boolean createMessenger(long leaseLengthToRequest) { - - // make sure the old messenger is closed - if (messenger != null) { - messenger.close(); - messenger = null; - } - - List endpointAddresses = null; - - // check for a relay advertisement - if (relayAdv != null) { - AccessPointAdvertisement accessPointAdv = relayAdv.getDest(); - - if (accessPointAdv != null) { - endpointAddresses = accessPointAdv.getVectorEndpointAddresses(); - } - } else { - // silly but if we use getVetorEndpointAddresses, we get - // strings. It's realy simpler to have only one kind of obj - // inthere. - endpointAddresses = new ArrayList(1); - endpointAddresses.add(relayAddress.toString()); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("createMessenger to " + endpointAddresses); - } - - // make sure we found some endpoint addresses to try - if (endpointAddresses == null) { - return false; - } - - // try each endpoint address until one is successful - for (String s : endpointAddresses) { - if (s == null) { - continue; - } - EndpointAddress addr = new EndpointAddress(s); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("find transport for " + addr); - } - // get the list of messengers on this endpoint - Iterator transports = client.endpoint.getAllMessageTransports(); - - while (transports.hasNext() && messenger == null) { - MessageTransport transport = (MessageTransport) transports.next(); - - // only try transports that are senders and allow routing - if (transport instanceof MessageSender && ((MessageSender) transport).allowsRouting()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("try transport " + transport); - } - if (addr.getProtocolName().equals(transport.getProtocolName())) { - // NOTE: here we're creating a messenger. - // For risk management reason, we refrain from - // including the flush request at this time in - // this. There is the possibility that the - // connection will be repeatedly established - // by the transport in our bakck, and would keep - // including the flush request ! Normaly this - // does not matter because the server should - // disregard it when it come in that way, but - // still, let's be defensive. We will still send - // the flush in a subsequent explicit message. - String reqStr = RelayTransport.createConnectString(leaseLengthToRequest, relayAdv == null, false); - // NOTE: this is simulating address mangling by CrossgroupMessenger. - // The real service param is after the "/" in the below serviceParam arg. - EndpointAddress addrToUse = new EndpointAddress(addr, "EndpointService:" + client.groupName - , - client.serviceName + "/" + reqStr); - - messenger = ((MessageSender) transport).getMessenger(addrToUse, null); - if (messenger != null && messenger.isClosed()) { - messenger = null; - } - if (messenger != null) { - logicalAddress = messenger.getLogicalDestinationAddress(); - // We're using a known adv, which means that - // we did not ask to get the adv back. - // Make sure that we do not keep going with - // an adv for the wrong peer. That can happen. - if (relayAdv != null && !addr2pid(logicalAddress).equals(relayAdv.getDestPeerID())) { - // oops, wrong guy ! - messenger.close(); - messenger = null; - logicalAddress = null; - } - // In case it was not given, set relayAddress - // for toString purposes. - relayAddress = addr; - } - } - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("messenger=" + messenger); - } - - return (messenger != null); - } - - protected boolean sendConnectMessage(long leaseLengthToRequest) { - if (messenger == null || messenger.isClosed()) { - return false; - } - - Message message = RelayTransport.createConnectMessage(leaseLengthToRequest, (relayAdv == null), flushNeeded); - - try { - messenger.sendMessage(message, "EndpointService:" + client.groupName, client.serviceName + "/" + client.peerId); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "could not send connect message", e); - } - - // connection attempt failed - return false; - } - - return true; - } - - protected boolean sendDisconnectMessage() { - if (messenger == null || messenger.isClosed()) { - return false; - } - - Message message = RelayTransport.createDisconnectMessage(); - - try { - messenger.sendMessage(message, "EndpointService:" + client.groupName, client.serviceName + "/" + client.peerId); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "could not send disconnect message", e); - } - - // connection attempt failed - return false; - } - - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - - return - ((relayAddress == null) ? "(adv to " + relayAdv.getDestPeerID() + ")" : relayAddress.toString()) + " [" - + leaseLength + ", " + leaseObtainedAt + "] "; - } - } - - /** - * Register an active Relay to the endpoint. This is done - * so the Route Advertisement of the PeerAdvertisement is - * updated - */ - public synchronized boolean addActiveRelayListener(Object service) { - - boolean added = false; - - if (!activeRelayListeners.contains(service)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Register group to relay connection " + ((PeerGroup) service).getPeerGroupName()); - } - - activeRelayListeners.add(service); - - added = true; - } - - return added; - } - - /** - * Unregister an active Relay to the endpoint. This is done - * so the Route Advertisement of the PeerAdvertisement is - * updated - */ - public synchronized boolean removeActiveRelayListener(Object service) { - activeRelayListeners.remove(service); - - return true; - } - - /** - * Notify of a new relay connection - * - */ - public synchronized boolean addActiveRelay(EndpointAddress address, RouteAdvertisement relayRoute) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("notify add relay connection for " + address); - } - - // need to notify all our listeners - - for (Object activeRelayListener : activeRelayListeners) { - PeerGroup pg = (PeerGroup) activeRelayListener; - addRelay(pg, relayRoute); - } - - // maintain the list of active relays - activeRelays.put(address, relayRoute); - return true; - } - - /** - * Notify of a relay connection removal - * - */ - public synchronized boolean removeActiveRelay(EndpointAddress address, RouteAdvertisement relayRoute) { - - // need to notify all our listeners - - for (Object activeRelayListener : activeRelayListeners) { - PeerGroup pg = (PeerGroup) activeRelayListener; - removeRelay(pg, relayRoute); - } - - activeRelays.remove(address); - - return true; - } - - /** - * Register an active Relay to the endpoint. This is done - * so the Route Advertisement of the PeerAdvertisement is - * updated - * - * @param relayRoute address of the relay to add - */ - private void addRelay(PeerGroup pg, RouteAdvertisement relayRoute) { - - ID assignedID = PeerGroup.endpointClassID; - - try { - // get the advertisement of the associated endpoint address as we - // need to get the peer Id and available route - - // update our own peer advertisement - PeerAdvertisement padv = pg.getPeerAdvertisement(); - XMLDocument myParam = (XMLDocument) padv.getServiceParam(assignedID); - - RouteAdvertisement route; - - if (myParam == null) { - // we should have found a route here. This is not good - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("no route found in peer adv"); - } - return; - } else { - Enumeration paramChilds = myParam.getChildren(RouteAdvertisement.getAdvertisementType()); - XMLElement param = null; - - if (paramChilds.hasMoreElements()) { - param = paramChilds.nextElement(); - } - - route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(param); - } - - if (route == null) { // we should have a route here - return; - } - - // ready to stich the Relay route in our route advertisement - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("found route info for local peer \n" + route.display()); - } - - // update the new hops info - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("OLD route info to local peer \n" + route.display()); - } - - // If we already have the relay in our list of hops, remove it. - // The new version can only be more accurate. - route.removeHop(relayRoute.getDestPeerID()); - - // Get a hold of the hops list AFTER removing: removeHop - // rebuilds the vector ! - Vector hops = route.getVectorHops(); - - // Create the new relay Hop - hops.add(relayRoute.getDest()); - - // update the new hops info - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("NEW route info to local peer" + route.display()); - } - - // create the new param route - myParam = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - StructuredTextDocument xptDoc = (StructuredTextDocument) - route.getDocument(MimeMediaType.XMLUTF8); - - StructuredDocumentUtils.copyElements(myParam, myParam, xptDoc); - - padv.putServiceParam(assignedID, myParam); - - // publish the new peer advertisement - DiscoveryService discovery = pg.getDiscoveryService(); - - if (discovery != null) { - discovery.publish(padv, DiscoveryService.DEFAULT_LIFETIME, DiscoveryService.DEFAULT_EXPIRATION); - } - } catch (Exception ex) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "exception adding relay route ", ex); - } - } - } - - /** - * remove relay hop from the peer advertisement - * - * @param group which peer advertisement needs to be updated - * @param relayRoute address of the relay to be removed - */ - private void removeRelay(PeerGroup group, RouteAdvertisement relayRoute) { - - // we can keep the advertisement for now (should remove it) - // remove the relay from its active list - ID assignedID = PeerGroup.endpointClassID; - PeerID relayPid = relayRoute.getDestPeerID(); - - try { - // get the advertisement of the associated endpoint address as we - // need to get the peer Id and available route - - PeerAdvertisement padv; - - // update our peer advertisement - padv = group.getPeerAdvertisement(); - XMLDocument myParam = (XMLDocument) padv.getServiceParam(assignedID); - - RouteAdvertisement route = null; - - if (myParam == null) { - // no route found we should really have one - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("no route found in peer adv"); - return; - } - } else { - Enumeration paramChilds = myParam.getChildren(RouteAdvertisement.getAdvertisementType()); - XMLElement param = null; - - if (paramChilds.hasMoreElements()) { - param = paramChilds.nextElement(); - } - - route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement( param); - } - - if (route == null) { - return; - } // we should have a route here - - // update the new hops info - route.removeHop(relayPid); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("new route info to the peer" + route.display()); - } - - // create the new param route - myParam = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - XMLDocument xptDoc = (XMLDocument) route.getDocument(MimeMediaType.XMLUTF8); - - StructuredDocumentUtils.copyElements(myParam, myParam, xptDoc); - - padv.putServiceParam(assignedID, myParam); - - // publish the new advertisement - DiscoveryService discovery = group.getDiscoveryService(); - - if (discovery != null) { - discovery.publish(padv, DiscoveryService.DEFAULT_LIFETIME, DiscoveryService.DEFAULT_EXPIRATION); - } - } catch (Throwable theMatter) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed adding relay route", theMatter); - } - } - } - - /** - * return the list of connected relays - */ - public Vector getActiveRelays(PeerGroup pg) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("get active Relays list"); - } - - Vector hops = new Vector(); - - for (RouteAdvertisement route : activeRelays.values()) { - try { - // publish our route if pg is not null - if (pg != null) { - DiscoveryService discovery = pg.getDiscoveryService(); - - if (discovery != null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("publishing route to active relay " + route.display()); - } - discovery.publish(route, DEFAULT_EXPIRATION, DEFAULT_EXPIRATION); - } - } - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "error publishing active relay", ex); - } - continue; - } - - hops.add(route.getDest()); - } - - return hops; - } - - // convert an endpointRouterAddress into a PeerID - private static PeerID addr2pid(EndpointAddress addr) { - try { - URI asURI = new URI(ID.URIEncodingName, ID.URNNamespace + ":" + addr.getProtocolAddress(), null); - - return (PeerID) IDFactory.fromURI(asURI); - } catch (Exception ex) { - return null; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayReferralSeedingManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayReferralSeedingManager.java deleted file mode 100644 index 3c3b3e26..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayReferralSeedingManager.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (c) 2002-2004 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.relay; - -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.MessageTransport; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.RouteAdvertisement; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.impl.util.URISeedingManager; - -/** - * Extends the URI Seeding Manager by supplementing the list of active seeds - * with the active relay peers. - */ -public class RelayReferralSeedingManager extends URISeedingManager { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(RelayReferralSeedingManager.class.getName()); - - private final PeerGroup group; - - /** - * Get an instance of RelayReferralSeedingManager. - * - * @param aclLocation acl URI - * @param allowOnlySeeds if true allow only seeds - * @param group the peer group - * @param serviceName Service name - */ - public RelayReferralSeedingManager(URI aclLocation, boolean allowOnlySeeds, PeerGroup group, String serviceName) { - super(aclLocation, allowOnlySeeds, group, serviceName); - this.group = group; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized URI[] getActiveSeedURIs() { - Collection result = new ArrayList(); - Collection relays = getRelayPeers(); - - int eaIndex = 0; - boolean addedEA; - - do { - addedEA = false; - - for (RouteAdvertisement aRA : relays) { - List raEAs = aRA.getDestEndpointAddresses(); - if (eaIndex < raEAs.size()) { - URI seedURI = raEAs.get(eaIndex).toURI(); - if(!result.contains(seedURI)) { - result.add(seedURI); - } - addedEA = true; - } - } - - // Next loop we use the next most preferred address. - eaIndex++; - } while (addedEA); - - // Add the non-relay seeds afterwards. - for(URI eachURI : Arrays.asList(super.getActiveSeedURIs())) { - if(!result.contains(eachURI)) { - result.add(eachURI); - } - } - - return result.toArray(new URI[result.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized RouteAdvertisement[] getActiveSeedRoutes() { - List result = new ArrayList(getRelayPeers()); - - for(RouteAdvertisement eachRoute : Arrays.asList(super.getActiveSeedRoutes())) { - if(!result.contains(eachRoute)) { - result.add(eachRoute); - } - } - return result.toArray(new RouteAdvertisement[result.size()]); - } - - /** - * @return List of RouteAdvertisement - */ - private Collection getRelayPeers() { - Collection result = new ArrayList(); - - try { - EndpointService ep = group.getEndpointService(); - - Iterator it = ep.getAllMessageTransports(); - - while (it.hasNext()) { - MessageTransport mt = (MessageTransport) it.next(); - - if (!mt.getEndpointService().getGroup().getPeerGroupID().equals(group.getPeerGroupID())) { - // We only want relay services in this peer group. - continue; - } - - if (mt instanceof RelayClient) { - RelayClient er = (RelayClient) mt; - - RelayClient.RelayServerConnection current = er.currentServer; - - if (null == current) { - continue; - } - - RouteAdvertisement rdvAdv = current.relayAdv; - - if (null == rdvAdv) { - continue; - } - - result.add(rdvAdv.clone()); - } - } - } catch (Exception ez1) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Unexpected error getting relays", ez1); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Found " + result.size() + " relay seeds."); - } - return result; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayServer.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayServer.java deleted file mode 100644 index c62b150c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayServer.java +++ /dev/null @@ -1,1498 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.relay; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Random; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.MessageSender; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.MessengerEvent; -import net.jxta.endpoint.MessengerEventListener; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.access.AccessList; -import net.jxta.impl.protocol.RelayConfigAdv; -import net.jxta.impl.util.TimeUtils; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; -import net.jxta.impl.endpoint.EndpointUtils; - -/** - * Relay server that maintains outgoing message queues, leases, etc. - */ -public class RelayServer implements MessageSender, MessengerEventListener, Runnable { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(RelayServer.class.getName()); - - private final static int MAX_CACHED_SERVERS = 20; - - /** - * The EndpointService for the RelayService - */ - private EndpointService endpointService; - - /** - * The DiscoveryService for the RelayService - */ - private DiscoveryService discoveryService; - - /** - * The public address is of the form relay://peerId - */ - private final EndpointAddress publicAddress; - - /** - * Map of the current clients - */ - private final Map relayedClients = new HashMap(); - - protected final PeerGroup group; - protected final String serviceName; - private final int maxClients; - private final long maxLeaseDuration; - private final long stallTimeout; - private final int clientQueueSize; - private final long minBroadcastInterval; - - protected final String peerId; - - protected final AccessList acl; - protected File aclFile; - protected long refreshTime = 0; - - protected long aclFileLastModified = 0; - private static final long ACL_REFRESH_PERIOD = 30 * TimeUtils.AMINUTE; - - protected RelayServerCache relayServerCache; - - private Thread gcThread = null; - - private MessengerEventListener messengerEventListener = null; - - /** - * constructor - */ - public RelayServer(PeerGroup group, String serviceName, RelayConfigAdv relayConfigAdv) { - - this.group = group; - peerId = group.getPeerID().getUniqueValue().toString(); - publicAddress = new EndpointAddress(RelayTransport.protocolName, peerId, null, null); - - this.serviceName = serviceName; - - this.maxClients = (-1 != relayConfigAdv.getMaxClients()) - ? relayConfigAdv.getMaxClients() - : RelayTransport.DEFAULT_MAX_CLIENTS; - this.clientQueueSize = (-1 != relayConfigAdv.getClientMessageQueueSize()) - ? relayConfigAdv.getClientMessageQueueSize() - : RelayTransport.DEFAULT_CLIENT_QUEUE_SIZE; - this.maxLeaseDuration = (-1 != relayConfigAdv.getServerLeaseDuration()) - ? relayConfigAdv.getServerLeaseDuration() - : RelayTransport.DEFAULT_LEASE; - this.minBroadcastInterval = (-1 != relayConfigAdv.getAnnounceInterval()) - ? relayConfigAdv.getAnnounceInterval() - : RelayTransport.DEFAULT_BROADCAST_INTERVAL; - this.stallTimeout = (-1 != relayConfigAdv.getStallTimeout()) - ? relayConfigAdv.getStallTimeout() - : RelayTransport.DEFAULT_STALL_TIMEOUT; - - aclFile = new File(new File(group.getStoreHome()), "relayACL.xml"); - aclFileLastModified = aclFile.lastModified(); - this.acl = new AccessList(); - try { - acl.init(aclFile); - this.refreshTime = System.currentTimeMillis() + ACL_REFRESH_PERIOD; - } catch (IOException io) { - acl.setGrantAll(true); - this.refreshTime = Long.MAX_VALUE; - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("RelayServer Access Control granting all permissions"); - } - } - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Relay Server"); - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tService Name : ").append(serviceName); - configInfo.append("\n\t\tMax Relay Clients : ").append(maxClients); - configInfo.append("\n\t\tMax Lease Length : ").append(maxLeaseDuration).append("ms."); - configInfo.append("\n\t\tBroadcast Interval : ").append(minBroadcastInterval).append("ms."); - configInfo.append("\n\t\tStall Timeout : ").append(stallTimeout).append("ms."); - - LOG.config(configInfo.toString()); - } - } - - /** - * Debug routine: returns the list of relayedClients with details. - */ - public List getRelayedClients() { - List res = new ArrayList(); - - for (Object o : Arrays.asList(relayedClients.values().toArray())) { - String client = o.toString(); - - res.add(client); - } - - return res; - } - - public boolean startServer() { - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Starting " + publicAddress.toString()); - } - - endpointService = group.getEndpointService(); - discoveryService = group.getDiscoveryService(); - - if ((messengerEventListener = endpointService.addMessageTransport(this)) == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Transport registration refused"); - } - return false; - } - - try { - discoveryService.publish(createRdvAdvertisement(group.getPeerAdvertisement(), serviceName)); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not publish Relay RdvAdvertisement", e); - } - } - - relayServerCache = new RelayServerCache(this); - - // start cache relay servers - relayServerCache.startCache(); - - endpointService.addMessengerEventListener(this, EndpointService.HighPrecedence); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Relay Server started"); - } - return true; - } - - public void stopServer() { - // stop cache relay servers - relayServerCache.stopCache(); - relayServerCache = null; - - // remove messenger events listener since we do not have any clients - endpointService.removeMessengerEventListener(this, EndpointService.HighPrecedence); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Messenger Event Listener removed " + serviceName); - } - - // Close all clients. - // Get a list of the clients but leave them in the map; - // they remove themselves by calling removeClient(this). - // That's why we do not iterate through the real map to close them. - - RelayServerClient[] oldClients; - - synchronized (relayedClients) { - oldClients = relayedClients.values().toArray(new RelayServerClient[0]); - } - - int i = oldClients.length; - - while (i-- > 0) { - oldClients[i].closeClient(); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Stopped " + publicAddress); - } - } - - /* - * Methods inherited from MessageSender - */ - - /** - * {@inheritDoc} - */ - public EndpointAddress getPublicAddress() { - return publicAddress; - } - - /** - * {@inheritDoc} - */ - public boolean isConnectionOriented() { - return true; - } - - /** - * {@inheritDoc} - */ - public boolean allowsRouting() { - return true; - } - - /** - * {@inheritDoc} - */ - public Object transportControl(Object operation, Object Value) { - return null; - } - - /** - * {@inheritDoc} - */ - public Messenger getMessenger(EndpointAddress destAddr, Object hintIgnored) { - Messenger messenger = null; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("getMessenger for dest " + destAddr); - } - - if (!RelayTransport.protocolName.equals(destAddr.getProtocolName())) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("could not make messenger for protocol :" + destAddr.getProtocolName()); - } - - return null; - } - - // check if we have a queue for this client - RelayServerClient handler = getClient(destAddr.getProtocolAddress()); - - if (handler != null) { - messenger = handler.getMessenger(publicAddress, destAddr, false); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("messenger for " + destAddr.getProtocolAddress() + " is " + messenger); - } - - return messenger; - } - - /** - * {@inheritDoc} - */ - @Deprecated - public boolean ping(EndpointAddress addr) { - - synchronized (relayedClients) { - return (null != relayedClients.get(addr.getProtocolAddress())); - } - } - - /* - * Methods inherited from MessageTransport - */ - - /** - * {@inheritDoc} - */ - public String getProtocolName() { - return RelayTransport.protocolName; - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - return endpointService; - } - - /** - * {@inheritDoc} - */ - public boolean messengerReady(MessengerEvent event) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("messengerReady"); - } - - Messenger newMessenger = event.getMessenger(); - Object source = event.getSource(); - EndpointAddress connectionAddress = event.getConnectionAddress(); - - // Sanity check, this should not happen - if (newMessenger == null || source == null || connectionAddress == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("there was not a messenger or not enough information"); - } - - return false; - } - - // We do not grab just any messenger; that would replace the - // existing one and then we could have a fight between the - // front channel and the back channel from the same peer. - // We only grab back-channel messengers that where explicitly - // directed to the relay. - if (!serviceName.equals(connectionAddress.getServiceName())) { - return false; - } - - // make sure that it is not a higher level messenger - if (source instanceof MessageSender && !((MessageSender) source).allowsRouting()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("this is a higher level messenger"); - } - - return false; - } - - // make sure that this is not one of our own. - if (source == this || newMessenger instanceof RelayServerClient.RelayMessenger) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("this is a relay messenger"); - } - - return false; - } - - // make sure that the messenger matches a possible client address - EndpointAddress destAddr = newMessenger.getLogicalDestinationAddress(); - - if (destAddr == null || !"jxta".equals(destAddr.getProtocolName())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("LogicalDestinationAddress is not a \"jxta\" protocol"); - } - - return false; - } - - // check if we have a queue for this client - // In that case, we just give it the handler and be done. - // We must not process the lease request that comes with a messenger - // for an existing client. If we did, we would reply with a lease - // response. Some connections can carry only one message and then - // close. In that case, the client has to re-establish the connection - // every time we respond. So, if we repond to all incoming connections - // we're going nowhere. In some cases, the client realy wants a - // response because it believes it is an initial connection while - // we still have it from a previous session. In that case, the client - // must try to send an explicit lease renewal message. (To which - // we do respond). - - String clientPeerId = destAddr.getProtocolAddress(); - RelayServerClient handler = getClient(clientPeerId); - - if (handler != null) { - return handler.addMessenger(newMessenger); - } - - // Non-existent client. We want to process the - // connection request and respond. - // handleRequest may do whatever, but we always keep the - // messenger. It was meant for us anyway. - handleRequest(newMessenger, connectionAddress); - return true; - } - - protected void handleRequest(Messenger messenger, EndpointAddress connectionAddress) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("handleRequest from messenger"); - } - - // In this case, the request comes within the messenger's destination. - String request = connectionAddress.getServiceParameter(); - - // make sure that the messenger shows a client logical address - EndpointAddress clientAddr = messenger.getLogicalDestinationAddress(); - - if (clientAddr == null || !"jxta".equals(clientAddr.getProtocolName())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("LogicalDestinationAddress is not a \"jxta\" protocol"); - } - - return; - } - - String clientPeerId = clientAddr.getProtocolAddress(); - - handleRequest(request, clientPeerId, messenger); - } - - protected void handleRequest(Message message, EndpointAddress dstAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("handleRequest from message"); - } - - String request = RelayTransport.getString(message, RelayTransport.REQUEST_ELEMENT); - String clientPeerId = dstAddr.getServiceParameter(); - - handleRequest(request, clientPeerId, null); - } - - void handleRequest(String request, String clientPeerId, Messenger messenger) { - // This request may come along with a messenger (if it is a renewal - // post-disconnection or an initial lease request). - - if (request == null) { - return; - } - - request = request.toLowerCase(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("request = " + request); - } - - // only process the request if a client peer id was sent - if (clientPeerId == null) { - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("clientPeerId = " + clientPeerId); - } - - // The only valid anonymous request is a request to obtain a real pid. - if ((clientPeerId.equals("unknown-unknown")) && (!request.startsWith(RelayTransport.PID_REQUEST))) { - return; - } - - Message responseMessage = null; - - RelayServerClient closingHandler = null; - boolean rawMessenger = false; - boolean closeMessenger = false; - - // Figure out which request it is - if (request.startsWith(RelayTransport.CONNECT_REQUEST)) { - // Connect Request - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("connect clientPeerId = " + clientPeerId); - } - - long requestedLease = maxLeaseDuration; - boolean returnRelayAdv = false; - boolean returnOtherRelayAdv = false; - boolean flushQueue = false; - - String requestedLeaseString = null; - - // check if a lease value was specified - int startIdx = request.indexOf(','); - - if (startIdx != -1) { - // find the end of the lease value - int endIdx = request.indexOf(',', startIdx + 1); - - if (endIdx == -1) { - requestedLeaseString = request.substring(startIdx + 1); - } else { - requestedLeaseString = request.substring(startIdx + 1, endIdx); - String flags = request.substring(endIdx + 1); - - if (flags.endsWith("true")) { - returnRelayAdv = true; - } else if (flags.endsWith("other")) { - // This is an addition to the protocol. Newer - // clients will always set that in connection requests - // when not setting true. Only older clients use to - // set nothing at all. - returnOtherRelayAdv = true; - } - // Only two flag positions for now - // The inserted first position is another extention. - // Only newer clients use it. Older servers will not - // notice it because they only check how the request ends. - // So, new clients are also compatible with old servers. - if (flags.startsWith("flush")) { - flushQueue = true; - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "request lease string = " + requestedLeaseString + "\treturn relay adv = " + returnRelayAdv - + "\n\treturn other relay adv = " + returnOtherRelayAdv + "\tflush queue = " + flushQueue); - } - - if (requestedLeaseString != null) { - try { - requestedLease = Long.parseLong(requestedLeaseString); - } catch (NumberFormatException e) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("could not parse requested lease string"); - } - } - - if (requestedLease > maxLeaseDuration) { - requestedLease = maxLeaseDuration; - } - } - - // process the connect request - EndpointAddress clientAddr = new EndpointAddress("jxta", clientPeerId, serviceName, peerId); - - // If we have a messenger, the clientHandler gets it. - // If the client handler did not already exist, it will be - // created only if we pass a messenger. We can no-longer create - // new clients without an incoming messenger. We used to get one - // from the router but no-longer. Now initial lease requests must - // come as part of the messenger creation. - - RelayServerClient handler = addClient(clientPeerId, requestedLease, messenger, flushQueue); - - if (handler != null) { - - // the client was added, send a connected response - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("added client " + clientPeerId); - } - - // Now get a messenger that goes through the handler and - // sends messages out-of-band (and internal perk). - // jice@jxta.org - 20021227 all this code is getting ridiculous - // it has to be re-organized. Addind the outOfBand feature - // to all RelayMessengers just for that is overkill. This - // just a temporary patch. The real fix would be to respond - // straight with the messenger we have. Unfortunately, sometimes - // we have to respond without a messenger in our hands because - // sending a message over an explicit connection is the only - // way for existing clients to ask for a response when they - // reconnect. We would need to change the protocol and add an - // "initial connection" request type to fix that. - - messenger = handler.getMessenger(publicAddress, clientAddr, true); - responseMessage = RelayTransport.createConnectedMessage(handler.getLeaseRemaining()); - // For protocol compatibility reasons, returnRelayAdv realy - // means "return your own because I do not know it". - // If returnOtherRelayAdv is true, then, we will return one - // selected among those we know, for the enlightenment of the - // other party. - // If neither is true, we'll return no adv at all in order not - // to confuse existing clients. - - RdvAdvertisement relayAdv = null; - - if (returnRelayAdv) { - relayAdv = createRdvAdvertisement(group.getPeerAdvertisement(), serviceName); - } else if (returnOtherRelayAdv) { - relayAdv = relayServerCache.getRandomCacheAdv(); - } - if (relayAdv != null) { - XMLDocument asDoc = (XMLDocument) relayAdv.getDocument(MimeMediaType.XMLUTF8); - - MessageElement relayAdvElement = new TextDocumentMessageElement(RelayTransport.RELAY_ADV_ELEMENT, asDoc, null); - - responseMessage.addMessageElement(RelayTransport.RELAY_NS, relayAdvElement); - } - } else { - // We can't keep the messenger. - // the client was not added, send a disconnected response - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("could not add client " + clientPeerId); - } - - // We do not get a messenger for ourselves here, so - // just get one from the router ourselves, if we have to. - // and can. - if (messenger == null) { - // If we did not get one and manage to obtain one - // from the endpoint, we can use it in-line, but - // we must close it. (The only case). - messenger = endpointService.getMessenger(clientAddr); - if (messenger != null) { - closeMessenger = true; - } - - } else { - - // This is the incoming messenger. We cannot use it - // synchronously. See, the use of BGSend, below. - - rawMessenger = true; - } - - responseMessage = RelayTransport.createDisconnectedMessage(); - - // add the relay advertisement of another know relay for the client to try - RdvAdvertisement relayAdv = relayServerCache.getRandomCacheAdv(); - - if (relayAdv != null) { - XMLDocument asDoc = (XMLDocument) relayAdv.getDocument(MimeMediaType.XMLUTF8); - - MessageElement relayAdvElement = new TextDocumentMessageElement(RelayTransport.RELAY_ADV_ELEMENT, asDoc, null); - - responseMessage.addMessageElement(RelayTransport.RELAY_NS, relayAdvElement); - } - } - } else if (RelayTransport.DISCONNECT_REQUEST.equals(request)) { - // Disconnect Request, don't send a response - if (clientPeerId != null) { - closingHandler = removeClient(clientPeerId); - if (closingHandler != null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removed client " + clientPeerId); - } - } - } - } else if (RelayTransport.PID_REQUEST.equals(request)) { - - // Generate a PeerID in the same group as our PeerID. - // The group which my peerID stems from is not necessarily - // the group where I am running (more likely it is the net peer - // group). Rather than guessing, get the group from our own PID. - - PeerGroupID groupOfMyPid = (PeerGroupID) group.getPeerID().getPeerGroupID(); - - String pidStr = IDFactory.newPeerID(groupOfMyPid).toString(); - - responseMessage = RelayTransport.createPIDResponseMessage(pidStr); - - // If there is a raw incoming messenger, that's what we - // use. Else, we won't respond. - rawMessenger = true; - } - - // if there is a messenger and a response, send it - if (messenger != null && responseMessage != null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("sending response to client " + clientPeerId); - } - - // If rawMessenger, then this is the incoming - // messenger brought in by messengerReady. In that case, - // be carefull. It is synchronous and it could block this - // here thread until the message can be sent. Which could - // possibly imply that this here method returns...dead lock. - // See HttpMessageServlet: messengerReady is called by - // the same thread that subsequently picks up messages from - // the BCMessenger. So, spawn a thread to reply. - // FIXME: eventualy we should start replacing some listener - // based code with state machines and event queues. - - if (rawMessenger) { - - // BGSend will *not* close the messenger after use - // Because incoming messengers do not need to be closed. - new BGSend(messenger, responseMessage, serviceName, peerId); - } else { - try { - messenger.sendMessage(responseMessage, serviceName, peerId); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not send response message to " + clientPeerId, e); - } - } - } - } - - if (closeMessenger) { - messenger.close(); - } - - if (closingHandler != null) { - closingHandler.closeClient(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("relayedClients.size()=" + relayedClients.size()); - } - } - - private RelayServerClient getClient(String clientPeerId) { - RelayServerClient handler; - - synchronized (relayedClients) { - handler = relayedClients.get(clientPeerId); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("getClient(" + clientPeerId + ") = " + handler); - } - - return handler; - } - - // Add client is idempotent. It can be called for a client that already - // exists. The flushqueue option instructs to clear the queue if the client - // exists. - private RelayServerClient addClient(String clientPeerId, long requestedLease, Messenger messenger, boolean flushQueue) { - RelayServerClient handler; - boolean isNewClient = false; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("addClient(" + clientPeerId + ")"); - } - - synchronized (relayedClients) { - // check if this client is already registered - handler = relayedClients.get(clientPeerId); - if (handler == null) { - // make sure the maximum number of clients has not been reached - // and make sure that we have a messenger to give to the new - // clientHandler. - if ((relayedClients.size() < maxClients) && (messenger != null) && !messenger.isClosed()) { - - // create a new handler - handler = new RelayServerClient(this, clientPeerId, requestedLease, stallTimeout, clientQueueSize); - - // add the handler to the list - relayedClients.put(clientPeerId, handler); - isNewClient = true; - - // check if this is the first client added - if (relayedClients.size() == 1) { - // start the gcThread if it is not already started - if (gcThread == null) { - gcThread = new Thread(group.getHomeThreadGroup(), this, "GC Thread for Relay at " + publicAddress); - gcThread.setDaemon(true); - gcThread.start(); - } - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "new client denied. nb clients: " + relayedClients.size() + "/" + maxClients + ", messenger: " - + messenger); - } - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("added = " + (handler != null)); - } - - if (handler == null) { - return null; - } - - // renew the lease on the old handler - // Watchout. The handler might have expired since we got it from the - // map. RenewLease will tell us. In that case, tough luck. We don't - // make a new one. FIXME: it's not nice to the client, but in no way - // a disaster (and very rare). - - if (!handler.renewLease()) { - return null; - } - - if (flushQueue) { - handler.flushQueue(); - } - - if (messenger != null) { - handler.addMessenger(messenger); - - // We must force the router to learn the new relay connection as - // a direct route, so that it replies to route queries even if we - // never start talking to the client otherwise. - // Here we do something rather acrobatic. We invoke messengerReady - // recursively with a new relay messenger that the router will - // catch as if it where an incoming messenger (which it is, sort - // of). The cleaner alternative: call getMessenger with a hint - // causes too much commotion: sometimes an unreachable tcp address - // is tried before the hint, which blocks getMessenger for long. - - if (isNewClient) { - EndpointAddress ear = new EndpointAddress(RelayTransport.protocolName, clientPeerId, null, null); - - MessengerEvent me = new MessengerEvent(this, handler.getMessenger(publicAddress, ear, false), null); - - messengerEventListener.messengerReady(me); - } - } - - return handler; - } - - private RelayServerClient removeClient(String clientPeerId) { - RelayServerClient handler; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removeClient(" + clientPeerId + ")"); - } - - synchronized (relayedClients) { - handler = relayedClients.remove(clientPeerId); - - // check if there are any clients - if (relayedClients.size() == 0) { - // stop the gcThread - if (gcThread != null) { - try { - gcThread.interrupt(); - } catch (SecurityException e) { - // ignore this exception - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(e.toString()); - } - } - } - } - } - - return handler; - } - - // this is only used by the RelayServerClient when it is closing and needs to remove itself - protected void removeClient(String clientPeerId, RelayServerClient handler) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removeClient(" + clientPeerId + "," + handler + ")"); - } - - synchronized (relayedClients) { - RelayServerClient currentHandler = relayedClients.get(clientPeerId); - - // only remove the client if the current handler matches the passed one - if (currentHandler == handler) { - relayedClients.remove(clientPeerId); - } - - // check if there are any clients - if (relayedClients.size() == 0) { - // stop the gcThread - Thread temp = gcThread; - - if (temp != null) { - try { - temp.interrupt(); - } catch (SecurityException e) { - // ignore this exception - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(e.toString()); - } - } - } - } - } - } - - /** - * {@inheritDoc} - */ - public void run() { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Starting lease gc thread"); - } - - try { - while (true) { - // check if there are any client handlers left - synchronized (relayedClients) { - if (relayedClients.size() == 0) { - break; - } - } - - // do the lease gc - doClientGC(); - - // check if there are any client handlers left - synchronized (relayedClients) { - if (relayedClients.size() == 0) { - break; - } - } - - // sleep for a while. - try { - Thread.sleep(stallTimeout); - } catch (InterruptedException e) { - Thread.interrupted(); - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - gcThread = null; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("stopping lease gc thread"); - } - } - } - - // checks for expired client handlers - private void doClientGC() { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("start: check for expired client handler. # clients = " + relayedClients.size()); - } - - // get a snapshot of the client handlers - RelayServerClient[] handlers; - - synchronized (relayedClients) { - handlers = relayedClients.values().toArray(new RelayServerClient[0]); - } - - // run through the client handlers - int i = handlers.length; - - while (i-- > 0) { - try { - // simply calling isExpired will cause the handler to check - // if it is expired and remove itself if expired - handlers[i].isExpired(); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception during client gc", e); - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("stop: check for expired client handler. # clients = " + relayedClients.size()); - } - } - - private static class RelayServerCache implements PipeMsgListener, Runnable { - final static ID pipeID = ID.create( - URI.create("urn:jxta:uuid-59616261646162614E50472050325033DEADBEEFDEAFBABAFEEDBABE0000000F04")); - - final RelayServer server; - final PipeAdvertisement pipeAdv; - InputPipe inputPipe = null; - - volatile boolean doRun = false; - Thread cacheThread = null; - - final Map relayAdvCache = new HashMap(); - - final Random rand = new Random(); - - protected RelayServerCache(RelayServer server) { - this.server = server; - - pipeAdv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType()); - pipeAdv.setPipeID(pipeID); - pipeAdv.setType(PipeService.PropagateType); - } - - private int relayAdvCacheSize() { - synchronized (relayAdvCache) { - return relayAdvCache.size(); - } - } - - protected RdvAdvertisement getRandomCacheAdv() { - synchronized (relayAdvCache) { - RdvAdvertisement[] items = relayAdvCache.values().toArray(new RdvAdvertisement[0]); - - if (items.length == 0) { - return null; - } - - return items[rand.nextInt(items.length)]; - } - } - - private boolean putCacheAdv(String peerId, RdvAdvertisement adv) { - if (!server.acl.isAllowed(adv.getPeerID())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Rejected cache entry for : " + peerId); - } - return false; - } - synchronized (relayAdvCache) { - boolean replaced = (null != relayAdvCache.put(peerId, adv)); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine((replaced ? "Updated" : "Created") + " cache entry for : " + peerId); - } - - if (relayAdvCache.size() >= MAX_CACHED_SERVERS) { - // New entry and map full. Remove one at random. - String[] keys = relayAdvCache.keySet().toArray(new String[0]); - - relayAdvCache.remove(keys[rand.nextInt(keys.length)]); - } - - return replaced; - } - } - - /** - * {@inheritDoc} - */ - public void pipeMsgEvent(PipeMsgEvent event) { - Message message = event.getMessage(); - - if (message == null) { - return; - } - - boolean isResponse = (RelayTransport.getString(message, RelayTransport.RESPONSE_ELEMENT) != null); - String peerId = RelayTransport.getString(message, RelayTransport.PEERID_ELEMENT); - - if (peerId == null || peerId.equals(server.peerId)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("pipeMsgEvent() discarding message no response PID defined, or loopback "); - } - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("pipeMsgEvent() from " + peerId); - } - - MessageElement me = message.getMessageElement(RelayTransport.RELAY_NS, RelayTransport.RELAY_ADV_ELEMENT); - - if (null == me) { - return; - } - - Advertisement adv; - try { - // XXX bondolo 20041207 Force parsing of MessageElement as - // XMLUTF8 rather than the actual mime type associated with the - // MessageElement since the advertisement is often incorrectly - // stored as a String by older JXTA implementations. - adv = AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8, me.getStream()); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building relay advertisement", failed); - } - return; - } catch (NoSuchElementException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not build relay advertisement", failed); - } - return; - } - - if (!(adv instanceof RdvAdvertisement)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Response does not contain relay advertisement (" + adv.getAdvType() + ")"); - } - return; - } - - RdvAdvertisement radv = (RdvAdvertisement) adv; - - if (putCacheAdv(peerId, radv)) { - - // New entry, we might want to respond. - // "someone" should respond; on average, one response - // is all we want. And that response obviously should be - // unicast. - // We achieve an approximation of that by making a computation - // that will result in "true" on average on only one peer - // of the set, based on our idea of what the set is. - // If we know very few other relays compared to what other - // relays know, we are more likely to respond than they are. - // So this is very approximate. We want to keep it simple - // until we have time replace this lazy junk with something - // sensible. - - // If it's a response already, the story stops here ! - if (isResponse) { - return; - } - - // Here we go: - int i = relayAdvCacheSize(); - long magic = server.peerId.hashCode() % i; - - if (rand.nextInt(i) == magic) { - - // Our number came out. Respond. - - // See if we have amunition to respond anyway. - // Very defensive. I care a lot more not to break anything - // at this stage, than to have optimal functionality. - - RdvAdvertisement myAdv = RelayServer.createRdvAdvertisement(server.group.getPeerAdvertisement(), server.serviceName); - - // Need to convert the other party's string pid into - // a real pid. - PeerID otherPid = null; - try { - otherPid = (PeerID) IDFactory.fromURI(new URI(ID.URIEncodingName, ID.URNNamespace + ":" + peerId, null)); - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Bad peerid : " + peerId, ex); - } - - } - - PipeService pipeService = server.group.getPipeService(); - if (pipeService == null) { - return; // Funny. We're receiving messages, after all. - } - - // FIXME: jice@jxta.org 20030131 - We're making a rather - // unorthodox use of the peer-subset feature of propagate - // pipes. Basically what this does is to send the message - // in unicast so that it is received on the propagate - // input pipe of the specified peer. - // The correct API, if it existed, would be respond(). - - OutputPipe retPipe = null; - try { - retPipe = pipeService.createOutputPipe(pipeAdv, Collections.singleton(otherPid), 2 * TimeUtils.ASECOND); - if (retPipe == null) { - return; - } - - // create a new cache message - message = new Message(); - - // String version of unique portion only. Per the protocol. - RelayTransport.setString(message, RelayTransport.PEERID_ELEMENT, server.peerId); - // Our own adv. - RelayTransport.setString(message, RelayTransport.RELAY_ADV_ELEMENT, myAdv.toString()); - - // This is a response. New servers: do not respond! Old - // servers won't respond anyway. - RelayTransport.setString(message, RelayTransport.RESPONSE_ELEMENT, "t"); - - retPipe.send(message); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Responded"); - } - - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Could not send reply on pipe ", e); - } - } - - if (retPipe != null) { - retPipe.close(); - } - } - } - } - - /** - * {@inheritDoc} - */ - public void run() { - try { - OutputPipe outputPipe = null; - PipeService pipeService = server.group.getPipeService(); - - while (doRun && inputPipe == null) { - try { - inputPipe = pipeService.createInputPipe(pipeAdv, this); - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Could not create input pipe, try again"); - } - } catch (IllegalStateException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Pipe Service not ready yet, try again"); - } - } - - try { - Thread.sleep(TimeUtils.ASECOND); - } catch (InterruptedException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("wait interrupted"); - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Created input pipe"); - } - - while (doRun && outputPipe == null) { - try { - outputPipe = pipeService.createOutputPipe(pipeAdv, 5 * TimeUtils.ASECOND); - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Could not create output pipe, try again"); - } - } catch (IllegalStateException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Pipe Service not ready yet, try again"); - } - } - - try { - Thread.sleep(TimeUtils.ASECOND); - } catch (InterruptedException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("wait interrupted "); - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Created output pipe"); - } - - // Wait a little before mcasting our hello. - // We depend on the rendezvous infrastructure for it to - // work. It's pretty important to get the first one out - // so that we may get a response from others. After that - // the interval is very long (and its computation an total - // nonsense) and so others do not talk much - // either. We want to learn at least one other relay early on. - // FIXME: jice@jxta.org 20030131 - We realy need to switch to - // using peerview. It does all of that correctly. - - try { - Thread.sleep(10 * TimeUtils.ASECOND); - } catch (InterruptedException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("wait interrupted"); - } - } - - while (doRun) { - RdvAdvertisement adv = RelayServer.createRdvAdvertisement(server.group.getPeerAdvertisement(), server.serviceName); - - // Make sure that the version that can be discovered - // is consistent. - try { - server.discoveryService.publish(adv); - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Could not publish Relay RdvAdvertisement", e); - } - } - - if (adv != null) { - // create a new cache message - Message message = new Message(); - - RelayTransport.setString(message, RelayTransport.PEERID_ELEMENT, server.peerId); - RelayTransport.setString(message, RelayTransport.RELAY_ADV_ELEMENT, adv.toString()); - - try { - outputPipe.send(message); - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Could not send message on pipe ", e); - } - } - } - - long sleepTime = server.minBroadcastInterval - + ((server.relayedClients.size() + 1) * 100 / (server.maxClients + 1)) * server.minBroadcastInterval; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("sleepTime=" + sleepTime); - } - - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - Thread.interrupted(); - } - } - outputPipe.close(); - if (System.currentTimeMillis() > server.refreshTime) { - server.refreshTime = System.currentTimeMillis() + ACL_REFRESH_PERIOD; - if (server.aclFile.lastModified() > server.aclFileLastModified) { - server.aclFileLastModified = server.aclFile.lastModified(); - server.acl.refresh(server.aclFile); - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - cacheThread = null; - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Cache thread quitting."); - } - } - } - - protected void startCache() { - doRun = true; - cacheThread = new Thread(server.group.getHomeThreadGroup(), this, "RelayCache Worker Thread for " + server.publicAddress); - cacheThread.setDaemon(true); - cacheThread.start(); - } - - protected void stopCache() { - doRun = false; - - if (inputPipe != null) { - inputPipe.close(); - inputPipe = null; - } - cacheThread.interrupt(); - } - } - - - /** - * Sends a message on an synchronous messenger. - */ - static class BGSend extends Thread { - - Messenger mr; - Message ms; - String sn; - String ps; - - BGSend(Messenger mr, Message ms, String sn, String ps) { - super("Relay Background Sender"); - this.mr = mr; - this.ms = ms; - this.sn = sn; - this.ps = ps; - setDaemon(true); - start(); - } - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - mr.sendMessage(ms, sn, ps); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed sending response " + ms + " to " + ps, e); - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } - - } - } - - private static RdvAdvertisement createRdvAdvertisement(PeerAdvertisement padv, String name) { - try { - // FIX ME: 10/19/2002 lomax@jxta.org. We need to properly set up the service ID. Unfortunately - // this current implementation of the PeerView takes a String as a service name and not its ID. - // Since currently, there is only PeerView per group (all peerviews share the same "service", this - // is not a problem, but that will have to be fixed eventually. - - // create a new RdvAdvertisement - RdvAdvertisement rdv = (RdvAdvertisement) AdvertisementFactory.newAdvertisement( - RdvAdvertisement.getAdvertisementType()); - - rdv.setPeerID(padv.getPeerID()); - rdv.setGroupID(padv.getPeerGroupID()); - rdv.setServiceName(name); - rdv.setName(padv.getName()); - - RouteAdvertisement ra = EndpointUtils.extractRouteAdv(padv); - - if (null == ra) { - // No route available - return null; - } - - // Insert it into the RdvAdvertisement. - rdv.setRouteAdv(ra); - - return rdv; - } catch (Exception ez) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Cannot create Local RdvAdvertisement: ", ez); - } - return null; - } - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayServerClient.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayServerClient.java deleted file mode 100644 index a89eee42..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayServerClient.java +++ /dev/null @@ -1,669 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.relay; - -import java.io.IOException; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.logging.Logger; -import java.util.logging.Level; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.logging.Logging; - -import net.jxta.impl.endpoint.BlockingMessenger; -import net.jxta.impl.endpoint.EndpointServiceImpl; -import net.jxta.impl.util.TimeUtils; - -/** - * This class abstracts a client of the Relay Server - */ -class RelayServerClient implements Runnable { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(RelayServerClient.class.getName()); - - /** - * The lease length when there are messages pending and we can't send them. - */ - private static long stallTimeout = 0; - - /** - * the Relay Server of this client - */ - private final RelayServer server; - - /** - * the peerId of this client - */ - private final String clientPeerId; - - /** - * The length of the lease in milliseconds - */ - private long leaseLength = 0; - - /** - * the Endpoint Address of the client of the queue expressed as jxta://'peerid' - */ - private final EndpointAddress clientAddr; - - /** - * the time at which the message queue expires - */ - private volatile long expireTime = 0; - - /** - * indicates whether this client handler is valid or expired - */ - private boolean isClosed = false; - - /** - * a queue of message for this client - */ - private final BlockingQueue messageList; - - /** - * endpoint service for this client - */ - private final EndpointService endpoint; - - private Messenger messenger = null; - private Thread thread = null; - private boolean thread_idle = false; - - private Message outOfBandMessage = null; - - protected RelayServerClient(RelayServer server, String clientPeerId, long leaseLength, long stallTimeout, int clientQueueSize) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("new Client peerId=" + clientPeerId + " lease=" + leaseLength); - } - - this.server = server; - this.clientPeerId = clientPeerId; - this.leaseLength = leaseLength; - RelayServerClient.stallTimeout = stallTimeout; - - clientAddr = new EndpointAddress("jxta", clientPeerId, null, null); - endpoint = server.getEndpointService(); - messageList = new ArrayBlockingQueue(clientQueueSize); - - // initialize the lease - renewLease(); - } - - /** - * {@inheritDoc} - */ - @Override - protected void finalize() throws Throwable { - closeClient(); - super.finalize(); - } - - /** - * {@inheritDoc} - * - *

          Send all of the queued messages to the client. - */ - public void run() { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("send queued messages to " + clientAddr); - } - - try { - Message message; - int failedInARow = 0; - - while (true) { - message = null; - Messenger holdIt; - synchronized (this) { - // Messenger + message is the condition to continue running - // We do not want to dequeue messages for sending before knowing if - // we have a messenger because re-queing is clumsy, so we - // check the messenger first. However, if we fail to get - // a messenger, we are forced to check the queue so that we - // can update the lease accordingly. It is possible to be here - // with neither messenger nor messages and then we must let - // the lease be long. - - if (messenger == null || messenger.isClosed()) { - messenger = null; - if (outOfBandMessage != null || !messageList.isEmpty()) { - - // If we cannot send a message by lack of messenger. - // The client is suspect of being dead. The clock starts - // ticking faster until we manage to send again. - // In two minutes we declare it dead. - - long newExpireTime = TimeUtils.toAbsoluteTimeMillis(stallTimeout); - - // If we're closed, we won't touch expireTime since it is 0. - if (expireTime > newExpireTime) { - expireTime = newExpireTime; - } - - } - thread = null; // Make sure a thread will be created if - break; // it is needed after we release the synch. - } - - if (outOfBandMessage != null) { - message = outOfBandMessage; - outOfBandMessage = null; - } else { - message = messageList.poll(0, TimeUnit.MILLISECONDS); - if (message == null) { - try { - thread_idle = true; - wait(4 * TimeUtils.ASECOND); - if (outOfBandMessage != null) { - message = outOfBandMessage; - outOfBandMessage = null; - } else { - message = messageList.poll(0, TimeUnit.MILLISECONDS); - } - } catch (InterruptedException ie) { - //ignored - } - if (message == null) { - thread = null; // Make sure a thread will be created if - break; // it is needed after we release the synch. - } - } - } - - holdIt = messenger; // Avoid NPE once out of synch. - thread_idle = false; - } - - // get the final service name and parameter that was loaded before queueing - MessageElement dstAddressElement = message.getMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NS, - EndpointServiceImpl.MESSAGE_DESTINATION_NAME); - - if (null == dstAddressElement) { - // No destination address... Just discard - // this should really not happen - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("message destination was not set"); - } - - continue; - } - EndpointAddress destAddr = new EndpointAddress(dstAddressElement.toString()); - - // send the message - try { - holdIt.sendMessageB(message, destAddr.getServiceName(), destAddr.getServiceParameter()); - - // The client is off the hook for now. One message was sent. - // Lease will stay long until the next messenger failure. - synchronized (this) { - failedInARow = 0; - - // Do not touch expireTime if we've been closed. - if (!isClosed) { - expireTime = TimeUtils.toAbsoluteTimeMillis(leaseLength); - } - } - } catch (Exception e) { - // Check that the exception is not due to the message - // rather than the messenger, and then drop the message. In that case - // we give the messenger the benefit of the doubt and keep - // it open, renewing the lease as above. (this could be the last - // message). For now the transports do not tell the difference, so we - // count the nb of times we failed in a row. After three times, - // kill the message rather than the messenger. - - // put the message back - synchronized (this) { - if (++failedInARow >= 3) { - failedInARow = 0; - if (!isClosed) { - expireTime = TimeUtils.toAbsoluteTimeMillis(leaseLength); - } - continue; - } - - // Ok, if we cannot push back the message, below, we - // should reset failedInARow, since we won't be retrying - // the same message. But it does not realy matter so - // let's keep things simple. - - if (outOfBandMessage == null) { - outOfBandMessage = message; - } - } - - // If we're here, we decided to close the messenger. We do that - // out of sync. - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "closing messenger after exception :" + clientAddr, e); - } - holdIt.close(); // Next loop deal with it. - // (including shortening the lease if needed.) - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - thread = null; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("stopped sending queued messages for " + clientAddr); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return clientPeerId + "," + messageList.size() + "," - + (messenger == null ? "-m" : "+m") + "," + TimeUtils.toRelativeTimeMillis(expireTime, TimeUtils.timeNow()); - } - - protected int getQueueSize() { - return messageList.size(); - } - - public long getLeaseRemaining() { - // May be shorter than lease length. Compute real value from expire - // time. - return TimeUtils.toRelativeTimeMillis(expireTime, TimeUtils.timeNow()); - } - - public void closeClient() { - - Messenger messengerToClose; - - synchronized (this) { - if (isClosed) { - return; - } - - isClosed = true; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info( "Terminating client:" + "\n\tclient=" + clientAddr + "\tnbMessages=" + messageList.size() - + "\tmessenger=" + messenger + (messenger == null ? "" : "(c:" + messenger.isClosed() + ")") - + "\tlease-left=" + TimeUtils.toRelativeTimeMillis(expireTime, TimeUtils.timeNow()) + "\tt=" + (thread != null)); - } - - messengerToClose = messenger; - - expireTime = 0; - messenger = null; - - // remove all queued messages if expired - messageList.clear(); - } - - // We can do that out of sync. It avoids nesting locks. - server.removeClient(clientPeerId, this); - if (messengerToClose != null) { - messengerToClose.close(); - } - } - - /** - * remove all queued messages. - */ - synchronized void flushQueue() { - messageList.clear(); - } - - public boolean addMessenger(Messenger newMessenger) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("addMessenger() " + newMessenger); - } - - // make sure we are being passed a valid messenger - if (newMessenger == null || newMessenger.isClosed()) { - return false; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("messenger (" + messenger + ") thread=" + thread); - } - - // Unless we change our mind, we'll close the new messenger. - // If we do not keep it, we must close it. Otherwise - // the client on the other end will never know what happened. - // Its connection will be left hanging for a long time. - - Messenger messengerToClose = newMessenger; - - synchronized (this) { - // Do not use isExpired() here. IsExpired is not supposed to be called - // synchronized. Also isClosed() is good enough. The handler being - // expired is not a problem; we'll figure it out soon enough and do the - // right thing. - - if (!isClosed) { - // use this messenger instead of the old one. - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - if (messenger != null) { - LOG.info("closing messenger replaced by a new one : " + clientAddr); - } - } - - // Swap messengers; we'll close the old one if there was one. - - messengerToClose = messenger; - messenger = newMessenger; - - if ((thread == null || thread_idle) && ((!messageList.isEmpty()) || (outOfBandMessage != null))) { - - // if we do not already have a thread, start one - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("messageList.size() = " + messageList.size() + " client=" + clientAddr); - } - - if (thread != null) { - notify(); - } else { - thread = new Thread(server.group.getHomeThreadGroup(), this, "Draining queue to " + clientAddr); - thread.setDaemon(true); - thread.start(); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("messenger (" + messenger + ") thread=" + thread); - } - } - } - - // Close whichever messenger out of sync. - // In either case, we claim that we kept the new one. - - if (messengerToClose != null) { - messengerToClose.close(); - } - - return true; - } - - public boolean isExpired() { - boolean isExpired = TimeUtils.timeNow() > expireTime; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("isExpired() = " + isExpired + " client=" + clientAddr); - } - - if (isExpired) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Closing expired client : " + clientAddr); - } - closeClient(); - } - - return isExpired; - } - - public synchronized boolean renewLease() { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("renewLease() old expireTime = " + expireTime); - } - - // It is ok to renew a lease past the expiration time, as long - // as the handler has not been closed yet. So, we do not use - // isExpired(). - - if (isClosed) { - return false; - } - - // As long as there are messages to send, the lease is controlled - // by our ability to send them, not by client renewal. - - if (!messageList.isEmpty()) { - return true; - } - - expireTime = TimeUtils.toAbsoluteTimeMillis(leaseLength); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("renewLease() new expireTime = " + expireTime); - } - return true; - } - - /** - * add a message to the tail of the list - * - * @param message the message - * @param outOfBand if true, indicates outbound - * @throws IOException if an io error occurs - */ - private void queueMessage(Message message, boolean outOfBand) throws IOException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("queueMessage (" + messageList.size() + ") client=" + clientAddr); - } - - synchronized (this) { - if (isClosed) { - throw new IOException("Client has been disconnected"); - } - - if (outOfBand) { - // We have a single oob message pending. - outOfBandMessage = message; - } else { - // We will simply discard the latest msg when the queue is full - // to avoid penalty of dropping earlier reliable message - if (!messageList.offer(message)) { - if (Logging.SHOW_WARNING) { - LOG.warning("Dropping relayed message " + message.toString() + " for peer " + clientPeerId); - } - } - } - - // check if a new thread needs to be started. - if ((thread == null) || thread_idle) { - // Normally, if messenger is null we knew it already: - // it becomes null only when we detect that it breaks while - // trying to send. However, let's imagine it's possible that - // we never had one so far. Be carefull that this is not a - // one-time event; we must not keep renewing the short lease; - // that would ruin it's purpose. - - if (messenger == null) { - long newExpireTime = TimeUtils.toAbsoluteTimeMillis(stallTimeout); - - if (expireTime > newExpireTime) { - expireTime = newExpireTime; - } - - } else { - // Messenger good. - // if we do not already have a thread, start one - if (thread != null) { - notify(); - } else { - thread = new Thread(server.group.getHomeThreadGroup(), this, "Draining queue to " + clientAddr); - thread.setDaemon(true); - thread.start(); - } - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("done queueMessage (" + messageList.size() + ") client=" + clientAddr); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("messenger (" + messenger + ") thread=" + thread); - } - } - - protected EndpointAddress getClientAddress() { - return clientAddr; - } - - protected Messenger getMessenger(EndpointAddress srcAddr, EndpointAddress destAddr, boolean outOfBand) { - return new RelayMessenger(srcAddr, destAddr, this, outOfBand); - } - - protected static class RelayMessenger extends BlockingMessenger { - private final MessageElement srcAddressElement; - private final RelayServerClient handler; - private boolean outOfBand = false; - - // Since we send messages through other messengers that do not necessarily have the - // same destination service and param (usually none), we have to pass these along explicitly - // in all cases. If we just build a destination element for the message it will be overwritten - // by messengers below. - private final String defaultServiceName; - private final String defaultServiceParam; - - public RelayMessenger(EndpointAddress srcAddress, EndpointAddress destAddress, RelayServerClient handler, boolean outOfBand) { - - // We do not use self destruction - super(handler.server.group.getPeerGroupID(), destAddress, false); - - this.defaultServiceName = destAddress.getServiceName(); - this.defaultServiceParam = destAddress.getServiceParameter(); - this.handler = handler; - this.outOfBand = outOfBand; - - this.srcAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NAME, srcAddress.toString(), null); - } - - /* - * The cost of just having a finalize routine is high. The finalizer is - * a bottleneck and can delay garbage collection all the way to heap - * exhaustion. Leave this comment as a reminder to future maintainers. - * Below is the reason why finalize is not needed here. - * - * This is never given to application layers directly. No need - * to close-on-finalize. - * - - protected void finalize() { - } - - */ - - /** - * {@inheritDoc} - */ - @Override - public boolean isIdleImpl() { - // We do not use self destruction - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public void closeImpl() { - // Nothing to do. The underlying connection is not affected. - // The messenger will be marked closed by the state machine once completely down; that's it. - } - - /** - * {@inheritDoc} - */ - @Override - public EndpointAddress getLogicalDestinationImpl() { - // getClientAddress returns a clone of the client's jxta: address. - return handler.getClientAddress(); - } - - /* - * {@inheritDoc} - * - *

          Send messages. Messages are queued and then processed when there is a transport messenger. - */ - @Override - public void sendMessageBImpl(Message message, String serviceName, String serviceParam) throws IOException { - - // Set the message with the appropriate src address - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NS, srcAddressElement); - - // load the final destination into the message - EndpointAddress destAddressToUse = getDestAddressToUse(serviceName, serviceParam); - - MessageElement dstAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NAME, - destAddressToUse.toString(), null); - - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NS, dstAddressElement); - - // simply enqueue the message. - // We clone it, since we pretend it's been sent synchronously. - handler.queueMessage(message.clone(), outOfBand); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayTransport.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayTransport.java deleted file mode 100644 index 51188fe8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/RelayTransport.java +++ /dev/null @@ -1,464 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.relay; - -import java.util.NoSuchElementException; - -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import java.util.logging.Logger; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.platform.Module; - -import net.jxta.exception.PeerGroupException; - -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.protocol.RelayConfigAdv; -import net.jxta.pipe.PipeService; - -/** - * The Relay Server supports the following commands: - * - * CONNECT - message contains PEERID, optional LEASE - * DISCONNECT - message contains PEERID. - * GETSERVER - message contains PEERID. - */ - -public final class RelayTransport implements EndpointListener, Module { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(RelayTransport.class.getName()); - - // // constants //// - static final String protocolName = "relay"; - - static final String RELAY_NS = "relay"; - static final String REQUEST_ELEMENT = "request"; - static final String RESPONSE_ELEMENT = "response"; - static final String PEERID_ELEMENT = "peerid"; - static final String LEASE_ELEMENT = "lease"; - static final String RELAY_ADV_ELEMENT = "relayAdv"; - - static final String CONNECT_REQUEST = "connect"; - static final MessageElement CONNECT_REQUEST_ELEMENT = new StringMessageElement(REQUEST_ELEMENT, CONNECT_REQUEST, null); - static final String DISCONNECT_REQUEST = "disconnect"; - static final MessageElement DISCONNECT_REQUEST_ELEMENT = new StringMessageElement(REQUEST_ELEMENT, DISCONNECT_REQUEST, null); - static final String PID_REQUEST = "pid"; - static final MessageElement PID_REQUEST_ELEMENT = new StringMessageElement(REQUEST_ELEMENT, PID_REQUEST, null); - - static final String CONNECTED_RESPONSE = "connected"; - static final MessageElement CONNECTED_RESPONSE_ELEMENT = new StringMessageElement(RESPONSE_ELEMENT, CONNECTED_RESPONSE, null); - static final String DISCONNECTED_RESPONSE = "disconnected"; - static final MessageElement DISCONNECTED_RESPONSE_ELEMENT = new StringMessageElement(RESPONSE_ELEMENT, DISCONNECTED_RESPONSE - , - null); - static final String PID_RESPONSE = "pid"; - static final MessageElement PID_RESPONSE_ELEMENT = new StringMessageElement(RESPONSE_ELEMENT, PID_RESPONSE, null); - - static final int DEFAULT_MAX_CLIENTS = 150; - - static final int DEFAULT_MAX_SERVERS = 1; - - // Note the weird time below can be decreased but should not be increased - // otherwise there will not be enough traffic for the other side to - // keep the connection open. - static final long DEFAULT_LEASE = TimeUtils.ANHOUR; - static final long DEFAULT_STALL_TIMEOUT = 15 * TimeUtils.ASECOND; - - static final long DEFAULT_POLL_INTERVAL = 15 * TimeUtils.ASECOND; // (the poll costs very little) - - static final long DEFAULT_BROADCAST_INTERVAL = 10 * TimeUtils.AMINUTE; - - static final int DEFAULT_CLIENT_QUEUE_SIZE = 20; - - private PeerGroup group = null; - - private String serviceName = null; - - private RelayClient relayClient = null; - private RelayServer relayServer = null; - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement implAdv) throws PeerGroupException { - this.group = group; - ModuleImplAdvertisement implAdvertisement = (ModuleImplAdvertisement) implAdv; - - this.serviceName = assignedID.getUniqueValue().toString(); - - ConfigParams confAdv = group.getConfigAdvertisement(); - - // Get the config. If we do not have a config, we're done; we just keep - // the defaults (edge peer/no auto-rdv) - RelayConfigAdv relayConfigAdv = null; - - if (confAdv != null) { - Advertisement adv = null; - - try { - XMLDocument configDoc = (XMLDocument) confAdv.getServiceParam(assignedID); - - if (null != configDoc) { - adv = AdvertisementFactory.newAdvertisement(configDoc); - } - } catch (NoSuchElementException failed) { - //ignored - } catch (IllegalArgumentException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Error in relay advertisement", failed); - } - - throw failed; - } - - if (adv instanceof RelayConfigAdv) { - relayConfigAdv = (RelayConfigAdv) adv; - } else { - relayConfigAdv = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(RelayConfigAdv.getAdvertisementType()); - } - } - - // XXX bondolo 20041030 I'd like to move these to startApp so that we - // can pass endpointService and share the instance. - if (relayConfigAdv.isServerEnabled()) { - relayServer = new RelayServer(group, serviceName, relayConfigAdv); - } - - if (relayConfigAdv.isClientEnabled()) { - relayClient = new RelayClient(group, serviceName, relayConfigAdv); - } - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Relay Message Transport : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tService Name : ").append(serviceName); - configInfo.append("\n\t\tisServer : ").append(relayConfigAdv.isServerEnabled()); - configInfo.append("\n\t\tisClient : ").append(relayConfigAdv.isClientEnabled()); - - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] args) { - EndpointService endpoint = group.getEndpointService(); - - if (null == endpoint) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - - return START_AGAIN_STALLED; - } - - // XXX bondolo 20041025 Server depends upon discovery and its non-optional. - DiscoveryService discovery = group.getDiscoveryService(); - - if (null == discovery) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a discovery service"); - } - - return START_AGAIN_STALLED; - } - - // XXX bondolo 20041025 Server depends upon pipes and its non-optional. - PipeService pipeService = group.getPipeService(); - - if (null == pipeService) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a pipe service"); - } - - return START_AGAIN_STALLED; - } - - endpoint.addIncomingMessageListener(this, serviceName, null); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Message Listener added " + serviceName); - } - - if (relayServer != null) { - if (!relayServer.startServer()) { - return -1; // cannot start - } - } - - if (relayClient != null) { - if (!relayClient.startClient()) { - return -1; // cannot start - } - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Relay Message Transport started"); - } - - return 0; - } - - /** - * {@inheritDoc} - */ - public void stopApp() { - // remove listener - EndpointService endpoint = group.getEndpointService(); - - if (endpoint == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("could not get EndpointService"); - } - } else { - endpoint.removeIncomingMessageListener(serviceName, null); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Message Listener removed " + serviceName); - } - } - - if (relayServer != null) { - relayServer.stopServer(); - } - - if (relayClient != null) { - relayClient.stopClient(); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Relay Message Transport stopped"); - } - } - - /** - * {@inheritDoc} - */ - public void processIncomingMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Started for " + message + "\tsrc=" + srcAddr); - } - - MessageElement element; - - // check if it is a request - element = message.getMessageElement(RelayTransport.RELAY_NS, REQUEST_ELEMENT); - - if (element != null) { - // this is a request, pass it to the relayServer - if (relayServer != null) { - relayServer.handleRequest(message, dstAddr); - } - } else { - // check if it is a response - element = message.getMessageElement(RelayTransport.RELAY_NS, RESPONSE_ELEMENT); - - if (element != null) { - // this is a response, pass it to the relayClient - if (relayClient != null) { - relayClient.handleResponse(message, dstAddr); - } - } - } - } - - protected PeerGroup getGroup() { - return group; - } - - protected String getServiceName() { - return serviceName; - } - - // This is for reference only, the Desktop client implementation does not - // use that server feature - static Message createPIDRequestMessage() { - Message message = new Message(); - message.addMessageElement(RELAY_NS, PID_REQUEST_ELEMENT); - return message; - } - - static Message createPIDResponseMessage(String pidStr) { - Message message = new Message(); - message.addMessageElement(RELAY_NS, PID_RESPONSE_ELEMENT); - setString(message, PEERID_ELEMENT, pidStr); - - return message; - } - - static Message createConnectMessage(long lease, boolean doReturnAdv, boolean doFlushQueue) { - Message message = new Message(); - String request = createConnectString(lease, doReturnAdv, doFlushQueue); - setString(message, REQUEST_ELEMENT, request); - return message; - } - - static String createConnectString(long lease, boolean doReturnAdv, boolean doFlushQueue) { - - String request = CONNECT_REQUEST; - - if (lease > 0) { - request += "," + Long.toString(lease); - } else { - request += ","; - } - - if (doFlushQueue) { - request += ",flush"; - } else { - request += ",keep"; - } - - if (doReturnAdv) { - request += ",true"; - } else { - request += ",other"; - } - - return request; - } - - static Message createConnectedMessage(long lease) { - Message message = new Message(); - - message.addMessageElement(RELAY_NS, CONNECTED_RESPONSE_ELEMENT); - - if (lease > 0) { - setString(message, LEASE_ELEMENT, Long.toString(lease)); - } - - return message; - } - - static Message createDisconnectMessage() { - Message message = new Message(); - message.addMessageElement(RELAY_NS, DISCONNECT_REQUEST_ELEMENT); - return message; - } - - static Message createDisconnectedMessage() { - Message message = new Message(); - message.addMessageElement(RELAY_NS, DISCONNECTED_RESPONSE_ELEMENT); - return message; - } - - /** - * Convinence function for setting a string element with the relay namespace - * - * @param message the message - * @param elementName message element name - * @param value the value of the string - */ - static void setString(Message message, String elementName, String value) { - // create a new String Element with the given value - StringMessageElement sme = new StringMessageElement(elementName, value, null); - - // add the new element to the message - message.addMessageElement(RELAY_NS, sme); - } - - /** - * Convinence function for getting a String from the element with the given - * tag and relay namespace - * - * @param message the message - * @param elementName the value of the string - * @return the string value, null if the element does not exist - */ - static String getString(Message message, String elementName) { - // get the requested element - MessageElement element = message.getMessageElement(RelayTransport.RELAY_NS, elementName); - - // if the element is not present, return null - if (element == null) { - return null; - } - return element.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/package.html deleted file mode 100644 index 8c7ed340..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/relay/package.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.endpoint.MessageTransport} implementation which - which provides client polling and server store-and forward functionality for - peers incapable of receiving incoming connections. A virtual transport, the - messages are transfered between peers using client initiated connections of - some other message transport. - - @see net.jxta.endpoint.EndpointService - @see net.jxta.endpoint.MessageTransport - @see net.jxta.endpoint.MessageSender - @see net.jxta.endpoint.MessageReceiver - @see net.jxta.endpoint.Message - @see JXTA Protocols Specification : Standard JXTA Transport Bindings - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/BadRoute.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/BadRoute.java deleted file mode 100644 index e731a7b6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/BadRoute.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.router; - - -import net.jxta.peer.PeerID; -import net.jxta.protocol.RouteAdvertisement; - -import java.util.HashSet; -import java.util.Set; - - -/** - * This class is used to cache negative route information. Bad routes are - * represented by three fields: - * - *

            - *
          • Route advertisement,
          • - *
          • Lists of hops that are known bad for that route.
          • - *
          • Expiration time of the negative cache.
          • - *
          - */ -class BadRoute { - - /** - * The RouteAdvertisement with known bad hops. - */ - private final RouteAdvertisement badRoute; - - /** - * The PeerID of the known bad hops in the route. - */ - private final Set badHops = new HashSet(); - - /** - * The absolute time at which this information becomes obsolete. - */ - private long expiration; - - BadRoute(RouteAdvertisement route, long exp, Set hops) { - this.badRoute = route; - this.expiration = exp; - this.badHops.addAll(hops); - } - - /** - * Return the bad route info - * - * @return bad route advertisement - */ - public RouteAdvertisement getRoute() { - if (badRoute != null) { - return badRoute.clone(); - } else { - return null; - } - } - - /** - * Return the absolute time at which the this entry expires. - * - * @return The absolute time at which the this entry expires. - */ - public long getExpiration() { - return expiration; - } - - /** - * set the bad route expiration time - * - * @param exp bad route expiration time - */ - public void setExpiration(long exp) { - this.expiration = exp; - } - - /** - * return the known bad hops in the route - * - * @return bad route hops - */ - public Set getBadHops() { - Set hops = new HashSet(badHops); - - return hops; - } - - /** - * set bad hops into the bad route - * - * @param hops bad route hops - */ - public void setBadHops(Set hops) { - - badHops.clear(); - addBadHops(hops); - } - - /** - * add bad hops into the bad route - * - * @param hops bad route hops - */ - public void addBadHops(Set hops) { - badHops.addAll(hops); - } - - /** - * add a bad hop into the bad route - * - * @param hop The bad route hop. - */ - public void addBadHop(PeerID hop) { - badHops.add(hop); - } - - /** - * {@inheritDoc} - * - *

          Implementation useful for debugging. Don't depend on the format - */ - @Override - public String toString() { - StringBuilder routeBuf = new StringBuilder(); - - routeBuf.append("Bad ").append(getRoute().display()); - routeBuf.append("\tExp: ").append(getExpiration()); - routeBuf.append("\tHops: "); - - for (PeerID eachBadHop : getBadHops()) { - routeBuf.append("\t\t").append(eachBadHop); - } - - return routeBuf.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/Destinations.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/Destinations.java deleted file mode 100644 index 27af7822..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/Destinations.java +++ /dev/null @@ -1,602 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.router; - - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Messenger; -import net.jxta.impl.util.TimeUtils; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.lang.ref.Reference; -import java.lang.ref.SoftReference; -import java.util.*; - - -/** - * This class is a repository of wisdom regarding destinations. It also provides - * a messenger if there is one. Currently, the wisdom is very limited and is - * only about direct destinations (for which a messenger once existed). The - * wisdom that can be obtained is: - * - *

            - *
          • is there a messenger at hand (incoming or otherwise).
          • - * - *
          • is it likely that one can be made from this end, should the one we - * have break. (the last attempt succeeded, not only incoming, and that was - * not long ago).
          • - * - *
          • is either of the above true, (are we confident we can get a - * messenger as of right now one way or the other).
          • - * - *
          • are we supposed to send a welcome to that destination (we can't - * remember having done it).
          • - *
          - * - *

          This could be extended to manage more of the life cycle, such as knowing - * about messengers being resolved or having failed to. This primitive interface - * is temporary; it is only meant to replace messengerPool without having to - * change the router too much. - */ - -class Destinations { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(Destinations.class.getName()); - - /** - * Shared Timer which handles cleanup of expired Wisdom. - */ - private final static transient Timer cleanup = new Timer("Endpoint Destinations GC", true); - - private final Map wisdoms = new HashMap(64); - - /** - * If {@code true} then we are shutting down. - */ - private volatile boolean stopped = false; - - /** - * The endpoint service we are working for. - */ - private final EndpointService endpoint; - - /** - * The wisdom GC task for this instance. - */ - private final WisdomGCTask wisdomGC; - - /** - * Stores knowledge about one particular destination. - * - *

          It does not provide any synchronization. This is provided by the Destinations class. - */ - final class Wisdom { - - /** - * How long we consider that a past outgoingMessenger is an indication - * that one is possible in the future. - */ - static final long EXPIRATION = 10 * TimeUtils.AMINUTE; - - /** - * The channel we last used, if any. They disappear faster than the - * canonical, but, as long as the canonical is around, they can be - * obtained at a near-zero cost. - */ - private Reference outgoingMessenger; - - /** - * The channel we last used if it happens to be an incoming messenger. We keep - * a strong reference to it. - */ - private Messenger incomingMessenger; - - /** - * The transport destination address of the messenger we're caching (if - * not incoming). - */ - private EndpointAddress xportDest; - - /** - * This tells when the outgoing messenger information expires. Incoming - * messengers have no expiration per se. We draw no conclusion from - * their past presence; only current presence. A wisdom is totally - * expired (and may thus be removed) when its outgoing messenger - * information is expired AND it has no incoming messenger. - */ - private long expiresAt = 0; - - /** - * When a new destination is added, we're supposed to send our welcome - * along with the first message. This tells whether isWelcomeNeeded was - * once invoked or not. - */ - private boolean welcomeNeeded = true; - - /** - * @param messenger The messenger to cache information about. - * @param incoming If true, this is an incoming messenger, which means - * that if the channel is lost it cannot be re-obtained. It must - * strongly referenced until it closes for disuse, or breaks. - */ - Wisdom(Messenger messenger, boolean incoming) { - if (incoming) { - addIncomingMessenger(messenger); - } else { - addOutgoingMessenger(messenger); - } - } - - /** - * Reports whether a welcome message is needed. The first time we're - * asked we say "true". Subsequently, always "false". - * - *

          This assumes that the welcome was sent following the first test. - * (so, ask only if you'll send the welcome when told to). - * - * @return {@code true} if this is the first time this method is invoked. - */ - synchronized boolean isWelcomeNeeded() { - boolean res = welcomeNeeded; - - welcomeNeeded = false; - return res; - } - - boolean addIncomingMessenger(Messenger m) { - - // If we have no other incoming, we take it. No questions asked. - Messenger currentIncoming = getIncoming(); - - if (currentIncoming == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Accepted new incoming messenger for " + m.getDestinationAddress()); - } - - incomingMessenger = m; - return true; - } - - // Now, check reachability (0 port number means no incoming connections). - // If the old one looks better, prefer it. - - // Compute reachability of the new one. - String originAddr = m.getDestinationAddress().getProtocolAddress(); - - int index = originAddr.lastIndexOf(':'); - int srcPort = (index != -1) ? Integer.parseInt(originAddr.substring(index + 1)) : 0; - boolean reachable = (srcPort != 0); - - // Compute reachability of the old one. - originAddr = currentIncoming.getDestinationAddress().getProtocolAddress(); - - index = originAddr.lastIndexOf(':'); - srcPort = (index != -1) ? Integer.parseInt(originAddr.substring(index + 1)) : 0; - boolean currentReachable = (srcPort != 0); - - // The new one is less reachable than the old one. Keep the old one. - if (currentReachable && !reachable) { - return false; - } - - incomingMessenger = m; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Accepted new incoming messenger for " + m.getDestinationAddress()); - } - - return true; - } - - boolean addOutgoingMessenger(Messenger m) { - if (getOutgoing() != null) { - return false; - } - this.outgoingMessenger = new SoftReference(m); - xportDest = m.getDestinationAddress(); - expiresAt = TimeUtils.toAbsoluteTimeMillis(EXPIRATION); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Accepted new outgoing messenger for " + xportDest); - } - return true; - } - - void noOutgoingMessenger() { - outgoingMessenger = null; - xportDest = null; - expiresAt = 0; - } - - /** - * Returns an incoming messenger is there is a working one available. - * - * @return an incoming messenger, null if there's none - */ - private Messenger getIncoming() { - if (incomingMessenger != null) { - if ((incomingMessenger.getState() & Messenger.USABLE) != 0) { - return incomingMessenger; - } - - // forget about this broken messenger. - incomingMessenger = null; - } - return null; - } - - /** - * Returns an outgoingMessenger if there is one or one can be made without delay. - * Renews a broken one if it can be. Refreshes expiration time if a messenger is returned. - * - * @return an outgoing messenger, null if there's none - */ - private Messenger getOutgoing() { - - if (outgoingMessenger == null) { - return null; - } - - // (If messenger is not null, it means that we also have a xportDest). - - Messenger messenger = outgoingMessenger.get(); - - // If it is gone or broken, try and get a new one. - if ((messenger == null) || ((messenger.getState() & Messenger.USABLE) == 0)) { - - messenger = endpoint.getMessengerImmediate(xportDest, null); - - // If this fails, it is hopeless: the address is bad or something like that. Make ourselves expired right away. - if (messenger == null) { - outgoingMessenger = null; - xportDest = null; - expiresAt = 0; - return null; - } - - // Renew the ref. The xportDest is the same. - outgoingMessenger = new SoftReference(messenger); - } - - // So we had one or could renew. But, does it work ? - if ((messenger.getState() & (Messenger.USABLE & Messenger.RESOLVED)) == 0) { - // We no-longer have the underlying connection. Let ourselves expire. Do not renew the expiration time. - outgoingMessenger = null; - xportDest = null; - return null; - } - - // Ok, we do have an outgoing messenger at the ready after all. - expiresAt = TimeUtils.toAbsoluteTimeMillis(EXPIRATION); - return messenger; - } - - /** - * Returns a channel for this destination if one is there or can be obtained - * readily and works. - *

          - *

          We prefer the incoming connection to the outgoing for two - * reasons: - *

            - *
          • The remote peer was able to reach us. We cannot be sure that - * we can reach the remote peer.
          • - *
          • The remote peer initiated the connection. It has a better - * sense of when the connection should be closed or reopened than - * we do.
          • - * - * @return a channel for this destination - */ - Messenger getCurrentMessenger() { - Messenger res = getIncoming(); - - if (res != null) { - return res; - } - - return getOutgoing(); - } - - /** - * @return true if we do have an outgoing messenger or, failing that, we had one not too long ago. - */ - boolean isNormallyReachable() { - return ((getOutgoing() != null) || (TimeUtils.toRelativeTimeMillis(expiresAt) >= 0)); - } - - /** - * We think the destination is reachable somehow. Not sure how long. - * - * @return true if we have any kind of messenger or, failing that, we had an outgoing one not too long ago. - */ - boolean isCurrentlyReachable() { - return ((getIncoming() != null) || (getOutgoing() != null) || (TimeUtils.toRelativeTimeMillis(expiresAt) >= 0)); - } - - /** - * @return true if this wisdom carries no positive information whatsoever. - */ - boolean isExpired() { - return !isCurrentlyReachable(); - } - } - - /* - * Internal mechanisms - */ - - /** - * Return any Wisdom for the specified destination. The address will - * be normalized to the base form. - * - * @param destination The address of the wisdom that is sought. - * @return The Wisdom for this address or {@code null} if no Wisdom found. - */ - private Wisdom getWisdom(EndpointAddress destination) { - if (destination.getServiceName() != null) { - destination = new EndpointAddress(destination, null, null); - } - return wisdoms.get(destination); - } - - /** - * Add a Wisdom for the specified destination. The address will - * be normalized to the base form. - * - * @param destination The address of the Wisdom that is being added. - * @param wisdom The Wisdom for this address to be added to the map. - */ - private void addWisdom(EndpointAddress destination, Wisdom wisdom) { - destination = new EndpointAddress(destination, null, null); - wisdoms.put(destination, wisdom); - } - - /* - * General house keeping. - */ - - public Destinations(EndpointService endpoint) { - - this.endpoint = endpoint; - - wisdomGC = new WisdomGCTask(); - - cleanup.schedule(wisdomGC, TimeUtils.AMINUTE, TimeUtils.AMINUTE); - } - - /** - * Shutdown this cache. (stop the gc) - */ - public synchronized void close() { - stopped = true; - - // forget everything. - wisdoms.clear(); - - wisdomGC.cancel(); - } - - /** - * Handles cleanup of expired wisdoms - */ - class WisdomGCTask extends TimerTask { - - /** - * {@inheritDoc} - * - *

            garbage collector. We use soft references to messengers, but we use - * a strong hashmap to keep the wisdom around in a more predictable - * manner. Entries are simply removed when they no-longer carry - * relevant information; so there's no change in the total meaning of - * the map when an entry is removed. - */ - @Override - public void run() { - try { - synchronized (Destinations.this) { - Iterator eachWisdom = wisdoms.values().iterator(); - - while (eachWisdom.hasNext()) { - Wisdom w = eachWisdom.next(); - - if (w.isExpired()) { - eachWisdom.remove(); - } - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && Destinations.LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in TimerTask :" + Thread.currentThread().getName(), all); - } - } - } - } - - public synchronized Collection allDestinations() { - - Set allKeys = wisdoms.keySet(); - List res = new ArrayList(allKeys); - - return res; - } - - /* - * information output - */ - - /** - * If there is a messenger at hand (incoming or otherwise), return it. - * - * @param destination The destination as an endpoint address (is automatically normalized to protocol and address only). - * @return A messenger to that destination if a resolved and usable one is available or can be made instantly. null otherwise. - */ - public synchronized Messenger getCurrentMessenger(EndpointAddress destination) { - Wisdom wisdom = getWisdom(destination); - - if (wisdom == null) { - return null; - } - return wisdom.getCurrentMessenger(); - } - - /** - * Is it likely that one can be made from this end. (the last attempt succeeded, not only incoming, and that was not long ago) ? - * This is a conservative test. It means that declaring that we can route to that destination is a very safe bet, as opposed - * to isNormallyReachable and getCurrentMessenger, which could be misleading if the only messenger we can ever get is incoming. - * Not currently used. Should likely be. - * - * @param destination The destination as an endpoint address (is automatically normalized to protocol and address only). - * @return true if it is likely that we can get a messenger to that destination in the future. - */ - public synchronized boolean isNormallyReachable(EndpointAddress destination) { - Wisdom wisdom = getWisdom(destination); - - return ((wisdom != null) && wisdom.isNormallyReachable()); - } - - /** - * Do we already have a messenger or is it likely that we can make one? - * We is will return {@code true} more often than - * {@code isNormallyReachable()} since it can be true even when all we have - * is an incoming messenger. - * - *

            Just testing that there is an entry is no-longer the same because we - * may keep the entries beyond the point where we would keep them before, so - * that we can add some longer-lived information in the future, and do not - * interfere as much with the gc thread. - * - * @param destination The destination as an endpoint address (is automatically normalized to protocol and address only). - * @return true is we are confident that we can obtain a messenger, either because we can get one instantly, or because - * this destination is normally reachable. (So, it is ok to try and route to that destination, now). - */ - public synchronized boolean isCurrentlyReachable(EndpointAddress destination) { - Wisdom wisdom = getWisdom(destination); - - return ((wisdom != null) && wisdom.isCurrentlyReachable()); - } - - /** - * Are we supposed to send a welcome to that destination (we can't remember having done it). - * It is assumed that once true was returned, it will be acted upon. So, true is not returned a second time. - * - * @param destination The destination as an endpoint address (is automatically normalized to protocol and address only). - * @return true if this a destination to whish we can't remember sending a welcome message. - */ - public synchronized boolean isWelcomeNeeded(EndpointAddress destination) { - Wisdom wisdom = getWisdom(destination); - - return ((wisdom != null) && wisdom.isWelcomeNeeded()); - } - - /* - * information input. - */ - - /** - * Here is a messenger that we were able to obtain. - * - * @param destination The destination as an endpoint address (is automatically normalized to protocol and address only). - * @param messenger The incoming messenger for that destination. - * @return true if this messenger was added (keep it open). false otherwise (do what you want with it). - */ - public synchronized boolean addOutgoingMessenger(EndpointAddress destination, Messenger messenger) { - Wisdom wisdom = getWisdom(destination); - - if (wisdom != null) { - return wisdom.addOutgoingMessenger(messenger); - } - addWisdom(destination, new Wisdom(messenger, false)); - return true; - } - - /** - * Here is an incoming messenger that just popped out. - * - * @param destination The destination as an endpoint address (is automatically normalized to protocol and address only). - * @param messenger The incoming messenger for that destination. - * @return true if this messenger was added (keep it open). false otherwise (do what you want with it). - */ - public synchronized boolean addIncomingMessenger(EndpointAddress destination, Messenger messenger) { - Wisdom wisdom = getWisdom(destination); - - if (wisdom != null) { - return wisdom.addIncomingMessenger(messenger); - } - addWisdom(destination, new Wisdom(messenger, true)); - return true; - } - - /** - * We tried to get a messenger but could not. We know that we do not have connectivity from our end, for now. we may still - * have an incoming. However, if we had to try and make a messenger, there probably isn't an incoming, but that's not our - * business here. isNormallyReachable becomes false; but we can still try when solicited. - * - * @param destination The destination as an endpoint address (is automatically normalized to protocol and address only). - */ - public synchronized void noOutgoingMessenger(EndpointAddress destination) { - Wisdom wisdom = getWisdom(destination); - - if (wisdom != null) { - wisdom.noOutgoingMessenger(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/EndpointRouter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/EndpointRouter.java deleted file mode 100644 index 1db22384..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/EndpointRouter.java +++ /dev/null @@ -1,2715 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.router; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageReceiver; -import net.jxta.endpoint.MessageSender; -import net.jxta.endpoint.MessageTransport; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.MessengerEvent; -import net.jxta.endpoint.MessengerEventListener; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.endpoint.LoopbackMessenger; -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.util.TimerThreadNamer; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.AccessPointAdvertisement; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RouteAdvertisement; -import net.jxta.service.Service; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class EndpointRouter implements EndpointListener, MessageReceiver, MessageSender, MessengerEventListener, Module { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(EndpointRouter.class.getName()); - - /** - * Until we decide otherwise, the router is *by definition* handling - * virtually addressed messages. - */ - private final static String ROUTER_PROTOCOL_NAME = "jxta"; - - /** - * Router Service Name - */ - private final static String ROUTER_SERVICE_NAME = "EndpointRouter"; - - /** - * how long we are willing to wait for a response from an async - * getMessenger. We do not wait long at all because it is non-critical - * that we get the answer synchronously. The goal is to avoid starting - * a route discovery if there's a chance to get a direct connection. - * However, we will still take advantage of the direct route if it is - * found while we wait for the route discovery result. If that happens, - * the only wrong is that we used some bandwidth doing a route discovery - * that wasn't needed after all. - */ - public final static long ASYNC_MESSENGER_WAIT = 3L * TimeUtils.ASECOND; - - /** - * MessageTransport Control operation - */ - public final static Integer GET_ROUTE_CONTROL = 0; // Return RouteControl Object - public final static int RouteControlOp = 0; // Return RouteControl Object - - /** - * MAX timeout (seconds) for route discovery after that timeout - * the peer will bail out from finding a route - */ - private final static long MAX_FINDROUTE_TIMEOUT = 60L * TimeUtils.ASECOND; - - /** - * How long do we wait (seconds) before retrying to make a connection - * to an endpoint destination - */ - private final static long MAX_ASYNC_GETMESSENGER_RETRY = 30L * TimeUtils.ASECOND; - - /** - * These are peers which we know multi-hop routes for. - */ - private final Map routedRoutes = new HashMap(16); - - /** - * A record of failures. - *

            - * Values are the time of failure as {@link java.lang.Long}. If - * {@code Long.MAX_VALUE} then a connect attempt is current in progress. - */ - private final Map triedAndFailed = new HashMap(); - - /** - * local peer ID as an endpointAddress. - */ - private EndpointAddress localPeerAddr = null; - - /** - * local Peer ID - */ - private PeerID localPeerId = null; - - /** - * The Endpoint Service we are routing for. - */ - private EndpointService endpoint = null; - - /** - * PeerGroup handle - */ - private PeerGroup group = null; - - private ID assignedID = null; - - /** - * If {@code true} this service has been closed. - */ - private boolean stopped = false; - - /** - * Whenever we initiate connectivity to a peer (creating a direct route). - * we remember that we need to send our route adv to that peer. So that - * it has a chance to re-establish the connection from its side, if need - * be. The route adv is actually sent piggy-backed on the first message - * that goes there. - */ - private final Set newDestinations = Collections.synchronizedSet(new HashSet()); - - /** - * A pool of messengers categorized by logical address. - * This actually is the direct routes map. - */ - private Destinations destinations; - - /** - * A record of expiration time of known bad routes we received a NACK route - */ - private final Map badRoutes = new HashMap(); - - /** - * We record queries when first started and keep them pending for - * a while. Threads coming in the meanwhile wait for a result without - * initiating a query. Thus threads may wait passed the point where - * the query is no-longer pending, and, although they could initiate - * a new one, they do not. - *

            - * However, other threads coming later may initiate a new query. So a - * query is not re-initiated systematically on a fixed schedule. This - * mechanism also serves to avoid infinite recursions if we're looking - * for the route to a rendezvous (route queries will try to go there - * themselves). - *

            - * FIXME: jice@jxta.org 20020903 this is approximate. We can do - * cleaner/better than this, but it's already an inexpensive improvement - * over what used before. - *

            - * FIXME: tra@jxta.org 20030818 the pending hashmap should be moved - * in the routeResolver class. - */ - private final Map pendingQueries = - Collections.synchronizedMap(new HashMap()); - - /** - * Timer by which we schedule the clearing of pending queries. - */ - private final Timer timer = new Timer("EndpointRouter Timer", true); - - /** - * PeerAdv tracking. - * The peer adv is modified every time a new public address is - * enabled/disabled. One of such cases is the connection/disconnection - * from a relay. Since these changes are to the embedded route adv - * and since we may embed our route adv in messages, we must keep it - * up-to-date. - */ - private PeerAdvertisement lastPeerAdv = null; - private int lastModCount = -1; - - /** - * Route info for the local peer (updated along with lastPeerAdv). - */ - private RouteAdvertisement localRoute = null; - - /** - * Route CM persistent cache - */ - private RouteCM routeCM = null; - - /** - * Route Resolver - */ - private RouteResolver routeResolver; - - class ClearPendingQuery extends TimerTask { - final PeerID peerID; - volatile boolean failed = false; - long nextRouteResolveAt = 0; - - ClearPendingQuery(PeerID peerID) { - this.peerID = peerID; - // We schedule for one tick at one minute and another at 5 minutes - // after the second, we cancel ourselves. - timer.schedule(this, TimeUtils.AMINUTE, 5L * TimeUtils.AMINUTE); - nextRouteResolveAt = TimeUtils.toAbsoluteTimeMillis(20L * TimeUtils.ASECOND); - } - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - if (failed) { - // Second tick. - // This negative cache info is expired. - pendingQueries.remove(peerID); - - this.cancel(); - } else { - // First timer tick. We're done trying. This is now a negative - // cache info. For the next 5 minutes that destination fails - // immediately unless it unexpectedly gets finaly resolved. - failed = true; - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in timer task " + Thread.currentThread().getName() + " for " + peerID, all); - } - } - } - - public synchronized boolean isTimeToResolveRoute() { - if (TimeUtils.toRelativeTimeMillis(nextRouteResolveAt) > 0) { - return false; - } - // nextRouteResolveAt is passed. Set the next time to retry from now. - nextRouteResolveAt = TimeUtils.toAbsoluteTimeMillis(20L * TimeUtils.ASECOND); - return true; - } - - public boolean isFailed() { - return failed; - } - } - - RouteAdvertisement getMyLocalRoute() { - - // Update our idea of the local peer adv. If it has change, - // update our idea of the local route adv. - // If nothing has changed, do not do any work. - // In either case, return the local route adv as it is after this - // refresh. - - // Race condition possible but tolerable: if two threads discover - // the change in the same time, lastPeerAdv and lastModCount - // could become inconsistent. That'll be straightened out the - // next time someone looks. The inconsistency can only trigger - // an extraneous update. - - PeerAdvertisement newPadv = group.getPeerAdvertisement(); - int newModCount = newPadv.getModCount(); - - if ((lastPeerAdv != newPadv) || (lastModCount != newModCount) || (null == localRoute)) { - lastPeerAdv = newPadv; - lastModCount = newModCount; - } else { - // The current version is good. - return localRoute; - } - - // Get its EndpointService advertisement - XMLElement endpParam = (XMLElement) - newPadv.getServiceParam(PeerGroup.endpointClassID); - - if (endpParam == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("no Endpoint SVC Params"); - } - - // Return whatever we had so far. - return localRoute; - } - - // get the Route Advertisement element - Enumeration paramChilds = endpParam.getChildren(RouteAdvertisement.getAdvertisementType()); - XMLElement param; - - if (paramChilds.hasMoreElements()) { - param = (XMLElement) paramChilds.nextElement(); - } else { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("no Endpoint Route Adv"); - } - - // Return whatever we had so far. - return localRoute; - } - - // build the new route - try { - // Stick the localPeerID in-there, since that was what - // every single caller of getMyLocalRoute did so far. - - RouteAdvertisement route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(param); - - route.setDestPeerID(localPeerId); - localRoute = route; - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure extracting route", ex); - } - } - - return localRoute; - } - - /** - * listener object to synchronize on asynchronous getMessenger - */ - private static class EndpointGetMessengerAsyncListener implements MessengerEventListener { - - private final EndpointRouter router; - private final EndpointAddress logDest; - - volatile boolean hasResponse = false; - volatile boolean isGone = false; - private Messenger messenger = null; - - /** - * Constructor - * - * @param router the router - * @param dest logical destination - */ - EndpointGetMessengerAsyncListener(EndpointRouter router, EndpointAddress dest) { - this.router = router; - this.logDest = dest; - } - - /** - * {@inheritDoc} - */ - public boolean messengerReady(MessengerEvent event) { - - Messenger toClose = null; - - synchronized (this) { - hasResponse = true; - if (event != null) { - messenger = event.getMessenger(); - if (null != messenger) { - if(!logDest.equals(messenger.getLogicalDestinationAddress())) { - // Ooops, wrong number ! - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Incorrect Messenger logical destination : " + logDest + "!=" + messenger.getLogicalDestinationAddress()); - } - - toClose = messenger; - messenger = null; - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("null messenger for dest :" + logDest); - } - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("null messenger event for dest :" + logDest); - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - if (messenger == null) { - LOG.fine("error creating messenger for dest :" + logDest); - } else { - LOG.fine("got a new messenger for dest :" + logDest); - } - } - - // We had to release the lock on THIS before we can get the lock on - // the router. (Or face a dead lock - we treat this as a lower level - // lock) - - if (messenger == null) { - if (toClose != null) { - toClose.close(); - } - - // we failed to get a messenger, we need to update the try and - // failed as it currently holds an infinite timeout to permit - // another thread to retry that destination. We only retry - // every MAX_ASYNC_GETMESSENGER_RETRY seconds - - router.noMessenger(logDest); - - synchronized (this) { - // Only thing that can happen is that we notify for nothing - // We took the lock when updating hasResult, so, the event - // will not be missed. - // FIXME It would be more logical to let the waiter do the - // above if (!isGone) as in the case of success below. - // However, we'll minimize changes for risk management - // reasons. - notify(); - } - return false; - } - - // It worked. Update router cache entry if we have to. - - synchronized (this) { - if (!isGone) { - notify(); // Waiter will do the rest. - return true; - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("async caller gone add the messenger " + logDest); - } - return router.newMessenger(event); - } - - /** - * Wait on the async call for ASYNC_MESSENGER_WAIT - * then bailout. The messenger will be added whenever - * the async getMessenger will return - * - * @param quick if true return a messenger immediately if available, - * otherwise wait the Messenger resolution to be completed - * @return the Messenger if one available - */ - public synchronized Messenger waitForMessenger(boolean quick) { - if (!quick) { - long quitAt = TimeUtils.toAbsoluteTimeMillis(ASYNC_MESSENGER_WAIT); - - while (TimeUtils.toRelativeTimeMillis(quitAt) > 0) { - try { - // check if we got a response already - if (hasResponse) { // ok, we got a response - break; - } - wait(ASYNC_MESSENGER_WAIT); - } catch (InterruptedException woken) { - Thread.interrupted(); - break; - } - } - } - - // mark the fact that the caller is bailing out - isGone = true; - return messenger; - } - } - - /** - * isLocalRoute is a shallow test. It tells you that there used to be a - * local route that worked the last time it was tried. - * - * @param peerAddress Address of the destination who's route is desired. - * @return {@code true} if we know a direct route to the specified address - * otherwise {@code false}. - */ - boolean isLocalRoute(EndpointAddress peerAddress) { - return destinations.isCurrentlyReachable(peerAddress); - } - - /** - * Get a Messenger for the specified destination if a direct route is known. - * - * @param peerAddress The peer who's messenger is desired. - * @param hint A route hint to use if a new Messenger must be created. - * @return Messenger for direct route or {@code null} if none could be - * found or created. - */ - Messenger ensureLocalRoute(EndpointAddress peerAddress, RouteAdvertisement hint) { - - // We need to make sure that there is a possible connection to that peer - // If we have a decent (not closed, busy or available) transport - // messenger in the pool, then we're done. Else we activly try to make - // one. - - // See if we already have a messenger. - Messenger messenger = destinations.getCurrentMessenger(peerAddress); - - if (messenger != null) { - return messenger; - } - - // Ok, try and make one. Pass the route hint info - messenger = findReachableEndpoint(peerAddress, false, hint); - if (messenger == null) { - // We must also zap it from our positive cache: if we remembered it - // working, we should think again. - destinations.noOutgoingMessenger(peerAddress); - return null; // No way. - } - - destinations.addOutgoingMessenger(peerAddress, messenger); - - // We realy did bring something new. Give relief to those that have been - // waiting for it. - synchronized (this) { - notifyAll(); - } - - // NOTE to maintainers: Do not remove any negative cache info - // or route here. It is being managed by lower-level routines. - // The presence of a messenger in the pool has many origins, - // each case is different and taken care of by lower level - // routines. - return messenger; - } - - /** - * Send a message to a given logical destination if it maps to some - * messenger in our messenger pool or if such a mapping can be found and - * added. - * - * @param destination peer-based address to send the message to. - * @param message the message to be sent. - * @throws java.io.IOException if an io error occurs - */ - void sendOnLocalRoute(EndpointAddress destination, Message message) throws IOException { - - IOException lastIoe = null; - Messenger sendVia; - - // Try sending the message as long as we get have transport messengers - // to try with. They close when they fail, which puts them out of cache - // or pool if any, so we will not see a broken one a second time. We'll - // try the next one until we run out of options. - - while ((sendVia = ensureLocalRoute(destination, null)) != null) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + message + " to " + destination + " via " + sendVia); - } - - try { - // FIXME 20040413 jice Maybe we should use the non-blocking mode - // and let excess messages be dropped given the threading issue - // still existing in the input circuit (while routing messages - // through). - - sendVia.sendMessageB(message, EndpointRouter.ROUTER_SERVICE_NAME, null); - - // If we reached that point, we're done. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sent " + message + " to " + destination); - } - return; - - } catch (IOException ioe) { - // Can try again, with another messenger (most likely). - lastIoe = ioe; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Trying next messenger to " + destination); - } - // try the next messenger if there is one. - } - - // Now see why we're here. - // If we're here for no other reason than failing to get a messenger - // say so. Otherwise, report the failure from the last time we tried. - if (lastIoe == null) { - lastIoe = new IOException("No reachable endpoints for " + destination); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Could not send to " + destination, lastIoe); - } - - throw lastIoe; - } - - /** - * Default constructor - */ - public EndpointRouter() { - } - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - - timer.schedule(new TimerThreadNamer("EndpointRouter Timer for " + group.getPeerGroupID()), 0); - - this.group = group; - this.assignedID = assignedID; - ModuleImplAdvertisement implAdvertisement = (ModuleImplAdvertisement) impl; - - localPeerId = group.getPeerID(); - localPeerAddr = pid2addr(group.getPeerID()); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Router Transport : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tProtocol : ").append(getProtocolName()); - configInfo.append("\n\t\tPublic Address : ").append(localPeerAddr); - - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public synchronized int startApp(String[] arg) { - endpoint = group.getEndpointService(); - - if (null == endpoint) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - return START_AGAIN_STALLED; - } - - Service needed = group.getResolverService(); - - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Endpoint Router start stalled until resolver service available"); - } - return Module.START_AGAIN_STALLED; - } - - needed = group.getMembershipService(); - - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Endpoint Router start stalled until membership service available"); - } - return Module.START_AGAIN_STALLED; - } - - needed = group.getRendezVousService(); - - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Endpoint Router start stalled until rendezvous service available"); - } - return Module.START_AGAIN_STALLED; - } - - destinations = new Destinations(endpoint); - - try { - // FIXME tra 20030818 Should be loaded as a service - // when we have service dependency. When loaded as a true service should - // not have to pass the EnpointRouter object. The issue is we need an - // api to obtain the real object from the PeerGroup API. - routeCM = new RouteCM(); - - // FIXME tra 20030818 Should be loaded as a service - // when we have service dependency. When loaded as a true service should - // not have to pass the EnpointRouter object. The issue is we need an - // api to obtain the real object from the PeerGroup API. - routeResolver = new RouteResolver(this); - - // initialize persistent CM route Cache - // FIXME tra 20030818 Should be loaded as service when complete - // refactoring is done. - routeCM.init(group, assignedID, null); - - // initialize the route resolver - // FIXME tra 20030818 Should be loaded as service when complete - // refactoring is done. - routeResolver.init(group, assignedID, null); - } catch (PeerGroupException failure) { - return -1; - } - - int status; - - // FIXME tra 20031015 Should be started as a service when refactored work - // completed - status = routeCM.startApp(arg); - if (status != 0) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Route CM failed to start : " + status); - } - - return status; - } - - // FIXME tra 20031015 Should be started as a service when refactored work - // completed - status = routeResolver.startApp(arg); - if (status != 0) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Route Resolver failed to start : " + status); - } - return status; - } - // publish my local route adv - routeCM.publishRoute(getMyLocalRoute()); - - // FIXME tra 20031015 is there a risk for double registration when - // startApp() is recalled due to failure to get the discovery service - // by the Route Resolver service. - - // NOTE: Endpoint needs to be registered before we register the endpoint - // resolver. This is bringing a more complex issue of service loading - // dependencies. - endpoint.addMessengerEventListener(this, EndpointService.MediumPrecedence); - - endpoint.addIncomingMessageListener(this, ROUTER_SERVICE_NAME, null); - - if (endpoint.addMessageTransport(this) == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Transport registration refused"); - } - - return -1; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info(group + " : Router Message Transport started."); - } - return status; - } - - /** - * {@inheritDoc} - *

            - * Careful that stopApp() could in theory be called before startApp(). - */ - public synchronized void stopApp() { - stopped = true; - - if (endpoint != null) { - endpoint.removeIncomingMessageListener(ROUTER_SERVICE_NAME, null); - endpoint.removeMessengerEventListener(this, EndpointService.MediumPrecedence); - endpoint.removeMessageTransport(this); - } - - // FIXME tra 20030818 should be unloaded as a service - routeCM.stopApp(); - - // FIXME tra 20030818 should be unloaded as a service - routeResolver.stopApp(); - - destinations.close(); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info(group + " : Router Message Transport stopped."); - } - } - - /** - * {@inheritDoc} - */ - public boolean isConnectionOriented() { - return false; - } - - /** - * {@inheritDoc} - */ - public boolean allowsRouting() { - // Yes, this is the router, and it does not allow routing. - // Otherwise we would have a chicken and egg problem. - return false; - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - return endpoint; - } - - /** - * {@inheritDoc} - */ - public EndpointAddress getPublicAddress() { - return localPeerAddr; - } - - /** - * {@inheritDoc} - */ - public Iterator getPublicAddresses() { - return Collections.singletonList(getPublicAddress()).iterator(); - } - - /** - * {@inheritDoc} - */ - public String getProtocolName() { - return ROUTER_PROTOCOL_NAME; - } - - /** - * Given a peer id, return an address to reach that peer. - * The address may be for a directly reachable peer, or - * for the first gateway along a route to reach the peer. - * If we do not have a route to the peer, we will use the - * Peer Routing Protocol to try to discover one. We will - * wait up to 30 seconds for a route to be discovered. - * - * @param peerAddress the peer we are trying to reach. - * @param seekRoute whether to go as far as issuing a route query, or just fish in our cache. - * when forwarding a message we allow ourselves to mend a broken source-issued route but we - * won't go as far as seeking one from other peers. When originating a message, on the other end - * we will aggressively try to find route. - * @param hint whether we are passed a route hint to be used, in that case that route - * hint should be used - * @return an EndpointAddress at which that peer should be reachable. - */ - EndpointAddress getGatewayAddress(EndpointAddress peerAddress, boolean seekRoute, RouteAdvertisement hint) { - PeerID peerID = addr2pid(peerAddress); - - try { - // FIXME 20021215 jice Replace this junk with a background task; - // separate the timings of route disco from the timeouts of - // the requesting threads. EndpointAddress result = null; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Searching local" + (seekRoute ? " & remote" : "") + " for route for " + peerAddress); - } - - // If we can't get a route within the timeout, give up for now. - long quitAt = TimeUtils.toAbsoluteTimeMillis(MAX_FINDROUTE_TIMEOUT); - - // Time we need to wait before we can start issue a find route request - // to give a chance for the async messenger to respond (success or failure) - long findRouteAt = TimeUtils.toAbsoluteTimeMillis(ASYNC_MESSENGER_WAIT); - - EndpointAddress addr; - - while (TimeUtils.toRelativeTimeMillis(quitAt) > 0) { - // Then check if by any chance we can talk to it directly. - Messenger directMessenger = ensureLocalRoute(peerAddress, hint); - - if (null != directMessenger) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Found direct route for " + peerAddress + " via " + directMessenger.getDestinationAddress()); - } - return peerAddress; - } - - // Otherwise, look for a long route. - // check if we got a hint. If that's the case use it - RouteAdvertisement route; - - if (hint != null) { - route = hint; - } else { - route = getRoute(peerAddress, seekRoute); - } - - if (route != null && route.size() > 0) { - addr = pid2addr(route.getLastHop().getPeerID()); - if (ensureLocalRoute(addr, null) != null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Found last hop remote address: " + peerAddress + " -> " + route.getLastHop().getPeerID()); - } - - // Ensure local route removes negative cache info about - // addr. We also need to remove that about peerAddress. - return addr; - } else { // need to try the first hop - addr = pid2addr(route.getFirstHop().getPeerID()); - - if (ensureLocalRoute(addr, null) != null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Found first hop remote address first hop: " + peerAddress + " -> " - + route.getFirstHop().getPeerID()); - } - - // Ensure local route removes negative cache info about addr. - return addr; - } else { - removeRoute(peerID); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Found no reachable route to " + peerAddress); - } - } - } - } - - // For messages we didn't originate we don't seek routes. - if (!seekRoute) { - break; - } - - // Check that route resolution is enabled if - // not then bail out, there is nothing more - // that we can do. - if (!routeResolver.useRouteResolver()) { - break; - } - - // due to the asynchronous nature of getting our messenger we - // need to handle the multi-entrance of issueing a route - // discovery. A route discovery needs to be generated only - // either if we have no pending request (it completed or we had - // no information so we did not created one), or we tried and - // we failed, or we waited at least ASYNC_MESSENGER_WAIT to get - // a chance for the async request to respond before we can - // issue the route discovery - Long nextTry = triedAndFailed.get(peerID); - - if ((nextTry == null) || (nextTry < TimeUtils.toAbsoluteTimeMillis(MAX_ASYNC_GETMESSENGER_RETRY)) - || (TimeUtils.toRelativeTimeMillis(findRouteAt) <= 0)) { - - // If it is already hopeless (negative cache), just give up. - // Otherwise, try and recover the route. If a query is not - // already pending, we may trigger a route discovery before we - // wait. Else, just wait. The main problem we have here is that - // the same may re-enter because the resolver query sent by - // findRoute ends up with the rendezvous service trying to - // resolve the same destiation if the destination happens to be - // the start of the walk. In that situation we will re-enter - // at every findRoute attempt until the query becomes "failed". - // However, we do want to do more than one findRoute because - // just one attempt can fail for totaly fortuitous or temporary - // reasons. A tradeoff is to do a very limitted number of attempts - // but still more than one. Over the minute for which the query - // is not failed, isTimeToRety will return true at most twice - // so that'll be a total of three attempts: once every 20 seconds. - boolean doFind = false; - ClearPendingQuery t; - - synchronized (pendingQueries) { - t = pendingQueries.get(peerID); - - if (t == null) { - doFind = true; - t = new ClearPendingQuery(peerID); - pendingQueries.put(peerID, t); - } else { - if (t.isFailed()) { - break; - } - if (t.isTimeToResolveRoute()) { - doFind = true; - } - } - } - - // protect against the async messenger request. We only - // look for a route after the first iteration by - // that time we will have bailed out from the async call - if (doFind) { - routeResolver.findRoute(peerAddress); - // we do not need to check the CM, route table will - // be updated when the route response arrive. This reduces - // CM activities when we wait for the route response - seekRoute = false; - } - } - - // Now, wait. Responses to our query may occur asynchronously. - // threads. - synchronized (this) { - // We can't possibly do everything above while synchronized, - // so we could miss an event of interrest. But some changes - // are not readily noticeable anyway, so we must wake up - // every so often to retry. - try { - // we only need to wait if we haven't got a messenger - // yet. - if (destinations.getCurrentMessenger(peerAddress) == null) { - wait(ASYNC_MESSENGER_WAIT); - } - } catch (InterruptedException woken) { - Thread.interrupted(); - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No route to " + peerAddress); - } - return null; - - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "getGatewayAddress exception", ex); - } - return null; - } - } - - /** - * {@inheritDoc} - */ - @Deprecated - public boolean ping(EndpointAddress addr) { - - EndpointAddress plainAddr = new EndpointAddress(addr, null, null); - - try { - return (getGatewayAddress(plainAddr, true, null) != null); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.FINE, "Ping failure (exception) for : " + plainAddr, e); - } - return false; - } - } - - /** - * Receives notifications of new messengers being generated by the - * underlying network transports. - *

            - * IMPORTANT: Incoming messengers only. If/when this is used for - * outgoing, some things have to change: - *

            - * For example we do not need to send the welcome msg, but for - * outgoing messengers, we would need to. - *

            - * Currently, newMessenger handles the outgoing side. - * - * @param event the new messenger event. - */ - public boolean messengerReady(MessengerEvent event) { - - Messenger messenger = event.getMessenger(); - Object source = event.getSource(); - EndpointAddress logDest = messenger.getLogicalDestinationAddress(); - - if (source instanceof MessageSender && !((MessageSender) source).allowsRouting()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Ignoring messenger to :" + logDest); - } - return false; - } - - // We learned that a transport messenger has just been announced. - // Nobody else took it, so far, so we'll take it. Incoming messengers - // are not pooled by the endpoint service. We do pool them for our - // exclusive use. - - boolean taken = destinations.addIncomingMessenger(logDest, messenger); - - // Note to maintainers: Do not remove any route or negative cache info - // here. Here is why: The messenger we just obtained was made out of an - // incoming connection. It brings no proof whatsoever that the peer is - // reachable at our initiative. In general, there is nothing to gain in - // removing our knowlege of a long route, or a pending route query, or a - // triedAndFailed record, other than to force trying a newly obtained - // set of addresses. They will not stop us from using this messenger as - // long as it works. The only good thing we can do here, is waking up - // those that may be waiting for a connection. - - synchronized (this) { - notifyAll(); - } - return taken; - } - - /** - * Call when an asynchronous new messenger could not be obtained. - * - * @param logDest the failed logical destination - */ - void noMessenger(EndpointAddress logDest) { - - // Switch to short timeout if there was an infinite one. - // Note if there's one, it is either short or inifinite. So we - // look at the value only in the hope it is less expensive - // than doing a redundant put. - - PeerID peerID = addr2pid(logDest); - - synchronized (this) { - Long curr = triedAndFailed.get(peerID); - - if (curr != null && curr > TimeUtils.toAbsoluteTimeMillis(MAX_ASYNC_GETMESSENGER_RETRY)) { - triedAndFailed.put(peerID, TimeUtils.toAbsoluteTimeMillis(MAX_ASYNC_GETMESSENGER_RETRY)); - } - } - } - - /** - * Call when an asynchronous new messenger is ready. - * (name is not great). - * - * @param event the new messenger event. - * @return always returns true - */ - boolean newMessenger(MessengerEvent event) { - - Messenger messenger = event.getMessenger(); - EndpointAddress logDest = messenger.getLogicalDestinationAddress(); - - // We learned that a new transport messenger has just been announced. - // We pool it for our exclusive use. - destinations.addOutgoingMessenger(logDest, messenger); - - // Here's a new connection. Wakeup those that may be waiting for that. - synchronized (this) { - notifyAll(); - } - return true; - } - - /** - * Get the routed route, if any, for a given peer id. - * - * @param peerAddress the peer who's route is desired. - * @param seekRoute boolean to indicate if we should search for a route - * if we don't have one - * @return a route advertisement describing the direct route to the peer. - */ - RouteAdvertisement getRoute(EndpointAddress peerAddress, boolean seekRoute) { - - ID peerID = addr2pid(peerAddress); - - // check if we have a valid route - RouteAdvertisement route; - - synchronized (this) { - route = routedRoutes.get(peerID); - } - if (route != null || !seekRoute) { // done - return route; - } - - // No known route and we're allowed to search for one - - // check if there is route advertisement available - Iterator allRadvs = routeCM.getRouteAdv(peerID); - - while (allRadvs.hasNext()) { - route = allRadvs.next(); - Vector hops = route.getVectorHops(); - - // no hops, uninterresting: this needs to be a route - if (hops.isEmpty()) { - continue; - } - - // let's check if we can speak to any of the hops in the route - // we try them in reverse order so we shortcut the route - // in the process - RouteAdvertisement newRoute = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - - newRoute.setDest(route.getDest().clone()); - Vector newHops = new Vector(); - - // build the route from the available hops - for (int i = hops.size() - 1; i >= 0; i--) { - ID hopID = hops.elementAt(i).getPeerID(); - - // If the local peer is one of the first reachable - // hop in the route, that route is worthless to us. - if (localPeerId.equals(hopID)) { - break; - } - - EndpointAddress addr = pid2addr(hopID); - - if (ensureLocalRoute(addr, null) != null) { - // we found a valid hop return the corresponding - // route from that point - for (int j = i; j <= hops.size() - 1; j++) { - newHops.add(hops.elementAt(j).clone()); - } - // make sure we have a real route at the end - if (newHops.isEmpty()) { - break; - } - - newRoute.setHops(newHops); - // try to set the route - if (setRoute(newRoute, false)) { - // We got one; we're done. - return newRoute; - } else { - // For some reason the route table does not - // want that route. Move on to the next adv; it - // unlikely that a longer version of the same would - // be found good. - break; - } - } - } - } - - // no route found - return null; - } - - /** - * Check if a route is valid. - * Currently, only loops are detected. - * - * @param routeAdvertisement The route to check. - * @return {@code true} if the route is valid otherwise {@code false}. - */ - private boolean checkRoute(RouteAdvertisement routeAdvertisement) { - - if (0 == routeAdvertisement.size()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("route is empty"); - } - return false; - } - - if (routeAdvertisement.containsHop(localPeerId)) { - // The route does contain this local peer. Using this route - // would create a loop. Discard. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("route contains this peer - loopback"); - } - return false; - } - - PeerID destPid = routeAdvertisement.getDest().getPeerID(); - - if (routeAdvertisement.containsHop(destPid)) { - // May be it is fixable, may be not. See to it. - Vector hops = routeAdvertisement.getVectorHops(); - - // It better be the last hop. Else this is a broken route. - hops.remove(hops.lastElement()); - if (routeAdvertisement.containsHop(destPid)) { - // There was one other than last: broken route. - return false; - } - } - - if (routeAdvertisement.hasALoop()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("route has a loop "); - } - return false; - } else { - // Seems to be a potential good route. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("route is ok"); - } - return true; - } - } - - // Adds a new long route provided there not a direct one already. - // Replaces any longer route. return true if the route was truely new. - // The whole deal must be synch. We do not want to add a long route - // while a direct one is being added in parallell or other stupid things like that. - - /** - * set new route info - * - * @param route new route to learn - * @param force true if the route was obtained by receiving - * a message - * @return true if route was truly new - */ - boolean setRoute(RouteAdvertisement route, boolean force) { - PeerID peerID; - EndpointAddress peerAddress; - boolean pushNeeded = false; - boolean status; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("setRoute:"); - } - - if (route == null) { - return false; - } - - synchronized (this) { - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(route.display()); - } - peerID = route.getDest().getPeerID(); - peerAddress = pid2addr(peerID); - - // Check if we are in the case where we are - // setting a new route as we received a message - // always force the new route setup when we received a - // a message - if (!force) { - // check if we have some bad NACK route info for - // this destination - BadRoute badRoute = badRoutes.get(peerAddress); - - if (badRoute != null) { - Long nextTry = badRoute.getExpiration(); - - if (nextTry > System.currentTimeMillis()) { - // check if the route we have in the NACK cache match the - // new one. Need to make sure that we clean the route - // from any endpoint addresses as the badRoute cache only - // contains PeerIDs - RouteAdvertisement routeClean = route.cloneOnlyPIDs(); - - if (routeClean.equals(badRoute.getRoute())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("try to use a known bad route"); - } - return false; - } - } else { - // expired info, just flush NACK route cache - badRoutes.remove(peerAddress); - } - } - } else { - // we get a new route - badRoutes.remove(peerAddress); - } - - // Check if the route makes senses (loop detection) - if (!checkRoute(route)) { - // Route is invalid. Drop it. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Route is invalid"); - } - return false; - } - - // check if we can reach the first hop in the route - // We only do a shallow test of the first hop. Whether more effort - // is worth doing or not is decided (and done) by the invoker. - if (!isLocalRoute(pid2addr(route.getFirstHop().getPeerID()))) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unreachable route - ignore"); - } - return false; - } - - } catch (Exception ez1) { - // The vector must be empty, which is not supposed to happen. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Got an empty route - discard" + route.display()); - } - return false; - } - - // add the new route - try { - // push the route to SRDI only if it is a new route. the intent is - // to minimize SRDI traffic. The SRDIinformation is more of the order - // this peer has a route to this destination, it does not need to be - // updated verey time the route is updated. Information about knowing - // that this peer has a route is more important that the precise - // route information - - // SRDI is run only if the peer is acting as a rendezvous - if (group.isRendezvous()) { - if (!routedRoutes.containsKey(peerID)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("push new SRDI route " + peerID); - } - pushNeeded = true; - } - } - - // new route so publish the known route in our cache - if (!routedRoutes.containsKey(peerID)) { - routeCM.createRoute(route); - newDestinations.add(peerAddress); - } - - // Remove any endpoint addresses from the route - // as part of the cloning. We just keep track - // of PIDs in our route table - RouteAdvertisement newRoute = route.cloneOnlyPIDs(); - - routedRoutes.put(peerID, newRoute); - - // We can get rid of any negative info we had. We have - // a new and different route. - badRoutes.remove(peerAddress); - notifyAll(); // Wakeup those waiting for a route. - status = true; - } catch (Exception e2) { - // We failed, leave things as they are. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(" failed setting route with " + e2); - } - status = false; - } - } - // due to the potential high latency of making the - // srdi revolver push we don't want to hold the lock - // on the EndpointRouter object as we may have to - // discover a new route to a rendezvous - if (pushNeeded && status) { - // we are pushing the SRDI entry to a replica peer - routeResolver.pushSrdi(null, peerID); - } - return status; - } - - /** - * This method is used to remove a route - * - * @param peerID route to peerid to be removed - */ - void removeRoute(PeerID peerID) { - boolean needRemove; - - synchronized (this) { - needRemove = false; - if (routedRoutes.containsKey(peerID)) { - if (group.isRendezvous()) { - // Remove the SRDI cache entry from the SRDI cache - needRemove = true; - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("remove SRDI route " + peerID); - } - } - routedRoutes.remove(peerID); - } - } - - // due to the potential high latency of pushing - // the SRDI message we don't want to hold the EndpointRouter - // object lock - if (needRemove) { - // We are trying to flush it from the replica peer - // Note: this is not guarantee to work if the peerview - // is out of sync. The SRDI index will be locally - // repaired as the peerview converge - routeResolver.removeSrdi(null, peerID); - } - } - - /** - * {@inheritDoc} - */ - public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { - EndpointAddress srcPeerAddress; - EndpointAddress destPeer; - EndpointAddress lastHop = null; - boolean connectLastHop = false; - EndpointAddress origSrcAddr; - EndpointAddress origDstAddr; - Vector origHops = null; // original route of the message - EndpointRouterMessage routerMsg; - EndpointAddress nextHop = null; - RouteAdvertisement radv; - - // We do not want the existing header to be ignored of course. - routerMsg = new EndpointRouterMessage(msg, false); - if (!routerMsg.msgExists()) { - // The sender did not use this router - if (Logging.SHOW_FINE && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Discarding " + msg + ". No routing info."); - } - return; - } - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(routerMsg.display()); - } - origSrcAddr = routerMsg.getSrcAddress(); - origDstAddr = routerMsg.getDestAddress(); - - // convert the src and dest addresses into canonical - // form stripping service info - srcPeerAddress = new EndpointAddress(origSrcAddr, null, null); - destPeer = new EndpointAddress(origDstAddr, null, null); - - lastHop = routerMsg.getLastHop(); - - // See if there's an originator full route adv inthere. - // That's a good thing to keep. - radv = routerMsg.getRouteAdv(); - if (radv != null) { - - // publish the full route adv. Also, leave it the - // message. It turns out to be extremely usefull to - // peers downstream, specially the destination. If - // this here peer wants to embed his own radv, it will - // have to wait; the one in the message may not come - // again. - - // FIXME - jice@jxta.org 20040413 : all this could wait (couldn't it ?) - // until we know it's needed, therefore parsing could wait as well. - - // Looks like a safe bet to try and ensure a - // connection in the opposite direction if there - // isn't one already. - - if (pid2addr(radv.getDestPeerID()).equals(lastHop)) { - connectLastHop = true; - } - - // Make the most of that new adv. - setRoute(radv, true); - updateRouteAdv(radv); - } - } catch (Exception badHdr) { - // Drop it, we do not even know the destination - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Bad routing header or bad message. Dropping " + msg); - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Exception: ", badHdr); - } - return; - } - - // Is this a loopback ? - if ((srcPeerAddress != null) && srcPeerAddress.equals(localPeerAddr)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("dropped loopback"); - } - return; - } - - // Are we already sending to ourself. This may occur - // if some old advertisements for our EA is still - // floating around - if ((lastHop != null) && lastHop.equals(localPeerAddr)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("dropped loopback from impersonating Peer"); - } - return; - } - - // We have to try and reciprocate the connection, so that we - // have chance to learn reverse routes early enough. If we do - // not already have a messenger, then we must know a route adv - // for that peer in order to be able to connect. Otherwise, - // the attempt will fail and we'll be left with a negative - // entry without having realy tried anything. To prevent that - // we rely on the presence of a radv in the router message. If - // there's no radv, two possibilities: - // - // - It is not the first contact from that peer and we already - // have tried (with or without success) to reciprocate. - // - // - It is the first contact from that peer but it has not - // embedded its radv. In the most likely case (an edge peer - // connecting to a rdv), the edge peer will have no difficulty - // finding the reverse route, provided that we do not make a - // failed attempt right now. - // - // Conclusion: if there's no embedded radv in the message, do - // nothing. - - if (connectLastHop) { - ensureLocalRoute(lastHop, radv); - } - - try { - - // Normalize the reverseHops vector from the message and, if it - // looks well formed and usefull, learn from it. Do we have a - // direct route to the origin ? If yes, we'll zap the revers - // route in the message: we're a much better router. else, - // learn from it. As a principle we regard given routes to be - // better than existing ones. - Vector reverseHops = routerMsg.getReverseHops(); - - if (reverseHops == null) { - reverseHops = new Vector(); - } - - // check if we do not have a direct route - // in that case we don't care to learn thelong route - if (!isLocalRoute(srcPeerAddress)) { - // Check if the reverseRoute info looks correct. - if (lastHop != null) { - // since we are putting the lasthop in the - // reverse route to indicate the validity of - // lastop to reach the previous hop, we have - // the complete route, just clone it. (newRoute - // owns the given vector) - - if ((reverseHops.size() > 0) && reverseHops.firstElement().getPeerID().equals(addr2pid(lastHop))) { - - // Looks like a good route to learn - setRoute(RouteAdvertisement.newRoute(addr2pid(srcPeerAddress), null, (Vector) reverseHops.clone()), true); - - } - - } - } - - // If this peer is the final destination, then we're done. Just let - // it be pushed up the stack. We must not leave our header; - // it is now meaningless and none of the upper layers business. - // All we have to do is to supply the end-2-end src and dest - // so that the endpoint demux routine can do its job. - if (destPeer.equals(localPeerAddr)) { - // Removing the header. - routerMsg.clearAll(); - routerMsg.updateMessage(); - // receive locally - endpoint.processIncomingMessage(msg, origSrcAddr, origDstAddr); - return; - } - - // WATCHOUT: if this peer is part of the reverse route - // it means that we've seen that message already: there's - // a loop between routers ! If that happens drop that - // message as if it was burning our fingers - - // First build the ap that we might add to the reverse route. - // We need it to look for ourselves in reverseHops. (contains - // uses equals(). equals will work because we always include - // in reversehops aps that have only a peerAddress. - - AccessPointAdvertisement selfAp = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - selfAp.setPeerID(localPeerId); - - if (reverseHops.contains(selfAp)) { - - // Danger, bail out ! - // Better not to try to NACK for now, but get rid of our own - // route. If we're sollicited again, there won't be a loop - // and we may NACK. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Routing loop detected. Message dropped"); - } - removeRoute(addr2pid(destPeer)); - return; - } - - // Update reverseHops. That is, add ourselves to the list. - - // We will only add the current hop to the reverse - // route if we know how to talk back to the previous hop - // it is important to point the difference between the lastHop - // and the reverse route entry. The lastHop indicates where the - // message came from but does not specify whether it is able to - // route messages in the other direction. The reverse route, if - // present, provides that information. - - // FIXME - jice@jxta.org 20040413 : HERE comes the use of connectLastHop. Could have waited till here. - - if (isLocalRoute(lastHop)) { // ok we have direct route back, at least we hope :-) - reverseHops.add(0, selfAp); // Update our vector - routerMsg.prependReverseHop(selfAp); // Update the message, this preserves the cache. - } else { - - // We cannot talk to our previous hop, well - // check if we have route to the src and use it as - // our reverse route. We could do more. But let's keep - // it to the minimum at this point. - RouteAdvertisement newReverseRoute = routedRoutes.get(addr2pid(srcPeerAddress)); - - if (newReverseRoute != null) { - // we found a new route back from our cache so let's use it - reverseHops = (Vector) newReverseRoute.getVectorHops().clone(); - // ok add ourselve to the reverse route - reverseHops.add(0, selfAp); - } else { - // no new route found, sorry. In the worst - // case it is better to not have reverse route - reverseHops = null; - } - - // In both cases above, we replace the hops completely. - // The cache is of no use and is lost. - routerMsg.setReverseHops(reverseHops); - } - - // Get the next peer into the forward route - origHops = routerMsg.getForwardHops(); - if (origHops != null) { - nextHop = getNextHop(origHops); - } - - // see if we can shortcut to the destination with no effort. - // If that works it's all very easy. - if (isLocalRoute(destPeer)) { - - // There is a local route - use it - // Clear the forward path which is probably wrong - routerMsg.setForwardHops(null); - nextHop = destPeer; - } else { - if (nextHop == null) { - - // No next hop. Use the destPeer instead. (but, unlike when - // we shortcut it deliberately, don't know if we can have a direct route - // yet). This is perfectly normal if we're just the last - // hop before the destination and we have closed the direct connection - // with it since we declared to be a router to it. - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No next hop in forward route - Using destination as next hop"); - } - nextHop = destPeer; - - // That forward path is exhausted. It will not be usefull anymore. - // either we reach the destination directly and there will be - // no need for a NACK further down, or we will need to find an alternate - // route. - routerMsg.setForwardHops(null); - } - - // We must be do better than look passively for a direct - // route. The negative cache will take care of reducing the - // implied load. If we do not, then we never re-establish - // a broken local route until the originating peer seeks a - // new route. Then the result is roughly the same plus - // the overhead of route seeking...worse, if we're in the - // path from the originator to it's only rdv, then the - // originator does not stand a chance until it re-seeds ! - - if (ensureLocalRoute(nextHop, null) == null) { - - // need to look for a long route. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Forward route element broken - trying alternate route"); - } - - // While we're at it, we might as well get rid of our own - // route to the destination if it goes through the same hop - // by any chance. - // FIXME: idealy, each time we get a broken local route - // we'd want to get rid of all routes that start from there - // but that's one more map to maintain. - - RouteAdvertisement route = getRoute(destPeer, false); - - if (route == null) { - cantRoute("No new route to repair the route - drop message", null, origSrcAddr, destPeer, origHops); - return; - } - - if (pid2addr(route.getFirstHop().getPeerID()).equals(nextHop)) { - // Our own route is just as rotten as the sender's. Get rid - // of it. - removeRoute(addr2pid(destPeer)); - cantRoute("No better route to repair the route - drop message", null, origSrcAddr, destPeer, origHops); - return; - } - - // optimization to see if we can reach - // directly the last hop of that route - EndpointAddress addr = pid2addr(route.getLastHop().getPeerID()); - - if (isLocalRoute(addr)) { - // FIXME - jice@jxta.org 20030723. Should update our route table to reflect the shortcut. - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Found new remote route via : " + addr); - } - - // set the forward path to null no next hop - // FIXME: Not true. the last hop is not the destination. - // There could be a need for us receiving a NACK and that won't be - // possible. We should leave the next hop in the fw path. Just like - // we do when forwarding along the existing route. - - routerMsg.setForwardHops(null); - } else { // need to check the first hop - Vector newHops = (Vector) route.getVectorHops().clone(); - - // FIXME: remove(0) seems wrong - // There could be a need for us receiving a NACK and that won't be - // possible. We should leave the next hop in the fw path. Just like - // we do when forwarding along the existing route. - addr = pid2addr(newHops.remove(0).getPeerID()); - if (!isLocalRoute(addr)) { - // Our own route is provably rotten - // as well. Get rid of it. - removeRoute(addr2pid(destPeer)); - cantRoute("No usable route to repair the route - drop message", null, origSrcAddr, destPeer, origHops); - return; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Found new remote route via : " + addr); - } - - // NB: setForwardHops does not clone. - routerMsg.setForwardHops(newHops); - } - // If we're here. addr is our new nextHop. - nextHop = addr; - } - } - - // The first time we talk to a peer to which we have - // initiated a connection, we must include our local - // route adv in the routerMsg. However, we give priority to - // a route adv that's already in the message and which we pass along. - // In that case, our own will go next time. Note: we care only for - // nextHop, not for the final destination. We give our radv to a far - // destination only if we originate a message to it; not when forwarding. - // JC: give priority to our own radv instead. It can be critical. - - // 20040301 tra: May be the case we haven't yet initialize our - // own local route. For example still waiting for our relay connection - RouteAdvertisement myRoute = getMyLocalRoute(); - - if ((myRoute != null) && destinations.isWelcomeNeeded(nextHop)) { - routerMsg.setRouteAdv(myRoute); - } - - // We always modify the router message within the message - routerMsg.setLastHop(localPeerAddr); - routerMsg.updateMessage(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Trying to forward to " + nextHop); - } - - sendOnLocalRoute(nextHop, msg); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Successfully forwarded to " + nextHop); - } - } catch (Exception e) { - cantRoute("Failed to deliver or forward message for " + destPeer, e, origSrcAddr, destPeer, origHops); - } - } - - private void cantRoute(String logMsg, Exception exception, EndpointAddress origSrcAddr, EndpointAddress destPeer, Vector origHops) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - if (exception == null) { - LOG.warning(logMsg); - } else { - LOG.log(Level.WARNING, logMsg, exception); - } - } - routeResolver.generateNACKRoute(addr2pid(origSrcAddr), addr2pid(destPeer), origHops); - } - - /** - * Return the address of the next hop in this vector - * - * @param hops of forward hops in the route - * @return next hop to be used - */ - private EndpointAddress getNextHop(Vector hops) { - // check if we have a real route - if ((hops == null) || (hops.size() == 0)) { - return null; - } - - // find the next hop. - for (Enumeration e = hops.elements(); e.hasMoreElements();) { - AccessPointAdvertisement ap = (AccessPointAdvertisement) e.nextElement(); - - if (localPeerId.equals(ap.getPeerID())) { - - // If found at the end, no next hop - if (!e.hasMoreElements()) { - return null; - } - return pid2addr(((AccessPointAdvertisement) e.nextElement()).getPeerID()); - } - } - - // The peer is not into the vector. Since we have got that - // message, the best we can do is to send it to the first gateway - // in the forward path. - return pid2addr(((AccessPointAdvertisement) hops.elementAt(0)).getPeerID()); - } - - /** - * lame hard-coding - * - * @param p message transport - * @return true if fast - */ - private boolean isFast(MessageTransport p) { - String name = p.getProtocolName(); - - return name.equals("tcp") || name.equals("beep"); - } - - private boolean isRelay(MessageTransport p) { - String name = p.getProtocolName(); - - return name.equals("relay"); - } - - /** - * Given a list of addresses, find the best reachable endpoint. - *

            - *

              - *
            • The address returned must be reachable.
            • - *
            • We prefer an address whose protocol is, in order:
            • - *
                - *
              1. connected and fast.
              2. - *
              3. connected and slow.
              4. - *
              5. unconnected and fast.
              6. - *
              7. unconnected and slow
              8. - *
              - *
            - * - * @param dest destination address. - * @param mightWork A list of addresses to evaluate reachability. - * @param exist true if there already are existing messengers for - * the given destinations but we want one more. It may lead us to reject - * certain addresses that we would otherwise accept. - * @return The endpoint address for which we found a local route otherwise - * null - */ - Messenger findBestReachableEndpoint(EndpointAddress dest, List mightWork, boolean exist) { - - List rankings = new ArrayList(mightWork.size()); - List worthTrying = new ArrayList(mightWork.size()); - - // First rank the available addresses by type rejecting those which - // cant be used. - - for (Object aMightWork : mightWork) { - EndpointAddress addr = (EndpointAddress) aMightWork; - - // skip our own type - if (getProtocolName().equals(addr.getProtocolName())) { - continue; - } - int rank = -1; - Iterator eachTransport = endpoint.getAllMessageTransports(); - - while (eachTransport.hasNext()) { - MessageTransport transpt = eachTransport.next(); - - if (!transpt.getProtocolName().equals(addr.getProtocolName())) { - continue; - } - - // must be a sender - if (!(transpt instanceof MessageSender)) { - continue; - } - - MessageSender sender = (MessageSender) transpt; - - // must allow routing - if (!sender.allowsRouting()) { - // This protocol should not be used for routing. - continue; - } - rank += 1; - if (sender.isConnectionOriented()) { - rank += 2; - } - - if (isRelay(transpt)) { - // That should prevent the relay for ever being used - // when the relay may be sending through the router. - if (exist) { - rank -= 1000; - } - } - if (isFast(transpt)) { - rank += 4; - } - } - - // if its worth trying then insert it into the rankings. - if (rank >= 0) { - for (int eachCurrent = 0; eachCurrent <= rankings.size(); eachCurrent++) { - if (rankings.size() == eachCurrent) { - rankings.add(rank); - worthTrying.add(addr); - break; - } - if (rank > rankings.get(eachCurrent)) { - rankings.add(eachCurrent, rank); - worthTrying.add(eachCurrent, addr); - break; - } - } - } - } - - // now that we have them ranked, go through them until we get a - // successful messenger. - rankings = null; - - for (EndpointAddress addr : worthTrying) { - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Trying : " + addr); - } - // We use an async getMessenger as we do not - // want to wait too long to obtain our messenger - // We will still wait ASYNCMESSENGER_WAIT to see - // if we can get the messenger before bailing out - - // Create the listener object for that request - EndpointGetMessengerAsyncListener getMessengerListener = new EndpointGetMessengerAsyncListener(this, dest); - boolean stat = endpoint.getMessenger(getMessengerListener, new EndpointAddress(addr, ROUTER_SERVICE_NAME, null) - , - null); - - if (!stat) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Failed to create async messenger to : " + addr); - } - // we failed to get a messenger, we need to update the try and - // failed as it currently holds an infinite timeout to permit - // another thread to retry that destination. We only retry - // every MAX_ASYNC_GETMESSENGER_RETRY seconds - synchronized (this) { - triedAndFailed.put(addr2pid(dest), TimeUtils.toAbsoluteTimeMillis(MAX_ASYNC_GETMESSENGER_RETRY)); - } - continue; - } - - // wait to see if we can get the Async messenger - // If there is a long route to that destination, do not - // wait on the direct route. - // It may happen that we are actually - // trying to reach a different peer and this is just part of - // shortcuting the route via the one of the hops. In that case - // this test is not entirely accurate. We might still decide - // to wait when we shouldn't (we're no worse than before, then) - // But, in most cases, this is going to help. - boolean quick = (getRoute(dest, false) != null); - Messenger messenger = getMessengerListener.waitForMessenger(quick); - - if (messenger == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("did not get our async messenger. continue"); - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("we got our async messenger, proceed"); - } - // Success we got a messenger synchronously. Remove - // the negative cache entry. - synchronized (this) { - triedAndFailed.remove(addr2pid(dest)); - notifyAll(); - } - return messenger; - } - } catch (RuntimeException e) { - // That address is somehow broken. - // Cache that result for a while. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "failed checking route", e); - } - } - } - return null; - } - - /** - * Read the route advertisement for a peer and find a suitable transport - * endpoint for sending to that peer either directly or via one of - * the advertised peer router - * - * @param destPeerAddress dest address - * @param exist use existing messengers, avoid creating a new one - * @param hint route hint - * @return a reachable messenger - */ - Messenger findReachableEndpoint(EndpointAddress destPeerAddress, boolean exist, RouteAdvertisement hint) { - - PeerID destPeerID = addr2pid(destPeerAddress); - - // findReachableEndpoint is really lazy because what it does is expensive. - // When needed, the negative info that prevents its from working - // too much is removed. (see calls to ensureLocalRoute). - synchronized (this) { - Long nextTry = triedAndFailed.get(destPeerID); - - if (nextTry != null) { - if (nextTry > TimeUtils.timeNow()) { - return null; - } - } - - // We are the first thread trying this destination. Let's preclude - // any other threads from attempting to do anything while we are - // trying that destination. Other threads will have a chance if they - // are still waiting when this thread is done. We will update - // triedAndFailed when we get the async notification that we got or - // we failed to get a messenger. - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Temporarly adding " + destPeerAddress.toString() + " to triedAndFailed, while attempting connection"); - } - triedAndFailed.put(destPeerID, TimeUtils.toAbsoluteTimeMillis(Long.MAX_VALUE)); - } - - // Never tried or it was a long time ago. - // Get (locally) the advertisements of this peer - Iterator advs; - - try { - // try to use the hint that was given to us - if (hint != null) { - advs = Collections.singletonList(hint).iterator(); - } else { - // Ok extract from the CM - advs = routeCM.getRouteAdv(destPeerID); - } - - // Check if we got any advertisements - List addrs = new ArrayList(); - - while (advs.hasNext()) { - RouteAdvertisement adv = advs.next(); - - String saddr = null; - - // add the destination endpoint - for (Enumeration e = adv.getDest().getEndpointAddresses(); e.hasMoreElements();) { - try { - saddr = e.nextElement(); - addrs.add(new EndpointAddress(saddr)); - } catch (Throwable ex) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(" bad address in route adv : " + saddr); - } - } - } - } - - // ok let's go and try all these addresses - if (!addrs.isEmpty()) { - Messenger bestMessenger = findBestReachableEndpoint(destPeerAddress, addrs, exist); - - if (bestMessenger != null) { - // Found a direct route. Return it. - // Tried+failed has been cleaned. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("found direct route"); - } - return bestMessenger; - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("findReachableEndpoint : Failed due to empty address list"); - } - } - } catch (RuntimeException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure looking for an address ", e); - } - } - - // We're done trying. Since we did not find anything at all (or failed, - // during the atempt) the triedFailed record is still set to infinite - // value. Reset it to finite. - // There is a small chance that another thread did find - // something in parallel, but that's very unlikely and - // if it is rare enough then the damage is small. - synchronized (this) { - triedAndFailed.put(destPeerID, TimeUtils.toAbsoluteTimeMillis(MAX_ASYNC_GETMESSENGER_RETRY)); - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("did not find a direct route to :" + destPeerAddress); - } - return null; - } - - /** - * {@inheritDoc} - */ - public Messenger getMessenger(EndpointAddress addr, Object hint) { - RouteAdvertisement routeHint = null; - EndpointAddress plainAddr = new EndpointAddress(addr, null, null); - - // If the dest is the local peer, just loop it back without going - // through the router. - if (plainAddr.equals(localPeerAddr)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("return LoopbackMessenger"); - } - return new LoopbackMessenger(group, endpoint, localPeerAddr, addr, addr); - } - - try { - // try and add that hint to our cache of routes (that may be our only route). - if (hint != null && hint instanceof RouteAdvertisement) { - routeHint = ((RouteAdvertisement) hint).clone(); - AccessPointAdvertisement firstHop = routeHint.getFirstHop(); - PeerID firstHopPid; - EndpointAddress firstHopAddr = null; - - // If the firstHop is equal to the destination, clean that up, - // that's a direct route. If the first hop is the local peer - // leave it there but treat it as a local route. That's what - // it is from the local peer point of view. - if (firstHop != null) { - - firstHopPid = firstHop.getPeerID(); - firstHopAddr = pid2addr(firstHopPid); - - if (firstHopAddr.equals(addr)) { - routeHint.removeHop(firstHopPid); - firstHop = null; - } else if (firstHopPid.equals(localPeerId)) { - firstHop = null; - } - - } - - if (firstHop == null) { - // The hint is a direct route. Make sure that we have the - // route adv so that we can actually connect. - - // we only need to publish this route if we don't know about - // it yet. - EndpointAddress da = pid2addr(routeHint.getDestPeerID()); - - if (!isLocalRoute(da) && !routedRoutes.containsKey(routeHint.getDestPeerID())) { - routeCM.publishRoute(routeHint); - } - - } else { - // For the hint to be useful, we must actively try the first - // hop. It is possible that we do not know it yet and that's - // not a reason to ignore the hint (would ruin the purpose - // in most cases). - RouteAdvertisement routeFirstHop = null; - - // Manufacture a RA just that as just the routerPeer as a - // destination. We only need to publish this route if we - // don't know about it yet. - if (!isLocalRoute(firstHopAddr) && !routedRoutes.containsKey(firstHop.getPeerID())) { - - routeFirstHop = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - routeFirstHop.setDest(firstHop.clone()); - - // Here we used to pass a second argument with value - // true which forced updateRouteAdv to ignore a - // pre-existing identical adv and remove negative cache - // information anyway. The reason for doing that was - // that sometimes the new route adv does already exist - // but has not yet been tried. We cannot do that; it - // exposes us too much to retrying incessantly the same - // address. A hint cannot be trusted to such an extent. - // The correct remedy is to be able to tell accurately - // if there really is an untried address in that radv, - // which requires a sizeable refactoring. in the - // meantime just let the negative cache play its role. - updateRouteAdv(routeFirstHop); - } - - // if we constructed the route hint then passes it in the - // past we were just relying on the CM now that the CM can - // be disabled, we have to pass the argument. - if (ensureLocalRoute(firstHopAddr, routeFirstHop) != null) { - setRoute(routeHint.clone(), false); - } - } - } - - } catch (Throwable ioe) { - // Enforce a stronger semantic to hint. If the application passes - // a hint that is rotten then this is an application problem - // we should not try to fix what was given to us. - return null; - } - - try { - // Build a persistent RouterMessenger around it that will add our - // header. If a hint was passed to us we just use it as it. Too bad - // if it is not the the right one. In that mode it is the - // responsibility of the application to make sure that a correct - // hint was passed. - return new RouterMessenger(addr, this, routeHint); - } catch (IOException caught) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Can\'t generate messenger for addr " + addr, caught); - } - return null; - } - } - - /** - * Updates the router element of a message and returns the peerAddress address of - * the next hop (where to send the message). - *

            - * Currently, address message is only called for messages that we - * originate. As a result we will always aggressively seek a route if needed. - * - * @param message the message for which to compute/update a route. - * @param dstAddress the final destination of the route which the message be set to follow. - * @return EndpointAddress The address (logical) where to send the message next. Null if there - * is nowhere to send it to. - */ - EndpointAddress addressMessage(Message message, EndpointAddress dstAddress) { - if (endpoint == null) { - return null; - } - - // We need to create a RouterMessage - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Create a new EndpointRouterMessage " + dstAddress); - } - - // Specify that we do not want an existing msg parsed. - EndpointRouterMessage routerMsg = new EndpointRouterMessage(message, true); - - if (routerMsg.isDirty()) { - // Oops there was one in the message already. This must be a - // low-level protocol looping back through the router. The relay can - // be led to do that in some corner cases. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Probable transport recursion"); - } - throw new IllegalStateException("RouterMessage element already present"); - } - - routerMsg.setSrcAddress(localPeerAddr); - routerMsg.setDestAddress(dstAddress); - - EndpointAddress theGatewayAddress; - EndpointAddress dstAddressPlain = new EndpointAddress(dstAddress, null, null); - - try { - RouteAdvertisement route = null; - - theGatewayAddress = getGatewayAddress(dstAddressPlain, true, null); - - if (theGatewayAddress == null) { - // Cleanup the message, so that the invoker - // may retry (with a different hint, for example). - routerMsg.clearAll(); - routerMsg.updateMessage(); - return null; - } - - // Check that we're actually going through a route; we could have one - // but not be using it, because we know of a volatile shortcut. - - // FIXME: jice@jxta.org - 20030512: This is not very clean: - // getGatewayAddress should be giving us the route that it's using, if any. - // By doing the fetch ourselves, not only do we waste CPU hashing - // twice, but we could also get a different route ! - - if (!theGatewayAddress.equals(dstAddressPlain)) { - route = getRoute(dstAddressPlain, false); - } - - // If we're going through a route for that, stuff it in the - // message. NB: setForwardHops does not clone. - if (route != null) { - routerMsg.setForwardHops((Vector) route.getVectorHops().clone()); - } - - // set the last hop info to point to the local peer info - // The recipient takes last hop to be the last peer that the message has traversed - // before arriving. - routerMsg.setLastHop(localPeerAddr); - - // The first time we talk to a peer to which we have - // initiated a connection, we must include our local - // route adv in the routerMsg. - RouteAdvertisement myRoute = getMyLocalRoute(); - - if (myRoute != null) { - // FIXME - jice@jxta.org 20040430 : use destinations instead of newDestinations, even for routed ones. - boolean newDest = newDestinations.remove(dstAddressPlain); - boolean newGatw = destinations.isWelcomeNeeded(theGatewayAddress); - - if (newDest || newGatw) { - routerMsg.setRouteAdv(myRoute); - } - } - - // Push the router header onto the message. - // That's all we have to do for now. - - routerMsg.updateMessage(); - } catch (Exception ez1) { - // Not much we can do - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not fully address message", ez1); - } - return null; - } - - return theGatewayAddress; - } - - /** - * {@inheritDoc} - */ - public Object transportControl(Object operation, Object value) { - if (!(operation instanceof Integer)) { - return null; - } - - int op = (Integer) operation; - - switch (op) { - case RouteControlOp: // Get a Router Control Object - return new RouteControl(this, localPeerId); - - default: - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Invalid Transport Control operation argument"); - } - - return null; - } - } - - /** - * Convert a Router EndpointAddress into a PeerID - * - * @param addr the address to extract peerAddress from - * @return the PeerID - */ - static PeerID addr2pid(EndpointAddress addr) { - URI asURI = null; - - try { - asURI = new URI(ID.URIEncodingName, ID.URNNamespace + ":" + addr.getProtocolAddress(), null); - return (PeerID) IDFactory.fromURI(asURI); - } catch (URISyntaxException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Error converting a source address into a virtual address : " + addr, ex); - } - } catch (ClassCastException cce) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Error converting a source address into a virtual address: " + addr, cce); - } - } - - return null; - } - - /** - * Convert an ID into a Router Endpoint Address - * - * @param pid The ID who's equivalent Endpoint Address is desired. - * @return The ID as an EndpointAddress. - */ - static EndpointAddress pid2addr(ID pid) { - return new EndpointAddress(ROUTER_PROTOCOL_NAME, pid.getUniqueValue().toString(), null, null); - } - - /** - * check if it is a new route adv - * - * @param route route advertisement - */ - void updateRouteAdv(RouteAdvertisement route) { - updateRouteAdv(route, false); - } - - /** - * check if it is a new route adv - * - * @param route route advertisement - * @param force enforce the route - */ - void updateRouteAdv(RouteAdvertisement route, boolean force) { - try { - PeerID pID = route.getDestPeerID(); - - // check if we updated the route - if (routeCM.updateRoute(route)) { - // We just dumped an adv for that dest, so we want to do a real check - // on its new addresses. Remove the entry from the negative cache. - synchronized (this) { - Long nextTry = triedAndFailed.get(pID); - - if (nextTry != null) { - // only remove if we do not have a pending request (infinite retry) - // we take the conservative approach to avoid creating multiple - // async thread blocked on the same destination - if (nextTry <= TimeUtils.toAbsoluteTimeMillis(MAX_ASYNC_GETMESSENGER_RETRY)) { - triedAndFailed.remove(pID); - notifyAll(); - } - } - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Route for " + pID + " is same as existing route, not publishing it"); - } - - if (force) { - synchronized (this) { - Long nextTry = triedAndFailed.get(pID); - - if (nextTry != null) { - // only remove if we do not have a pending request (infinite retry) - // we take the conservative approach to avoid creating multiple - // async thread blocked on the same destination - if (nextTry <= TimeUtils.toAbsoluteTimeMillis(MAX_ASYNC_GETMESSENGER_RETRY)) { - triedAndFailed.remove(pID); - notifyAll(); - } - } - } - } - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to publish route advertisement", e); - } - } - } - - /** - * is there a pending route query for that destination - * - * @param peerID destination address - * @return true or false - */ - boolean isPendingRouteQuery(PeerID peerID) { - return pendingQueries.containsKey(peerID); - } - - /** - * get a pending route query info - * - * @param peerID destination address - * @return pending route query info - */ - ClearPendingQuery getPendingRouteQuery(PeerID peerID) { - return pendingQueries.get(peerID); - } - - /** - * Do we have a long route for that destination - * - * @param peerID destination address - * @return true or false - */ - boolean isRoutedRoute(PeerID peerID) { - return peerID != null && routedRoutes.containsKey(peerID); - } - - /** - * Snoop if we have a messenger - * - * @param addr destination address - * @return Messenger - */ - Messenger getCachedMessenger(EndpointAddress addr) { - return destinations.getCurrentMessenger(addr); - } - - /** - * Get all direct route destinations - * - * @return Iterator iterations of all endpoint destinations - */ - Iterator getAllCachedMessengerDestinations() { - return destinations.allDestinations().iterator(); - } - - /** - * Get all long route destinations - * - * @return Iterator iterations of all routed route destinations - */ - Iterator> getRoutedRouteAllDestinations() { - return routedRoutes.entrySet().iterator(); - } - - /** - * Get all long route destination addresses - * - * @return Iterator iterations of all routed route addresses - */ - Iterator getAllRoutedRouteAddresses() { - return routedRoutes.keySet().iterator(); - } - - /** - * Get all pendingRouteQuery destinations - * - * @return All pending route query destinations - */ - Collection> getPendingQueriesAllDestinations() { - List> copy = new ArrayList>( - pendingQueries.size()); - - synchronized (pendingQueries) { - copy.addAll(pendingQueries.entrySet()); - } - - return copy; - } - - /** - * Get the route CM cache Manager - * - * @return the route CM cache Manager - */ - RouteCM getRouteCM() { - return routeCM; - } - - /** - * Get the route resolver manager - * - * @return the route resolver Manager - */ - RouteResolver getRouteResolver() { - return routeResolver; - } - - /** - * set bad route entry - * - * @param addr of the bad route - * @param badRoute bad route info - */ - synchronized void setBadRoute(EndpointAddress addr, BadRoute badRoute) { - badRoutes.put(addr, badRoute); - } - - /** - * get bad route entry - * - * @param addr of the bad route - * @return BadRoute bad route info - */ - synchronized BadRoute getBadRoute(EndpointAddress addr) { - return badRoutes.get(addr); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/EndpointRouterMessage.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/EndpointRouterMessage.java deleted file mode 100644 index febf54e4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/EndpointRouterMessage.java +++ /dev/null @@ -1,512 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.router; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.protocol.AccessPointAdvertisement; -import net.jxta.protocol.RouteAdvertisement; -import net.jxta.logging.Logging; - -import java.util.Enumeration; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Router Message element. This element is added to every message to carry route - * information for the EndpointRouter service. - */ -public class EndpointRouterMessage { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(EndpointRouterMessage.class.getName()); - - public static final String MESSAGE_NS = "jxta"; - public static final String MESSAGE_NAME = "EndpointRouterMsg"; - public static final String Name = "jxta:ERM"; - - public static final String SrcTag = "Src"; - public static final String DestTag = "Dest"; - public static final String LastHopTag = "Last"; - public static final String GatewayForwardTag = "Fwd"; - public static final String GatewayReverseTag = "Rvs"; - - private EndpointAddress srcAddress = null; // PeerID-based EndpointAddress - private EndpointAddress destAddress = null; // PeerID-based EndpointAddress - private EndpointAddress lastHop = null; // Plain PeerID - - private transient Vector forwardGateways = null; - private transient Vector forwardCache = null; - private transient Vector reverseGateways = null; - private transient Vector reverseCache = null; - private transient RouteAdvertisement radv = null; - - // A flag that represents the existence of data. Which is - // different from all fields being empty. - private transient boolean rmExists = false; - - // A flag that tells us that the message is not uptodate compared to - // This object. - private transient boolean rmDirty = false; - - // Keep tied to one and only one message. - private final transient Message message; - - // Cache the element. At the minimum it simplifies removal. - private transient MessageElement rmElem = null; - - public boolean msgExists() { - return rmExists; - } - - public boolean isDirty() { - return rmDirty; - } - - public EndpointRouterMessage(Message message, boolean removeMsg) { - - this.message = message; - - try { - rmElem = message.getMessageElement(MESSAGE_NS, MESSAGE_NAME); - if (rmElem == null) { - return; - } - - // We have an element, but until we read it, no data to - // match (rmExists == false). If the data cannot be read - // from the element, the element is scheduled for removal. - rmDirty = true; - - // If we have been instructed so, do not parse any existing - // element, and leave it marked for removal from the message - // as if it were invalid. - if (removeMsg) { - return; - } - - XMLDocument doc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(rmElem); - - Enumeration each; - XMLElement e; - - each = doc.getChildren(); - if (!each.hasMoreElements()) { - // results in rmExists being false. - return; - } - - while (each.hasMoreElements()) { - try { - e = each.nextElement(); - - if (e.getName().equals(SrcTag)) { - srcAddress = new EndpointAddress(e.getTextValue()); - continue; - } - - if (e.getName().equals(DestTag)) { - destAddress = new EndpointAddress(e.getTextValue()); - continue; - } - - if (e.getName().equals(LastHopTag)) { - lastHop = new EndpointAddress(e.getTextValue()); - continue; - } - - if (e.getName().equals(GatewayForwardTag)) { - for (Enumeration eachXpt = e.getChildren(); eachXpt.hasMoreElements();) { - - if (forwardGateways == null) { - forwardGateways = new Vector(); - } - if (forwardCache == null) { - forwardCache = new Vector(); - } - XMLElement aXpt = eachXpt.nextElement(); - AccessPointAdvertisement xptAdv = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(aXpt); - - forwardGateways.addElement(xptAdv); - // Save the original element - forwardCache.addElement(aXpt); - } - continue; - } - - if (e.getName().equals(GatewayReverseTag)) { - for (Enumeration eachXpt = e.getChildren(); eachXpt.hasMoreElements();) { - if (reverseGateways == null) { - reverseGateways = new Vector(); - } - if (reverseCache == null) { - reverseCache = new Vector(); - } - XMLElement aXpt = eachXpt.nextElement(); - AccessPointAdvertisement xptAdv = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(aXpt); - - reverseGateways.addElement(xptAdv); - // Save the original element - reverseCache.addElement(aXpt); - } - continue; - } - - if (e.getName().equals(RouteAdvertisement.getAdvertisementType())) { - radv = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(e); - } - } catch (Exception ee) { - // keep going - } - } - - // XXX 20040929 bondolo Should be doing validation here. - - // All parsed ok, we're in sync. - rmExists = true; - rmDirty = false; - } catch (Exception eee) { - // give up. The dirty flag will get the element removed - // from the message (if there was one) and we'll report - // there was none. - } - } - - public void updateMessage() { - - if (!rmDirty) { - return; - } - - if (!rmExists) { - - // The change was to remove it. - // If there was an rmElem, remove it and make sure to remove - // all of them. We may have found one initialy but there may be - // several. (just a sanity check for outgoing messages). - - while (rmElem != null) { - message.removeMessageElement(MESSAGE_NS, rmElem); - rmElem = message.getMessageElement(MESSAGE_NS, MESSAGE_NAME); - } - - rmDirty = false; - return; - } - - // The element was either created or changed. Replace whatever - // if anything was in the message - - XMLDocument doc = (XMLDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, Name); - - doc.addAttribute("xmlns:jxta", "http://jxta.org"); - doc.addAttribute("xml:space", "preserve"); - - XMLElement e; - - if (srcAddress != null) { - e = doc.createElement(SrcTag, srcAddress.toString()); - doc.appendChild(e); - } - - if (destAddress != null) { - e = doc.createElement(DestTag, destAddress.toString()); - doc.appendChild(e); - } - - if (lastHop != null) { - e = doc.createElement(LastHopTag, lastHop.toString()); - doc.appendChild(e); - } - - e = doc.createElement(GatewayForwardTag); - doc.appendChild(e); - if ((forwardGateways != null) && (!forwardGateways.isEmpty())) { - if (forwardCache != null) { - for (XMLElement xptDoc : forwardCache) { - try { - StructuredDocumentUtils.copyElements(doc, e, xptDoc); - } catch (Exception e1) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Forward cache failed"); - } - forwardCache = null; - break; - } - } - } else { - for (AccessPointAdvertisement gateway : forwardGateways) { - try { - XMLDocument xptDoc = (XMLDocument) gateway.getDocument(MimeMediaType.XMLUTF8); - StructuredDocumentUtils.copyElements(doc, e, xptDoc); - } catch (Exception ignored) { - //ignored - } - } - } - } - - e = doc.createElement(GatewayReverseTag); - doc.appendChild(e); - if ((reverseGateways != null) && (!reverseGateways.isEmpty())) { - if (reverseCache != null) { - for (XMLElement xptDoc : reverseCache) { - try { - StructuredDocumentUtils.copyElements(doc, e, xptDoc); - } catch (Exception e1) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Reverse cache failed"); - } - reverseCache = null; - break; - } - } - } else { - for (AccessPointAdvertisement gateway : reverseGateways) { - try { - XMLDocument xptDoc = (XMLDocument) gateway.getDocument(MimeMediaType.XMLUTF8); - StructuredDocumentUtils.copyElements(doc, e, xptDoc); - } catch (Exception e1) { - // ignored - } - } - } - } - - if (radv != null) { - try { - XMLDocument radvDoc = (XMLDocument) radv.getDocument(MimeMediaType.XMLUTF8); - - StructuredDocumentUtils.copyElements(doc, doc, radvDoc); - } catch (Exception e1) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Cannot add route advertisement"); - } - } - } - - rmElem = new TextDocumentMessageElement(MESSAGE_NAME, doc, null); - message.replaceMessageElement(MESSAGE_NS, rmElem); - - rmDirty = false; - } - - public void setSrcAddress(EndpointAddress address) { - rmExists = true; - rmDirty = true; - srcAddress = address; - } - - public EndpointAddress getSrcAddress() { - return srcAddress; - } - - public void setDestAddress(EndpointAddress address) { - rmExists = true; - rmDirty = true; - destAddress = address; - } - - public EndpointAddress getDestAddress() { - return destAddress; - } - - public void setLastHop(EndpointAddress lhop) { - rmExists = true; - rmDirty = true; - lastHop = lhop; - } - - public EndpointAddress getLastHop() { - return lastHop; - } - - public void setForwardHops(Vector fhops) { - rmExists = true; - rmDirty = true; - forwardGateways = fhops; - forwardCache = null; - } - - public Vector getForwardHops() { - return forwardGateways; - } - - public void prependReverseHop(AccessPointAdvertisement apa) { - rmExists = true; - rmDirty = true; - if (reverseGateways == null) { - reverseGateways = new Vector(); - reverseCache = new Vector(); - } - - reverseGateways.add(0, apa); - - if (reverseCache == null) { - return; - } - - // if we still have a cache (we where able to keep it conistent, update it - XMLDocument apDoc = (XMLDocument) apa.getDocument(MimeMediaType.XMLUTF8); - - reverseCache.add(0, apDoc); - } - - // Do not call this routine lightly: it blasts the cache. - public void setReverseHops(Vector rhops) { - rmExists = true; - rmDirty = true; - - // No inplace changes allowed, we need to keep the cache - // consistent: clone - - if (rhops == null) { - reverseGateways = null; - } else { - reverseGateways = (Vector) rhops.clone(); - } - - // Not worth updating the cache. Blast it. - reverseCache = null; - } - - public Vector getReverseHops() { - - if (reverseGateways == null) { - return null; - } - - return (Vector) reverseGateways.clone(); - } - - public RouteAdvertisement getRouteAdv() { - return radv; - } - - public void setRouteAdv(RouteAdvertisement radv) { - rmExists = true; - rmDirty = true; - this.radv = radv; - } - - // Used only for debugging - public String display() { - StringBuilder msgInfo = new StringBuilder("Endpoint Router Message : "); - - msgInfo.append("\n\tsrc="); - msgInfo.append((srcAddress != null) ? srcAddress : "none"); - msgInfo.append("\n\tdest== "); - msgInfo.append((destAddress != null) ? destAddress : "none"); - msgInfo.append("\n\tlastHop= "); - msgInfo.append((lastHop != null) ? lastHop : "none"); - msgInfo.append("\n\tembedded radv= "); - msgInfo.append(radv != null ? radv.display() : "none"); - if (forwardGateways != null) { - msgInfo.append("\n\tForward Hops:"); - for (int i = 0; i < forwardGateways.size(); ++i) { - try { - msgInfo.append(" [").append(i).append("] "); - msgInfo.append(forwardGateways.elementAt(i).getPeerID()); - } - catch (Exception ez1) { - break; - } - } - } - if (reverseGateways != null) { - msgInfo.append("\n\tReverse Hops:"); - for (int i = 0; i < reverseGateways.size(); ++i) { - msgInfo.append(" [").append(i).append("] "); - msgInfo.append(reverseGateways.elementAt(i).getPeerID()); - } - } - return msgInfo.toString(); - } - - // This will ensure that all older elements will be removed from - // the message in case they do not get replaced by new ones before - // updateMsg is called. - - public void clearAll() { - - if (rmExists) { - rmDirty = true; - - srcAddress = null; - destAddress = null; - lastHop = null; - forwardGateways = null; - reverseGateways = null; - radv = null; - rmExists = false; - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouteCM.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouteCM.java deleted file mode 100644 index 012e8fbe..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouteCM.java +++ /dev/null @@ -1,595 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -/** - * This class is used to manage a persistent CM cache of route - * for the router - */ -package net.jxta.impl.endpoint.router; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.XMLElement; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.util.LRUCache; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.AccessPointAdvertisement; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import net.jxta.impl.endpoint.EndpointUtils; - -class RouteCM implements Module { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(RouteCM.class.getName()); - - /** - * Default expiration time for Route advertisements. This is the amount - * of time which advertisements will live in caches. After this time, the - * advertisement should be refreshed from the source. - */ - public final static long DEFAULT_EXPIRATION = 20L * TimeUtils.AMINUTE; - - /** - * If {@code true} then the CM is used to persistently store route - * advertisements. If {@code false} then only the in-memory route table is - * used. - */ - public final static boolean USE_CM_DEFAULT = true; - - /** - * If {@code true} then the CM is used to persistently store route - * advertisements. If {@code false} then only the in-memory route table is - * used. - *

            - * We start out {@code false} until the module is started. - */ - private boolean useCM = false; - - /** - * If {@code true} then the CM is used to persistently store route - * advertisements. If {@code false} then only the in-memory route table is - * used. - */ - private boolean useCMConfig = USE_CM_DEFAULT; - - /** - * PeerGroup Service Handle - */ - private PeerGroup group = null; - private LRUCache lruCache = new LRUCache(100); - - /** - * EndpointRouter pointer - */ - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - - ModuleImplAdvertisement implAdvertisement = (ModuleImplAdvertisement) impl; - - // extract Router service configuration properties - - ConfigParams confAdv = group.getConfigAdvertisement(); - XMLElement paramBlock = null; - - if (confAdv != null) { - paramBlock = (XMLElement) confAdv.getServiceParam(assignedID); - } - - if (paramBlock != null) { - // get our tunable router parameter - Enumeration param; - - param = paramBlock.getChildren("useCM"); - if (param.hasMoreElements()) { - useCMConfig = Boolean.getBoolean(((XMLElement) param.nextElement()).getTextValue()); - } - } - - this.group = group; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Router Transport Resolver : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID : ").append(group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tUse Route CM : ").append(useCMConfig); - - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] arg) { - // ok, we are initialized, go ahead and enable CM usage desired - useCM = useCMConfig; - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - public void stopApp() { - useCM = false; - } - - /** - * return routeCM usage - * - * @return true if enabled - */ - boolean useRouteCM() { - return useCM; - } - - /** - * toggles whether to use the RouteCM - * @param enable if true it enables use of persistent store - */ - void enableRouteCM(boolean enable) { - useCM = enable; - } - - /** - * Get route advertisements from the local discovery cache. - * We collect straight RouteAdvertisements as well as what can be - * found in PeerAdvertisements. - * - *

            We can find both, and there's no way to know which is most relevant, - * so we have to return all and let the invoker try its luck with each. - * - * @param peerID the target peer's ID. - * @return Route Advertisements for the specified peer. - */ - protected Iterator getRouteAdv(ID peerID) { - DiscoveryService discovery; - - // check if we use the CM, if not then nothing - // to retrieve - if (!useCM) { - return Collections.emptyList().iterator(); - } else { - discovery = group.getDiscoveryService(); - if (null == discovery) { - return Collections.emptyList().iterator(); - } - } - - String peerIDStr = peerID.toString(); - List result = new ArrayList(2); - if (lruCache.contains(peerID)) { - result.add(lruCache.get(peerID)); - return result.iterator(); - } - // check first if we have a route advertisement - Enumeration advs = null; - - try { - advs = discovery.getLocalAdvertisements(DiscoveryService.ADV, RouteAdvertisement.DEST_PID_TAG, peerIDStr); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed discovering routes for " + peerIDStr, failed); - } - } - - while ((null != advs) && advs.hasMoreElements()) { - Advertisement adv = advs.nextElement(); - - if (!(adv instanceof RouteAdvertisement)) { - continue; - } - - RouteAdvertisement route = (RouteAdvertisement) adv; - - if (!result.contains(route)) { - result.add(route); - } - } - - // get the local peer advertisements for the peer. - advs = null; - try { - advs = discovery.getLocalAdvertisements(DiscoveryService.PEER, "PID", peerIDStr); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed discovering peer advertisements for " + peerIDStr, failed); - } - } - - while ((null != advs) && advs.hasMoreElements()) { - Advertisement adv = advs.nextElement(); - - if (!(adv instanceof PeerAdvertisement)) { - continue; - } - - PeerAdvertisement padv = (PeerAdvertisement) adv; - - RouteAdvertisement route = EndpointUtils.extractRouteAdv(padv); - - // Publish the route if it was previously unknown. - if (!result.contains(route)) { - // We found a new route just publish it locally - try { - // XXX 20060106 bondolo These publication values won't be obeyed if - // the route had been previously published. - - //FIXME by hamada: This operation may lead to overwriting an existing and valid rout adv, no? - discovery.publish(route, DEFAULT_EXPIRATION, DEFAULT_EXPIRATION); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed publishing route", failed); - } - } - result.add(route); - } - } - return result.iterator(); - } - - /** - * Create a new persistent route to the cache only if we can find set of - * endpoint addresses - * - * @param route to be published - */ - protected void createRoute(RouteAdvertisement route) { - DiscoveryService discovery; - - // check if CM is used - if (!useCM) { - return; - } else { - discovery = group.getDiscoveryService(); - - if (null == discovery) { - return; - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("try to publish route "); - } - // we need to retrieve the current adv to get all the known - // endpoint addresses - try { - RouteAdvertisement newRoute = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - - PeerID pId = route.getDestPeerID(); - - String realPeerID = pId.toString(); - - // check first if we have a route advertisement - Enumeration advs = discovery.getLocalAdvertisements(DiscoveryService.ADV, RouteAdvertisement.DEST_PID_TAG, realPeerID); - - if (!advs.hasMoreElements()) { - // No route, sorry - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("could not find a route advertisement " + realPeerID); - } - return; - } - - // make sure we are returning the longest route we know either - // from the peer or route advertisement - Advertisement adv = advs.nextElement(); - - if (adv instanceof RouteAdvertisement) { - RouteAdvertisement dest = (RouteAdvertisement) adv; - - newRoute.setDest(dest.getDest()); - } - - // let's get the endpoint addresses for each hops - Vector newHops = new Vector(); - - Enumeration e = route.getHops(); - - while (e.hasMoreElements()) { - AccessPointAdvertisement ap = e.nextElement(); - - realPeerID = ap.getPeerID().toString(); - - // check first if we have a route advertisement - advs = discovery.getLocalAdvertisements(DiscoveryService.ADV, RouteAdvertisement.DEST_PID_TAG, realPeerID); - if (!advs.hasMoreElements()) { - // No route, sorry - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("could not find a route advertisement for hop " + realPeerID); - } - return; - } - adv = advs.nextElement(); - // ensure it is a RouteAdvertisement - if (adv instanceof RouteAdvertisement) { - newHops.add(((RouteAdvertisement) adv).getDest()); - } - } - - // last check to see that we have a route - if (newHops.isEmpty()) { - return; - } - - newRoute.setHops(newHops); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("publishing new route \n" + newRoute.display()); - } - lruCache.put(route.getDestPeerID(), route); - // XXX 20060106 bondolo These publication values won't be obeyed if - // the route had been previously published. - discovery.publish(newRoute, DEFAULT_EXPIRATION, DEFAULT_EXPIRATION); - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "error publishing route" + route.display(), ex); - } - } - } - - /** - * Publish a route advertisement to the CM - * - * @param route advertisement to be published - */ - protected void publishRoute(RouteAdvertisement route) { - DiscoveryService discovery; - - // check if CM is in used, if not nothing to do - if (!useCM) { - return; - } else { - discovery = group.getDiscoveryService(); - if (null == discovery) { - return; - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Publishing route for " + route.getDestPeerID()); - } - - // publish route adv - if (!lruCache.contains(route.getDestPeerID())) { - try { - // XXX 20060106 bondolo These publication values won't be obeyed if - // the route had been previously published. - discovery.publish(route, DEFAULT_EXPIRATION, DEFAULT_EXPIRATION); - } catch (Exception ex) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "error publishing route adv \n" + route, ex); - } - } - } - lruCache.put(route.getDestPeerID(), route); - } - - /** - * flush route adv from CM - * - * @param peerID the PeerID - */ - protected void flushRoute(ID peerID) { - DiscoveryService discovery; - - // check if CM is in used, if not nothing to do - if (!useCM) { - return; - } else { - discovery = group.getDiscoveryService(); - if (null == discovery) { - return; - } - } - - // leqt's remove any advertisements (route, peer) related to this peer - // this should force a route query to try to find a new route - // check first if we have a route advertisement - String peerIDStr = peerID.toString(); - - Enumeration advs = null; - - // Flush the local route advertisements for the peer. - try { - advs = discovery.getLocalAdvertisements(DiscoveryService.ADV, RouteAdvertisement.DEST_PID_TAG, peerIDStr); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure recovering route advertisements.", failed); - } - } - - while ((null != advs) && advs.hasMoreElements()) { - Advertisement adv = advs.nextElement(); - - if (!(adv instanceof RouteAdvertisement)) { - continue; - } - - // ok so let's delete the advertisement - try { - discovery.flushAdvertisement(adv); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removed RouteAdvertisement for " + peerIDStr); - } - } catch (IOException ex) {// protect against flush IOException when the entry is not there - } - } - - // Flush the local peer advertisements for the peer. - advs = null; - try { - advs = discovery.getLocalAdvertisements(DiscoveryService.PEER, "PID", peerIDStr); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed discovering peer advertisements for " + peerIDStr, failed); - } - } - - while ((null != advs) && advs.hasMoreElements()) { - Advertisement adv = advs.nextElement(); - - if (!(adv instanceof PeerAdvertisement)) { - continue; - } - - // ok so let's delete the advertisement - try { - discovery.flushAdvertisement(adv); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removed PeerAdvertisement for " + peerIDStr); - } - } catch (IOException ex) {// protect against flush IOException when the entry is not there - } - } - // remove it from the cache as well - lruCache.remove(peerID); - } - - /** - * publish or update new route from the advertisement cache - * - * @param route to be published or updated - * @return boolean true or false if adv cache was updated - */ - protected boolean updateRoute(RouteAdvertisement route) { - DiscoveryService discovery; - - // check if CM is in used - if (!useCM) { - return false; - } else { - discovery = group.getDiscoveryService(); - if (null == discovery) { - return true; - } - } - - try { - String realPeerID = route.getDestPeerID().toString(); - - // check first if we have a route advertisement - Enumeration advs = discovery.getLocalAdvertisements(DiscoveryService.ADV, RouteAdvertisement.DEST_PID_TAG, realPeerID); - - if (advs.hasMoreElements()) { - Advertisement adv = advs.nextElement(); - - if (adv instanceof RouteAdvertisement) { - RouteAdvertisement oldRouteAdv = (RouteAdvertisement) adv; - - // check if the old route is equal to the new route - if (!route.equals(oldRouteAdv)) { - // publish the new route - // XXX 20060106 bondolo These publication values won't be obeyed if - // the route had been previously published. - discovery.publish(route, DEFAULT_EXPIRATION, DEFAULT_EXPIRATION); - lruCache.put(route.getDestPeerID(), route); - return true; - } - } - } else { - // publish the new route - discovery.publish(route, DEFAULT_EXPIRATION, DEFAULT_EXPIRATION); - lruCache.put(route.getDestPeerID(), route); - return true; - } - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, " failure to publish route advertisement response", e); - } - } - return false; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouteControl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouteControl.java deleted file mode 100644 index ccf0ec26..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouteControl.java +++ /dev/null @@ -1,502 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -/** - * This class is used to control the Router route options - * - */ -package net.jxta.impl.endpoint.router; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.MessengerEvent; -import net.jxta.endpoint.Message; -import net.jxta.id.ID; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.protocol.AccessPointAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import java.util.Iterator; -import java.util.Map; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.io.IOException; - -/** - * Provides an "IOCTL" style interface to the JXTA router transport - */ -public class RouteControl { - - /** - * Logger - */ - private static transient final Logger LOG = Logger.getLogger(RouteControl.class.getName()); - - /** - * return value for operation - */ - public final static int OK = 0; // operation succeeded - public final static int ALREADY_EXIST = 1; // failed route already exists - public final static int FAILED = -1; // failed operation - public final static int DIRECT_ROUTE = 2; // failed direct route - public final static int INVALID_ROUTE = 3; // invalid route - - /** - * Endpoint Router pointer - */ - private final EndpointRouter router; - - /** - * Router CM cache - */ - private final RouteCM routeCM; - - /** - * local Peer Id - */ - private final ID localPeerId; - - /** - * initialize RouteControl - * - * @param router the router - * @param pid the PeerID - */ - public RouteControl(EndpointRouter router, ID pid) { - this.router = router; - this.routeCM = router.getRouteCM(); - this.localPeerId = pid; - } - - /** - * get my local route - * - * @return RoutAdvertisement of the local route - */ - public RouteAdvertisement getMyLocalRoute() { - return router.getMyLocalRoute(); - } - - /** - * add a new route. For the route to be useful, we actively verify - * the route by trying it - * - * @param newRoute route to add - * @return Integer status (OK, FAILED, INVALID_ROUTE or ALREADY_EXIST) - */ - public int addRoute(RouteAdvertisement newRoute) { - - RouteAdvertisement route = newRoute.clone(); - - // check if the destination is not ourself - if (route.getDestPeerID().equals(localPeerId)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Skipping Local peer addRoute"); - } - return ALREADY_EXIST; - } - - AccessPointAdvertisement firstHop = route.getFirstHop(); - PeerID firstHopPid; - EndpointAddress firstHopAddr; - - // The route is not necessarily a direct route - if (firstHop != null) { - firstHopPid = firstHop.getPeerID(); - - // The first hop is ourselves. Remove it a move to the new first hop if any - if (localPeerId.equals(firstHopPid)) { - route.removeHop(firstHopPid); - firstHop = route.getFirstHop(); - } - } - - if (firstHop == null) { - // It really is a direct route. - EndpointAddress destAddress = EndpointRouter.pid2addr(route.getDestPeerID()); - - if (router.ensureLocalRoute(destAddress, route) != null) { - routeCM.publishRoute(newRoute); - return OK; - } - - if (router.isLocalRoute(destAddress) || router.isRoutedRoute(route.getDestPeerID())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Skipping add Route " + destAddress + " already exists"); - LOG.fine("isLocalRoute() " + router.isLocalRoute(destAddress) + " isRoutedRoute() : " - + router.isRoutedRoute(route.getDestPeerID())); - } - return ALREADY_EXIST; - } - - // ok go ahead try to connect to the destination using the route info - if (router.ensureLocalRoute(destAddress, route) == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed to connect to address :" + destAddress); - } - return FAILED; - } - - // Use the original route for publication as we may later supply the advertisement to othe peers - // which may make good use of ourselves as a first and only hop. (Normally routes are discovered - // via route discovery, which automatically stiches routes to the respondant ahead of the - // discovered route. But a discovered route adv is sometimes used as well). - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Publishing route :" + newRoute); - } - routeCM.publishRoute(newRoute); - return OK; - } - - // we have a long route - - // Manufacture a RA just that as just the routerPeer as a destination. - // We only need to publish this route if we don't know about it yet. - - RouteAdvertisement firstHopRoute = null; - - firstHopPid = firstHop.getPeerID(); - firstHopAddr = EndpointRouter.pid2addr(firstHopPid); - - if (!router.isLocalRoute(firstHopAddr) && !router.isRoutedRoute(firstHopPid)) { - firstHopRoute = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - firstHopRoute.setDest(firstHop.clone()); - router.updateRouteAdv(firstHopRoute); - } - if (router.ensureLocalRoute(firstHopAddr, firstHopRoute) == null) { - // could not find a route to the first hop, discard the route - return FAILED; - } - - router.setRoute(route.clone(), false); - return OK; - } - - /** - * Get a current route info - * - * @param pId destination of the route - * @return RouteAdvertisement current route info - */ - public RouteAdvertisement getRouteInfo(PeerID pId) { - - RouteAdvertisement route; - EndpointRouter.ClearPendingQuery entry; - EndpointAddress addr = EndpointRouter.pid2addr(pId); - - // check if we have a direct route - Messenger oneOfThem = router.getCachedMessenger(addr); - EndpointAddress pcaddr = (oneOfThem == null) ? null : oneOfThem.getDestinationAddress(); - - if (pcaddr != null) { - AccessPointAdvertisement ap = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - ap.setPeerID(pId); - Vector eas = new Vector(); - - eas.add(pcaddr.getProtocolName() + "://" + pcaddr.getProtocolAddress()); - ap.setEndpointAddresses(eas); - route = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - route.setDest(ap); - return route; - - } else { // check if we have a long route - route = router.getRoute(addr, false); - if (route != null) { - return route; - } else { // check if we have a pending query - entry = router.getPendingRouteQuery(pId); - if (entry != null) { // ok we have a pending query - AccessPointAdvertisement ap = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - ap.setPeerID(pId); - Vector eas = new Vector(); - - eas.add("pending " + (entry.isFailed() ? "(failed)" : "(new)")); - ap.setEndpointAddresses(eas); - route = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - route.setDest(ap); - return route; - } else { // sorry no route found - AccessPointAdvertisement ap = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - ap.setPeerID(pId); - route = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - route.setDest(ap); - return route; - } - } - } - } - - /** - * Delete route info - * - * @param pId destination route to be removed - * @return Integer status - */ - public int deleteRoute(PeerID pId) { - - // check if the route Id is not ourself - if (pId.equals(localPeerId)) { - return INVALID_ROUTE; - } - - EndpointAddress addr = EndpointRouter.pid2addr(pId); - - // FIXME tra 20030820 We are only allowing to remove long routes. - // Since direct routes can be used as the first hop for multiple - // valid routes, we don't want to close the associate messenger. At some - // point we should introduce a way to disassociate direct routes and - // their corresponding messengers, so we can have a generic table of routes - // and a separated table of messengers that can be manipulated - // independently. - - // Check if we have a direct route - if (router.isLocalRoute(addr)) { - return DIRECT_ROUTE; - } - - // remove routing table info - router.removeRoute(pId); - - // flush the CM. We need to flush the CM - // so the route will not be regenarated - routeCM.flushRoute(pId); - - return OK; - } - - /** - * get all the know routes by the router. Return a vector of all - * the routes known. - *

            - * This method which is meant for informational purposes, does not lock the maps that - * it browses. As a result, it could in some cases generate a concurrent modification - * exception. - * - * @return vector of known routes - */ - public Vector getAllRoutesInfo() { - - Vector routes = new Vector(); - EndpointAddress ea; - - try { - // get the direct routes - for (Iterator it = router.getAllCachedMessengerDestinations(); it.hasNext();) { - ea = (EndpointAddress) it.next(); - AccessPointAdvertisement ap = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - ap.setPeerID(EndpointRouter.addr2pid(ea)); - Vector eas = new Vector(); - Messenger oneOfThem = router.getCachedMessenger(ea); - EndpointAddress pcaddr = (oneOfThem == null) ? null : oneOfThem.getDestinationAddress(); - - if (pcaddr == null) { // incomplete route - eas.add("unknown"); - } else { - eas.add(pcaddr.getProtocolName() + "://" + pcaddr.getProtocolAddress()); - } - ap.setEndpointAddresses(eas); - RouteAdvertisement r = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - - r.setDest(ap); - routes.add(r); - } - - // now get the long routes - // Use entrySet, there's no point in doing redundant lookups - // in the map. - for (Iterator> i = router.getRoutedRouteAllDestinations(); i.hasNext();) { - Map.Entry entry = i.next(); - - routes.add(entry.getValue()); - } - - for (Map.Entry entry : router.getPendingQueriesAllDestinations()) { - PeerID pid = entry.getKey(); - AccessPointAdvertisement ap = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - ap.setPeerID(pid); - Vector eas = new Vector(); - - eas.add("pending " + (entry.getValue().isFailed() ? "(failed)" : "(new)")); - ap.setEndpointAddresses(eas); - RouteAdvertisement r = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - - r.setDest(ap); - routes.add(r); - } - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "getAllRoutesInfo error : ", ex); - } - } - return routes; - } - - /** - * get RouteCM usage - * - * @return true if use route CM is set - */ - public boolean useRouteCM() { - return router.getRouteCM().useRouteCM(); - } - - /** - * get RouteResolver usage - * - * @return true of use route resolver - */ - public boolean useRouteResolver() { - return router.getRouteResolver().useRouteResolver(); - } - - /** - * enable usage of Route CM cache - */ - public void enableRouteCM() { - router.getRouteCM().enableRouteCM(true); - } - - /** - * disable usage of Route CM cache - */ - public void disableRouteCM() { - router.getRouteCM().enableRouteCM(false); - } - - /** - * enable usage of Route Resolver - */ - public void enableRouteResolver() { - router.getRouteResolver().enableRouteResolver(true); - } - - /** - * disable usage of Route resolver - */ - public void disableRouteResolver() { - router.getRouteResolver().enableRouteResolver(false); - } - - /** - * Get the low level messenger for a destination. - * - * @param source the source endpoint address - * @param destination the destination endpoint address - * @param messenger the messenger to add - * @return true if successful - */ - public boolean addMessengerFor(Object source, EndpointAddress destination, Messenger messenger) { - return router.newMessenger(new MessengerEvent(source, messenger, destination)); - } - - /** - * Get the low level messenger for a destination. - * - * @param destination the destination endpoint address - * @param hint route hint - * @return the messenger for the destination - */ - public Messenger getMessengerFor(EndpointAddress destination, Object hint) { - if (!(hint instanceof RouteAdvertisement)) { - hint = null; - } - - return router.ensureLocalRoute(destination, (RouteAdvertisement) hint); - } - /** - * Determines whether a connection to a specific node exists, or if one can be created. - * This method can block to ensure a usable connection exists, it does so by sending an empty - * message. - * - * @param pid Node ID - * @return true, if a connection already exists, or a new was sucessfully created - */ - public boolean isConnected(PeerID pid) { - Messenger messenger = getMessengerFor(new EndpointAddress("jxta", pid.getUniqueValue().toString(), null, null), null); - if (messenger == null) { - return false; - } - if ((messenger.getState() & Messenger.USABLE) != 0) { - try { - //ensure it can be used - messenger.sendMessageB(new Message(), null, null); - } catch (IOException io) { - // determine whether it is usable - return (messenger.getState() & Messenger.USABLE) != 0; - } - } - return (messenger.getState() & Messenger.CLOSED) != Messenger.CLOSED; - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouteResolver.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouteResolver.java deleted file mode 100644 index 6f3cfd17..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouteResolver.java +++ /dev/null @@ -1,1432 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.router; - -import net.jxta.credential.Credential; -import net.jxta.document.*; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.OutgoingMessageEvent; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.impl.cm.Srdi; -import net.jxta.impl.cm.Srdi.SrdiInterface; -import net.jxta.impl.cm.SrdiIndex; -import net.jxta.impl.protocol.*; -import net.jxta.impl.util.TimeUtils; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.*; -import net.jxta.resolver.QueryHandler; -import net.jxta.resolver.ResolverService; -import net.jxta.resolver.SrdiHandler; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Handles dynamic route resolution. - */ -class RouteResolver implements Module, QueryHandler, SrdiHandler, SrdiInterface { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(RouteResolver.class.getName()); - - /** - * Router Service Name - */ - public final static String routerSName = "EndpointRouter"; - - private final static String srdiIndexerFileName = "routerSrdi"; - - /** - * Negative Route query acknowledgment - */ - private final static int NACKROUTE_QUERYID = -1; - - /** - * Bad route expiration. Amount of time we consider a route bad - */ - private final static long BADROUTE_EXPIRATION = 2L * TimeUtils.AMINUTE; - - /** - * Default dynamic route resolution configuration preference. - */ - private final static boolean USE_ROUTE_RESOLVER_DEFAULT = true; - - /** - * Configuration property that disables the usage - * of dynamic route resolution. Dynamic routes - * will not be discovered. set to true by default - * can be overwritten via ConfigParams - */ - private boolean useRouteResolver = USE_ROUTE_RESOLVER_DEFAULT; - - /** - * PeerGroup Service Handle - */ - private PeerGroup group = null; - - /** - * Resolver service handle - */ - private ResolverService resolver = null; - - /** - * membership service - */ - private MembershipService membership = null; - - /** - * EndpointRouter pointer - */ - private EndpointRouter router = null; - - /** - * local peer ID as a endpointAddress. - */ - private EndpointAddress localPeerAddr = null; - - /** - * local Peer ID - */ - private ID localPeerId = null; - - /** - * Route CM Persistent cache - */ - private RouteCM routeCM = null; - - /** - * The current resolver query ID. static to make debugging easier. - */ - private final static AtomicInteger qid = new AtomicInteger(0); - - /** - * SRDI route index - */ - private SrdiIndex srdiIndex = null; - - /** - * SRDI Index - */ - private Srdi srdi = null; - - /** - * Encapsulates current Membership Service credential. - */ - final static class CurrentCredential { - - /** - * The current default credential - */ - final Credential credential; - - /** - * The current default credential in serialized XML form. - */ - final XMLDocument credentialDoc; - - CurrentCredential(Credential credential, XMLDocument credentialDoc) { - this.credential = credential; - this.credentialDoc = credentialDoc; - } - } - - /** - * The current Membership service default credential. - */ - CurrentCredential currentCredential; - - /** - * Listener we use for membership property events. - */ - private class CredentialListener implements PropertyChangeListener { - - /** - * Standard Constructor - */ - CredentialListener() {} - - /** - * {@inheritDoc} - */ - public void propertyChange(PropertyChangeEvent evt) { - if (MembershipService.DEFAULT_CREDENTIAL_PROPERTY.equals(evt.getPropertyName())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("New default credential event"); - } - - synchronized (RouteResolver.this) { - Credential cred = (Credential) evt.getNewValue(); - XMLDocument credentialDoc; - if (null != cred) { - try { - credentialDoc = (XMLDocument) cred.getDocument(MimeMediaType.XMLUTF8); - currentCredential = new CurrentCredential(cred, credentialDoc); - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not generate credential document", all); - } - currentCredential = null; - } - } else { - currentCredential = null; - } - } - } - } - } - - final CredentialListener membershipCredListener = new CredentialListener(); - - /** - * @param router the router - */ - RouteResolver(EndpointRouter router) { - this.router = router; - } - - /** - * initialize routeResolver - */ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - - ModuleImplAdvertisement implAdvertisement = (ModuleImplAdvertisement) impl; - - // extract Router service configuration properties - ConfigParams confAdv = group.getConfigAdvertisement(); - XMLElement paramBlock = null; - - if (confAdv != null) { - paramBlock = (XMLElement) confAdv.getServiceParam(assignedID); - } - - if (paramBlock != null) { - // get our tunable router parameter - Enumeration param; - - param = paramBlock.getChildren("useRouteResolver"); - if (param.hasMoreElements()) { - useRouteResolver = Boolean.getBoolean(((XMLElement) param.nextElement()).getTextValue()); - } - } - - this.group = group; - - localPeerId = group.getPeerID(); - - localPeerAddr = EndpointRouter.pid2addr(group.getPeerID()); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Router Transport Resolver : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration:"); - configInfo.append("\n\t\tUse Route Resolver : ").append(useRouteResolver()); - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] arg) { - - resolver = group.getResolverService(); - - if (null == resolver) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Endpoint Router start stalled until resolver service available"); - } - return Module.START_AGAIN_STALLED; - } - - membership = group.getMembershipService(); - - if (null == membership) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Endpoint Router start stalled until membership service available"); - } - return Module.START_AGAIN_STALLED; - } - - resolver.registerHandler(routerSName, this); - // create and register the srdi service - srdiIndex = new SrdiIndex(group, srdiIndexerFileName); - // Srdi is a thread but we are not going to start, - // since the service is reactive. - srdi = new Srdi(group, routerSName, this, srdiIndex, 0, 0); - resolver.registerSrdiHandler(routerSName, this); - - synchronized (this) { - // register our credential listener. - membership.addPropertyChangeListener(MembershipService.DEFAULT_CREDENTIAL_PROPERTY, membershipCredListener); - - try { - // set the initial version of the default credential. - currentCredential = null; - Credential credential = membership.getDefaultCredential(); - XMLDocument credentialDoc; - - if (null != credential) { - credentialDoc = (XMLDocument) credential.getDocument(MimeMediaType.XMLUTF8); - currentCredential = new CurrentCredential(credential, credentialDoc); - } - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "could not get default credential", all); - } - } - } - - // get the RouteCM cache service - routeCM = router.getRouteCM(); - - return Module.START_OK; - } - - /** - * {@inheritDoc} - *

            - * Careful that stopApp() could in theory be called before startApp(). - */ - public void stopApp() { - - resolver.unregisterHandler(routerSName); - - // unregister SRDI - resolver.unregisterSrdiHandler(routerSName); - srdiIndex.stop(); - - membership.removePropertyChangeListener("defaultCredential", membershipCredListener); - currentCredential = null; - - resolver = null; - srdi = null; - membership = null; - } - - /** - * return routeResolver usage - * - * @return routeResolver usage - */ - boolean useRouteResolver() { - return useRouteResolver; - } - - /** - * enable routeResolver usage - * @param enable if true, enables route resolver - */ - void enableRouteResolver(boolean enable) { - useRouteResolver = enable; - } - - /** - * issue a new route discovery resolver request - * - * @param peer the destination as a logical endpoint address - */ - protected void findRoute(EndpointAddress peer) { - - RouteAdvertisement myRoute = router.getMyLocalRoute(); - - // No need to pursue further if we haven't initialized our own route as - // responding peers are not going to be able to respond to us. - if (myRoute == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Cannot issue a find route if we don\'t know our own route"); - } - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Find route for peer = " + peer); - } - - try { - // create a new RouteQuery message - RouteQuery doc; - - // check if we have some bad route information - // for that peer, in that case pass the bad hop count - BadRoute badRoute; - - badRoute = router.getBadRoute(peer); - - if (badRoute != null) { - // ok we have a bad route - // pass the bad hops info as part of the query - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("findRoute sends query: known bad Hops" + badRoute); - } - doc = new RouteQuery(EndpointRouter.addr2pid(peer), myRoute, badRoute.getBadHops()); - } else { - doc = new RouteQuery(EndpointRouter.addr2pid(peer), myRoute, null); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending query for peer : " + peer); - } - - XMLDocument credentialDoc; - CurrentCredential current = currentCredential; - - if (null != current) { - credentialDoc = current.credentialDoc; - } else { - credentialDoc = null; - } - - ResolverQuery query = new ResolverQuery(routerSName, credentialDoc, localPeerId.toString(), doc.toString(), qid.incrementAndGet()); - - // only run SRDI if we are a rendezvous - // FIXME 20060106 bondolo This is not dynamic enough. The route - // resolver needs to respond to changes in rendezvous configuration - // at runtime. - if (group.isRendezvous()) { - - // check where to send the query via SRDI - List results; - - if (srdiIndex != null) { - // try to find a least 10 entries, will pick up one - // randomly. This will protect against retry. It is - // likely that a number of RDV will know about a route - results = srdiIndex.query("route", RouteAdvertisement.DEST_PID_TAG, EndpointRouter.addr2pid(peer).toString(), 10); - - if (results != null && !results.isEmpty()) { - // use SRDI to send the query - // remove any non rdv peers from the candidate list - // and garbage collect the index in the process - List clean = cleanupAnyEdges(query.getSrcPeer(), results); - - if (!clean.isEmpty()) { - // The purpose of incrementing the hopcount - // when an SRDI index match is found (we got a - // pointer to a rdv that should have the route) is to - // restrict any further forwarding. The increment - // count is only done when a matching SRDI index is - // found. Not when the replica is selected as we - // still need to forward the query. This restriction - // is purposelly done to avoid too many longjumps - // within a walk. - query.incrementHopCount(); - - srdi.forwardQuery(clean, query, 1); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("found an srdi entry forwarding query to SRDI peer"); - } - return; - } - } else { - // it is not in our cache, look for the replica peer - // we need to send the query - PeerID destPeer = srdi.getReplicaPeer(EndpointRouter.addr2pid(peer).toString()); - - if (destPeer != null && !destPeer.equals(localPeerId)) { - // don't push anywhere if we do not have a replica - // or we are trying to push to ourself - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("processQuery srdiIndex DHT forward :" + destPeer); - } - - srdi.forwardQuery(destPeer, query); - return; - } else { - LOG.fine("processQuery srdiIndex DHT forward resulted in no op"); - } - } - } - } - - // if we reach that point then we just use the resolver walk - resolver = group.getResolverService(); - if (resolver != null) { - resolver.sendQuery(null, query); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("find route query sent"); - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("cannot get the resolver service"); - } - } - } catch (Exception ee) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception in findRoute", ee); - } - } - } - - /** - * {@inheritDoc} - *

            - * This is called by the Generic ResolverServiceImpl when processing a - * response to a query. - */ - public void processResponse(ResolverResponseMsg response) { - - if (!useRouteResolver) { // Route resolver disabled - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("processResponse got a response"); - } - - // convert the response into a RouteResponse - RouteResponse doc = null; - - try { - Reader ip = new StringReader(response.getResponse()); - - XMLDocument asDoc = (XMLDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, ip); - - doc = new RouteResponse(asDoc); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "malformed response - discard", e); - } - return; - } - - RouteAdvertisement dstRoute = doc.getDestRoute(); - RouteAdvertisement srcRoute = doc.getSrcRoute(); - int queryId = response.getQueryId(); - - EndpointAddress routingPeer = EndpointRouter.pid2addr(srcRoute.getDestPeerID()); - EndpointAddress destPeer = EndpointRouter.pid2addr(dstRoute.getDestPeerID()); - - // check if we have a negative route response - if (queryId == NACKROUTE_QUERYID) { - AccessPointAdvertisement badHop = dstRoute.nextHop(EndpointRouter.addr2pid(routingPeer)); - - PeerID badPeer; - - if (badHop != null) { - badPeer = badHop.getPeerID(); - } else { // the bad hop is the final destination - badPeer = dstRoute.getDestPeerID(); - } - - processBadRoute(badPeer, dstRoute); - return; - } - - // This is not our own peer adv, so we must not keep it - // for more than its expiration time. - // we only need to publish this route if - // we don't know about it yet - // XXX: here is where we could be more conservative and use isNormallyReachable() instead, thus excluding - // incoming messengers. - if ((!router.isLocalRoute(EndpointRouter.pid2addr(srcRoute.getDestPeerID()))) - && (!router.isRoutedRoute(srcRoute.getDestPeerID()))) { - router.updateRouteAdv(srcRoute); - } - - if (destPeer.equals(routingPeer)) { - // The dest peer itself managed to respond to us. That means we - // learned the route from the reverseRoute in the message - // itself. So, there's nothing we need to do. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("learn route directly from the destination"); - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("learn route:" + routingPeer); - } - - try { - // build the candidate route using the - // route response from the respondant peer - RouteAdvertisement candidateRoute = RouteAdvertisement.newRoute(EndpointRouter.addr2pid(destPeer), - EndpointRouter.addr2pid(routingPeer),(Vector) dstRoute.getVectorHops().clone()); - - // cleanup the candidate route from any loop and remove the local peer extra - // cycle - RouteAdvertisement.cleanupLoop(candidateRoute, (PeerID) localPeerId); - - // Is there anything left in that route (or did the respondant - // believe that we are the last hop on the route - which - // obviously we are not. - if (candidateRoute.size() == 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Route response outdated: NACK responder"); - } - generateNACKRoute(EndpointRouter.addr2pid(routingPeer), EndpointRouter.addr2pid(destPeer), dstRoute.getVectorHops()); - return; - } - - // get the address of the first hop in the route to verify that - // we have a route (direct or long) to the first hop, so the route - // is valid - EndpointAddress candidateRouter = EndpointRouter.pid2addr(candidateRoute.getFirstHop().getPeerID()); - - // check that we have a direct connection to the first hop - if (router.ensureLocalRoute(candidateRouter, null) == null) { - // If we do not have a direct route to the candidate router check - // for a long route in that case stich the route - RouteAdvertisement routeToRouter = router.getRoute(candidateRouter, false); - - if (routeToRouter == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Route response useless: no route to next router hop"); - } - return; - } - - // stich the route removing any loops and localPeer cycle - if (RouteAdvertisement.stichRoute(candidateRoute, routeToRouter, (PeerID) localPeerId)) { - router.setRoute(candidateRoute, false); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Route response error stiching route response"); - } - return; - } - } else { - // we have a direct connection with the first hop of the candidate route - // set the new route, which starts with the peer that replied to us. - router.setRoute(candidateRoute, false); - } - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure building response route", ex); - LOG.warning(" bad dstRoute: " + dstRoute.display()); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("finish process route response successfully"); - } - } - } - - /** - * bad route, so let's remove everything we have so - * we can start from scratch. We are maintaining a - * bad route up to DEFAULT_ROUTE expiration after - * that we consider it to be ok to retry the same route - * We are removing both the route and peer advertisement - * to force a new route query - * - * @param badHop source PeerID of NACK route info - * @param dest original route information - */ - private void processBadRoute(PeerID badHop, RouteAdvertisement dest) { - - EndpointAddress addr = EndpointRouter.pid2addr(dest.getDestPeerID()); - - if (addr == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("remove bad route has a bad route info - discard"); - } - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("remove bad route info for dest " + dest.display()); - if (badHop != null) { - LOG.fine("remove bad route bad hop " + badHop); - } - } - - try { - - // check first that we still have the same route, we may already - // using a new route - RouteAdvertisement currentRoute = router.getRoute(addr, false); - - if (currentRoute == null) { // we already cleanup the route info - return; - } - - // check if we still have the old bad route, we may have - // already updated the route - if (!currentRoute.equals(dest)) { - - // check if the bad hop is not the destination - // if it is then we still have a bad route - if (badHop == null) { - // we could get the bad hop, so consider the route ok - return; - } - if (badHop.equals(EndpointRouter.addr2pid(addr))) { - // check if the new route may still contain the bad hop - // the known bad hop is the hop after the src peer that - // responded with a NACK route - // In this case we also consider the route bad - if (!currentRoute.containsHop(badHop)) { - return; // we are ok - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("current route is bad because it contains known bad hop" + badHop); - } - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("current route is bad because it contains known bad destination" + badHop); - } - } - - } - - // keep the bad one in a cache table so we don't retry them - // right away. We use the default route timeout - BadRoute badRoute = (router.getBadRoute(addr)); - - if (badRoute != null) { - if (badRoute.getExpiration() > TimeUtils.timeNow()) {// nothing to do. the information is still valid - } else { - // It is ancient knowlege update it - badRoute.setExpiration(TimeUtils.toAbsoluteTimeMillis(BADROUTE_EXPIRATION)); - } - - // check if we have to add a new bad hop - // to our bad route - if (badHop != null) { - badRoute.addBadHop(badHop); - badRoute.setExpiration(TimeUtils.toAbsoluteTimeMillis(BADROUTE_EXPIRATION)); - } - - router.setBadRoute(addr, badRoute); - return; - } else { - // create a new NACK route entry - Set badHops; - - if (badHop != null) { - badHops = Collections.singleton(badHop); - } else { - badHops = Collections.emptySet(); - } - - badRoute = new BadRoute(dest, TimeUtils.toAbsoluteTimeMillis(BADROUTE_EXPIRATION), badHops); - router.setBadRoute(addr, badRoute); - } - - // remove route from route CM - routeCM.flushRoute(EndpointRouter.addr2pid(addr)); - - // let's remove the remote route info from the routing table - // we do this after we removed the entries from the CM - // to avoid that another thread is putting back the entry - router.removeRoute(EndpointRouter.addr2pid(addr)); - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "exception during bad route removal", ex); - } - } - } - - /** - * Process the Query, and generate response - * - * @param query the query to process - */ - public int processQuery(ResolverQueryMsg query) { - - if (!useRouteResolver) { // Route resolver disabled - return ResolverService.OK; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("processQuery starts"); - } - - RouteQuery routeQuery; - try { - Reader ip = new StringReader(query.getQuery()); - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, ip); - routeQuery = new RouteQuery(asDoc); - } catch (RuntimeException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Malformed Route query ", e); - } - return ResolverService.OK; - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Malformed Route query ", e); - } - return ResolverService.OK; - } - - PeerID pId = routeQuery.getDestPeerID(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Looking for route to " + pId); - } - - RouteAdvertisement srcRoute = routeQuery.getSrcRoute(); - Collection badHops = routeQuery.getBadHops(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - StringBuilder badHopsDump = new StringBuilder("bad Hops :\n"); - - for (ID aBadHop : badHops) { - badHopsDump.append('\t').append(aBadHop); - } - - LOG.finer(badHopsDump.toString()); - } - - // if our source route is not null, then publish it - if (srcRoute != null) { - if (!(srcRoute.getDestPeerID()).equals(localPeerId)) { - // This is not our own peer adv so we must not keep it - // longer than its expiration time. - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Publishing sender route info " + srcRoute.getDestPeerID()); - } - - // we only need to publish this route if - // we don't know about it yet - // XXX: here is where we could be more conservative and use isNormallyReachable() instead, thus excluding - // incoming messengers. - if ((!router.isLocalRoute(EndpointRouter.pid2addr(srcRoute.getDestPeerID()))) - && (!router.isRoutedRoute(srcRoute.getDestPeerID()))) { - routeCM.publishRoute(srcRoute); - } - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Could not publish Route Adv from query - discard", e); - } - return ResolverService.OK; - } - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No src Route in route query - discard "); - } - return ResolverService.OK; - } - - if (pId == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Malformed route query request, no PeerId - discard"); - } - return ResolverService.OK; - } - - // We have more luck with that one because, since it is part of OUR - // message, and not part of the resolver protocol, it is in OUR - // format. - EndpointAddress qReqAddr = EndpointRouter.pid2addr(pId); - - RouteAdvertisement route; - - // check if this peer has a route to the destination - // requested - boolean found = false; - - if (qReqAddr.equals(localPeerAddr)) { - found = true; - // return the route that is my local route - route = router.getMyLocalRoute(); - } else { - // only rendezvous can respond to route requests - // if not we are generating too much traffic - // XXX: here is where we could be more conservative and use isNormallyReachable() instead, thus excluding - // incoming messengers. - if (router.isLocalRoute(qReqAddr)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Peer has direct route to destination "); - } - // we should set the route to something :-) - - found = true; - - // this peer has a direct route to the destination - // return the short route advertisement we know for this peer - // (For us it is zero hop, and we advertise ourself as the routing - // peer in the response. The stiching is done by whoever gets that - // response). May be there are more than one hop advertised in-there... - // alternate routing peers...should we leave them ? - // For now, we keep the full dest, but wack the hops. - - route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - - AccessPointAdvertisement ap = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - ap.setPeerID(pId); - route.setDest(ap); - } else { - route = router.getRoute(qReqAddr, false); - if (route != null) { - found = true; - // check if we were given some bad hops info - // and see if the found route contains - // any of these bad hops. In that case, we need - // to mark this route as bad - for (PeerID aBadHop : badHops) { - // destination is known to be bad - if (EndpointRouter.addr2pid(qReqAddr).equals(aBadHop)) { - processBadRoute(aBadHop, route); - found = false; - break; - } - - if (route.containsHop(aBadHop)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Peer has bad route due to " + aBadHop); - } - processBadRoute(aBadHop, route); - found = false; - break; - } - } - } - } - } - - if (!found) { - // discard the request if we are not a rendezvous - // else forward to the next peers - if (!group.isRendezvous()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("discard query forwarding as not a rendezvous"); - } - return ResolverService.OK; - } - - // did not find a route, check our srdi cache - // make sure we protect against out of sync - // SRDI index - - // srdi forwarding is only involved once the Index entry has - // been found and we forwarded the resolver query. Afterward a - // normal walk proceeds from the initial SRDI index pointing - // rdv. This is done to protect against potential loopback - // entries in the SRDI cache index due to out of sync peerview - // and index. - if (query.getHopCount() < 2) { - - // check local SRDI cache to see if we have the entry - // we look for 10 entries, will pickup one randomly - List results = srdiIndex.query("route", RouteAdvertisement.DEST_PID_TAG, pId.toString(), 10); - - if (results.size() > 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("processQuery srdiIndex lookup match :" + results.size()); - } - - // remove any non-rdv peers to avoid sending - // to a non-rdv peers and garbage collect the SRDI - // index in the process - List clean = cleanupAnyEdges(query.getSrcPeer(), results); - - if (clean.size() > 0) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("found an srdi entry forwarding query to SRDI peer"); - } - - // The purpose of incrementing the hopcount - // when an SRDI index match is found (we got a - // pointer to a rdv that should have the route) is to - // restrict any further forwarding. The increment - // count is only done when a matching SRDI index is - // found. Not when the replica is selected as we - // still need to forward the query. This restriction - // is purposelly done to avoid too many longjumps - // within a walk. - query.incrementHopCount(); - - // Note: this forwards the query to 1 peer randomly - // selected from the result - srdi.forwardQuery(clean, query, 1); - - // tell the resolver no further action is needed. - return ResolverService.OK; - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("did not find a route or SRDI index"); - } - - // force a walk - return ResolverService.Repropagate; - } - - // we found a route send the response - try { - if (route == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("we should have had a route at this point"); - } - return ResolverService.OK; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("we have a route build route response" + route.display()); - } - - RouteAdvertisement myRoute = router.getMyLocalRoute(); - - // make sure we initialized our local - // route info as we will need it to respond. We may - // not have our route if we are still - // waiting for a relay connection. - if (myRoute == null) { - return ResolverService.OK; - } - - RouteResponse routeResponse = new RouteResponse(); - - routeResponse.setDestRoute(route); - routeResponse.setSrcRoute(myRoute); - - if (routeResponse == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("error creating route response"); - } - return ResolverService.OK; - } - - // construct a response from the query - ResolverResponseMsg res = query.makeResponse(); - - CurrentCredential current = currentCredential; - - if (null != current) { - res.setCredential(current.credentialDoc); - } - res.setResponse(routeResponse.toString()); - - resolver.sendResponse(query.getSrcPeer().toString(), res); - return ResolverService.OK; - - } catch (Exception ee) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "processQuery: error while processing query ", ee); - } - return ResolverService.OK; - } - } - - /** - * Return a route error in case a route was found to be invalid - * as the current hop cannot find a way to forward the message to the - * destination or any other hops in the forward part of the route. - * In that case a negative route response is forwarded - * to the original source of the message. Now of course we - * do not have any way to guarantee that the NACK message will be - * received by the sender, but the best we can do is to try :-) - *

            - * we send a query ID to NACKROUTE_QUERYID to indicate - * this is a bad Route - * - * @param src original source of the message - * @param dest original destination of the message - * @param origHops original hops - */ - protected void generateNACKRoute(PeerID src, PeerID dest, Vector origHops) { - - // As long as the group is partially initialized, do not bother - // trying to send NACKS. We can't: it just causes NPEs. - if (resolver == null) { - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("generate NACK Route response " + src); - } - - // check first, if we are not already in process of looking for a - // route to the destination peer of the NACK. We should not try to - // send a NACK to that destination at that point as this will block - // our incoming processing thread while it is looking for a route to - // that destination. If there a no pending route requests to that - // destination then we can go ahead an attempt to send the NACK. At - // the maximum we should have only one thread block while looking for - // a specific destination. When we find a route to the destination, - // the next NACK processing will be sent. - - if (router.isPendingRouteQuery(src)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("drop NACK due to pending route discovery " + src); - } - return; - } - - // Generate a route response - RouteAdvertisement route = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - - AccessPointAdvertisement ap = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - ap.setPeerID(dest); - route.setDest(ap); - route.setHops(origHops); - - // set the the route of the peer that - // detected the bad route - RouteAdvertisement routeSrc = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - - AccessPointAdvertisement apSrc = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - apSrc.setPeerID((PeerID) localPeerId); - routeSrc.setDest(apSrc); - - RouteResponse routeResponse = new RouteResponse(); - - routeResponse.setDestRoute(route); - routeResponse.setSrcRoute(routeSrc); - - ResolverResponse res = new ResolverResponse(); - - res.setHandlerName(routerSName); - - CurrentCredential current = currentCredential; - - if (null != current) { - res.setCredential(current.credentialDoc); - } - - res.setQueryId(NACKROUTE_QUERYID); - res.setResponse(routeResponse.toString()); - - // send the NACK response back to the originator - resolver.sendResponse(src.toString(), res); - } - - /** - * process an SRDI message request - * - * @param message SRDI resolver message - */ - public boolean processSrdi(ResolverSrdiMsg message) { - if(!group.isRendezvous()) { - return true; - } - - String value; - SrdiMessage srdiMsg; - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received a SRDI messsage in group" + group.getPeerGroupName()); - } - - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, new StringReader(message.getPayload())); - srdiMsg = new SrdiMessageImpl(asDoc); - } catch (Exception e) { - // we don't understand this msg, let's skip it - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "corrupted SRDI message", e); - } - return false; - } - - PeerID pid = srdiMsg.getPeerID(); - - // filter messages that contain messages - // about the local peer, so we don't enter - // self-reference - if (pid.equals(localPeerId)) { - return false; - } - - for (SrdiMessage.Entry entry : srdiMsg.getEntries()) { - // drop any information about ourself - if (entry.key.equals(localPeerId.toString())) { - continue; - } - value = entry.value; - if (value == null) { - value = ""; - } - - // Expiration of entries is taken care of by SrdiIdex, so we always add - // FIXME hamada 20030314 - // All routes are added under the secondary key 'DstPID', it would be more correct to - // Specify it in the message, but since versioning is not yet supported the following is - // acceptable, since it is localized - srdiIndex.add(srdiMsg.getPrimaryKey(), RouteAdvertisement.DEST_PID_TAG, entry.key, pid, entry.expiration); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Primary Key [" + srdiMsg.getPrimaryKey() + "] key [RouteAdvertisement.DEST_PID_TAG]" + " value [" + entry.key + "] exp [" + entry.expiration + "]"); - } - } - - return true; - } - - /** - * {@inheritDoc} - */ - public void pushEntries(boolean all) { - // only send to the replica - pushSrdi(null, all); - } - - /* - * push all srdi entries to the rednezvous SRDI cache (new connection) - * - *@param all if true push all entries, otherwise just deltas - */ - protected void pushSrdi(String peer, boolean all) { - - SrdiMessage srdiMsg; - Vector routeIx = new Vector(); - - // 20021018 tra:Route info don't expire unless the peer disappears - // This approach is used to limit the SRDI traffic. The key - // point here is that SRDI is used to tell a peer that another - // has a route to the destination it is looking for. The information - // that SRDI cache is not so much the specific route info but rather - // the fact that a peer has knowledge of a route to another peer - // We don't want to update the SRDI cache on every route update. - // The SRDI cache will be flushed when the peer disconnect from - // the rendezvous. - - // We cannot support concurrent modification of the map while we - // do that: we must synchronize... - for (Iterator each = router.getAllRoutedRouteAddresses(); each.hasNext();) { - ID pid = each.next(); - SrdiMessage.Entry entry = new SrdiMessage.Entry(pid.toString(), "", Long.MAX_VALUE); - routeIx.addElement(entry); - } - - try { - // check if we have anything to send - if (routeIx.size() == 0) { - return; - } - - srdiMsg = new SrdiMessageImpl(group.getPeerID(), - // one hop - 1, - "route", routeIx); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending a SRDI messsage of [All=" + all + "] routes"); - } - // this will replicate entry to the SRDI replica peers - srdi.replicateEntries(srdiMsg); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "SRDI Push failed", e); - } - } - } - - /* - * push srdi entries to the SRDI rendezvous cache - * @param all if true push all entries, otherwise just deltas - */ - protected void pushSrdi(ID peer, PeerID id) { - - SrdiMessage srdiMsg; - - try { - srdiMsg = new SrdiMessageImpl(group.getPeerID(), 1, // only one hop - "route", id.toString(), null, Long.MAX_VALUE); // maximum expiration - // 20021018 tra:Route info don't expire unless the peer disappears - // This approach is used to limit the SRDI traffic. The key - // point here is that SRDI is used to tell a peer that another - // has a route to the destination it is looking for. The information - // that SRDI cache is not so much the specific route info but rather - // the fact that a peer has knowledge of a route to another peer - // We don't want to update the SRDI cache on every route update. - // The SRDI cache will be flushed when the peer disconnect from - // the rendezvous. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("sending a router SRDI message add route " + id); - } - if (peer == null) { - PeerID destPeer = srdi.getReplicaPeer(id.toString()); - peer = destPeer; - } - // don't push anywhere if we do not have a replica - // or we are trying to send the query to ourself - if (!localPeerId.equals(peer)) { - srdi.pushSrdi(peer, srdiMsg); - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "SRDI push failed", e); - } - } - } - - /** - * remove a SRDI cache entry - * - * @param peer peer id we send the request, null for sending to all - * @param id peer id of the SRDI route that we want to remove - * from the cache - */ - protected void removeSrdi(String peer, PeerID id) { - - SrdiMessage srdiMsg; - - try { - srdiMsg = new SrdiMessageImpl(group.getPeerID(), 1, // only one hop - "route", id.toString(), null, // 0 means remove - 0); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("sending a router SRDI message delete route " + id); - } - - if (peer == null) { - PeerID destPeer = srdi.getReplicaPeer(id.toString()); - - // don't push anywhere if we do not have replica - // or we are trying to push to ouself - if (destPeer != null && (!destPeer.equals(localPeerId))) { - srdi.pushSrdi(destPeer, srdiMsg); - } - } - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Removing srdi entry failed", e); - } - } - } - - /** - * {@inheritDoc} - */ - public void messageSendFailed(PeerID peerid, OutgoingMessageEvent e) { - // when the resolver failed to send, we get a notification and - // flush the SRDI cache entries for that destination - removeSrdiIndex(peerid); - } - - /** - * cleanup any edge peers when trying to forward an SRDI query so we are - * guaranteed to the best of our knowledge that the peer is a rendezvous. - * This is not perfect, as it may take time for the peerview to converge but - * at least we can remove any peers that is not a rendezvous. - * - * @param src source - * @param results vector of PeerIDs - * @return cleaned up vector of PeerIDs - */ - protected List cleanupAnyEdges(ID src, List results) { - List clean = new ArrayList(results.size()); - - // put the peerview as a vector of PIDs - List rpvId = srdi.getGlobalPeerView(); - - // remove any peers not in the current peerview - // these peers may be gone or have become edges - for (PeerID pid : results) { - // eliminate the src of the query so we don't resend - // the query to whom send it to us - if (src.equals(pid)) { - continue; - } - // remove the local also, so we don't send to ourself - if (localPeerId.equals(pid)) { - continue; - } - if (rpvId.contains(pid)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("valid rdv for SRDI forward " + pid); - } - clean.add(pid); - } else { - // cleanup our SRDI cache for that peer - srdiIndex.remove(pid); - } - } - return clean; - } - - /** - * remove SRDI index - * - * @param pid of the index to be removed - */ - protected void removeSrdiIndex(PeerID pid) { - srdiIndex.remove(pid); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouterMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouterMessenger.java deleted file mode 100644 index 7b9245f5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/RouterMessenger.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.router; - - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.impl.endpoint.BlockingMessenger; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.IOException; -import net.jxta.protocol.RouteAdvertisement; - - -/** - * Messenger for destinations which are logical peers. This messenger is used - * only at the origin of routes. Incoming messages that are being forwarded to - * another peer do not use this form of messenger. - */ -class RouterMessenger extends BlockingMessenger { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(RouterMessenger.class.getName()); - - /** - * The router we are working for. Also who we make route queries to. - */ - private final EndpointRouter router; - - /** - * Constructor for a RouterMessenger. - * - * @param dstAddress the peer which is the final destination of the message. - * @param r the router which this messenger is servicing. - * @param hint potential hint information that we passed - * @throws IOException Thrown if the messenger cannot be constructed for this destination. - */ - public RouterMessenger(EndpointAddress dstAddress, EndpointRouter r, Object hint) throws IOException { - - // Make sure that we do not ask for self destruction. - super(r.getEndpointService().getGroup().getPeerGroupID(), dstAddress, false); - - this.router = r; - - // Probably redundant. getGatewayAddress does it. - EndpointAddress plainAddr = new EndpointAddress(dstAddress, null, null); - - // Discard the hint if it is not a route advertisement. - if (!(hint instanceof RouteAdvertisement)) { - hint = null; - } - - // We aggressively look for a route upfront. If it fails, we must refuse to create the messenger. - EndpointAddress gate = router.getGatewayAddress(plainAddr, true, (RouteAdvertisement) hint); - - if (gate == null) { - throw new IOException("Could not construct RouterMessenger, no route for " + plainAddr); - } - } - - /** - * {@inheritDoc} - */ - @Override - public EndpointAddress getLogicalDestinationImpl() { - return getDestinationAddress(); - } - - /** - * {@inheritDoc} - */ - @Override - public void closeImpl() {// Nothing to do. The underlying connection is not affected. - // The messenger will be marked closed by the state machine once completely down; that's it. - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isIdleImpl() { - // We do not need self destruction. - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public void sendMessageBImpl(Message message, String service, String serviceParam) throws IOException { - - if (isClosed()) { - IOException failure = new IOException("Messenger was closed, it cannot be used to send messages."); - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, failure.getMessage(), failure); - } - - throw failure; - } - - EndpointAddress dest = getDestAddressToUse(service, serviceParam); - - // Loop trying to send message until we run out of routes. - Throwable lastFailure = null; - - while (true) { - EndpointAddress sendTo = null; - - try { - sendTo = router.addressMessage(message, dest); - if (null == sendTo) { - break; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + message + " to " + sendTo); - } - - router.sendOnLocalRoute(sendTo, message); - - // it worked! We are done. - return; - } catch (RuntimeException rte) { - // Either the message is invalid, or there is - // a transport loop and the upper layer should close. - // Either way, we must not retry. The loop could be - // unbounded. - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure while routing " + message, rte); - } - - lastFailure = rte; - break; - } catch (Throwable theMatter) { - if (sendTo == null) { - // This is bad: address message was not able to - // do anything. Stop the loop. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Unknown failure while routing " + message, theMatter); - } - break; - } - - // Everything else is treated like a bad route. - lastFailure = theMatter; - } - - // Currently we have only one long route per destination. - // If the first hop is broken, then that long route is broken - // as well. We must dump it, under penalty of trying it over and over again. - - EndpointAddress destPeer = new EndpointAddress(getDestinationAddress(), null, null); - - router.removeRoute(EndpointRouter.addr2pid(destPeer)); - - // reset the router message for the next attempt. - message.removeMessageElement(message.getMessageElement(EndpointRouterMessage.MESSAGE_NS, EndpointRouterMessage.MESSAGE_NAME)); - } - - if (lastFailure == null) { - lastFailure = new IOException("Could not find a route for : " + dest); - } - - // Except if we hit an illegal transport loop, we've exhausted all - // the options we had, or there was a RuntimeException. - // In both cases we must close. In the latter case it is a - // precaution: we're not 100% sure that the message is at fault; - // it could be this messenger as well. For illegal transport loops - // the invoking messenger should close, not this one. - - if (!(lastFailure instanceof IllegalStateException)) { - // FIXME - jice@jxta.org 20040413: as for all the transports. This used to be how this messenger broke itself. Now, - // all it does is too pretend that someone called for a nice close...just before the exception we throw causes the - // BlockingMessenger state machine to go into breackage mode. Ultimately transports should get a deeper retrofit. - close(); - } - - // Kind of stupid. Have to convert the runtime exceptions so that we - // can re-throw them. - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Messenger failed:", lastFailure); - } - - if (lastFailure instanceof IOException) { - throw (IOException) lastFailure; - } else if (lastFailure instanceof RuntimeException) { - throw (RuntimeException) lastFailure; - } else if (lastFailure instanceof Error) { - throw (Error) lastFailure; - } else { - IOException failure = new IOException("Failed sending " + message); - failure.initCause(lastFailure); - throw failure; - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/package.html deleted file mode 100644 index a20925af..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/router/package.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - -A JXTA {@link net.jxta.endpoint.MessageTransport} implementation which -simply translates addresses in messages from peer ids to physical Endpoint -Addresses. - -@see net.jxta.endpoint.EndpointService -@see net.jxta.endpoint.MessageTransport -@see net.jxta.endpoint.MessageSender -@see net.jxta.endpoint.MessageReceiver -@see net.jxta.endpoint.Message -@see JXTA Protocols - Specification : Standard JXTA Transport Bindings - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpClientMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpClientMessenger.java deleted file mode 100644 index 62dba706..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpClientMessenger.java +++ /dev/null @@ -1,917 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.servlethttp; - -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.SocketTimeoutException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.MimeMediaType; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.endpoint.WireFormatMessage; -import net.jxta.endpoint.WireFormatMessageFactory; - -import net.jxta.impl.endpoint.BlockingMessenger; -import net.jxta.impl.endpoint.EndpointServiceImpl; -import net.jxta.impl.endpoint.transportMeter.TransportBindingMeter; -import net.jxta.impl.endpoint.transportMeter.TransportMeterBuildSettings; -import net.jxta.impl.util.TimeUtils; - -/** - * Simple messenger that simply posts a message to a URL. - * - *

            URL/HttpURLConnection is used, so (depending on your JDK) you will get - * reasonably good persistent connection management. - */ -final class HttpClientMessenger extends BlockingMessenger { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(HttpClientMessenger.class.getName()); - - /** - * Minimum amount of time between poll - */ - private final static int MIMIMUM_POLL_INTERVAL = (int) (5 * TimeUtils.ASECOND); - - /** - * Amount of time to wait for connections to open. - */ - private final static int CONNECT_TIMEOUT = (int) (15 * TimeUtils.ASECOND); - - /** - * Amount of time we are willing to wait for responses. This is the amount - * of time between our finishing sending a message or beginning a poll and - * the beginning of receipt of a response. - */ - private final static int RESPONSE_TIMEOUT = (int) (2 * TimeUtils.AMINUTE); - - /** - * Amount of time we are willing to accept for additional responses. This - * is the total amount of time we are willing to wait after receiving an - * initial response message whether additional responses are sent or not. - * This setting governs the latency with which we switch back and forth - * between sending and receiving messages. - */ - private final static int EXTRA_RESPONSE_TIMEOUT = (int) (2 * TimeUtils.AMINUTE); - - /** - * Messenger idle timeout. - */ - private final static long MESSENGER_IDLE_TIMEOUT = 15 * TimeUtils.AMINUTE; - - /** - * Number of attempts we will attempt to make connections. - */ - private final static int CONNECT_RETRIES = 2; - - /** - * Warn only once about obsolete proxies. - */ - private static boolean neverWarned = true; - - /** - * The URL we send messages to. - */ - private final URL senderURL; - - /** - * The ServletHttpTransport that created this object. - */ - private final ServletHttpTransport servletHttpTransport; - - /** - * The Return Address element we will add to all messages we send. - */ - private final MessageElement srcAddressElement; - - /** - * The logical destination address of this messenger. - */ - private final EndpointAddress logicalDest; - - private TransportBindingMeter transportBindingMeter; - - /** - * The last time at which we successfully received or sent a message. - */ - private transient long lastUsed = TimeUtils.timeNow(); - - /** - * Poller that we use to get our messages. - */ - private MessagePoller poller = null; - - /** - * Constructs the messenger. - * - * @param servletHttpTransport The transport this messenger will work for. - * @param srcAddr The source address. - * @param destAddr The destination address. - */ - HttpClientMessenger(ServletHttpTransport servletHttpTransport, EndpointAddress srcAddr, EndpointAddress destAddr) throws IOException { - - // We do use self destruction. - super(servletHttpTransport.getEndpointService().getGroup().getPeerGroupID(), destAddr, true); - - this.servletHttpTransport = servletHttpTransport; - - EndpointAddress srcAddress = srcAddr; - this.srcAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NAME, srcAddr.toString(), null); - - String protoAddr = destAddr.getProtocolAddress(); - - String host; - int port; - int lastColon = protoAddr.lastIndexOf(':'); - - if ((-1 == lastColon) || (lastColon < protoAddr.lastIndexOf(']')) || ((lastColon + 1) == protoAddr.length())) { - // There's no port or it's an IPv6 addr with no port or the colon is the last character. - host = protoAddr; - port = 80; - } else { - host = protoAddr.substring(0, lastColon); - port = Integer.parseInt(protoAddr.substring(lastColon + 1)); - } - - senderURL = new URL("http", host, port, "/"); - - logicalDest = retreiveLogicalDestinationAddress(); - - // Start receiving messages from the other peer - poller = new MessagePoller(srcAddr.getProtocolAddress(), destAddr); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("New messenger : " + this ); - } - } - - /* - * The cost of just having a finalize routine is high. The finalizer is - * a bottleneck and can delay garbage collection all the way to heap - * exhaustion. Leave this comment as a reminder to future maintainers. - * Below is the reason why finalize is not needed here. - * - * These messengers (normally) never go to the application layer. Endpoint - * code does call close when necessary. - - protected void finalize() { - } - - */ - - /** - * {@inheritDoc} - *

            - * A simple implementation for debugging. Do not parse the String - * returned. All of the information is available in other (simpler) ways. - */ - public String toString() { - StringBuilder result = new StringBuilder(super.toString()); - result.append(" {"); - result.append(getDestinationAddress()); - result.append(" / "); - result.append(getLogicalDestinationAddress()); - result.append("}"); - - return result.toString(); - } - - /** - * {@inheritDoc} - */ - void doShutdown() { - super.shutdown(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void closeImpl() { - - if (isClosed()) { - return; - } - - super.close(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Close messenger to " + senderURL); - } - - MessagePoller stopPoller = poller; - - poller = null; - - if (null != stopPoller) { - stopPoller.stop(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void sendMessageBImpl(Message message, String service, String serviceParam) throws IOException { - - if (isClosed()) { - IOException failure = new IOException("Messenger was closed, it cannot be used to send messages."); - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Messenger was closed, it cannot be used to send messages.", failure); - } - - throw failure; - } - - // clone the message before modifying it. - message = message.clone(); - - // Set the message with the appropriate src and dest address - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NS, srcAddressElement); - - EndpointAddress destAddressToUse = getDestAddressToUse(service, serviceParam); - - MessageElement dstAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NAME, - destAddressToUse.toString(), null); - - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NS, dstAddressElement); - - try { - doSend(message); - } catch (IOException e) { - // close this messenger - close(); - // rethrow the exception - throw e; - } - } - - /** - * {@inheritDoc} - */ - @Override - public EndpointAddress getLogicalDestinationImpl() { - return logicalDest; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isIdleImpl() { - return isClosed() || (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), lastUsed) > MESSENGER_IDLE_TIMEOUT); - } - - /** - * Connects to the http server and retrieves the Logical Destination Address - */ - private EndpointAddress retreiveLogicalDestinationAddress() throws IOException { - long beginConnectTime = 0; - long connectTime = 0; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Ping (" + senderURL + ")"); - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - beginConnectTime = TimeUtils.timeNow(); - } - - // open a connection to the other end - HttpURLConnection urlConn = (HttpURLConnection) senderURL.openConnection(); - - urlConn.setRequestMethod("GET"); - urlConn.setDoOutput(true); - urlConn.setDoInput(true); - urlConn.setAllowUserInteraction(false); - urlConn.setUseCaches(false); - urlConn.setConnectTimeout(CONNECT_TIMEOUT); - urlConn.setReadTimeout(CONNECT_TIMEOUT); - - try { - // this is where the connection is actually made, if not already - // connected. If we can't connect, assume it is dead - int code = urlConn.getResponseCode(); - - if (code != HttpURLConnection.HTTP_OK) { - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - transportBindingMeter = servletHttpTransport.getTransportBindingMeter(null, getDestinationAddress()); - if (transportBindingMeter != null) { - transportBindingMeter.connectionFailed(true, TimeUtils.timeNow() - beginConnectTime); - } - } - - throw new IOException("Message not accepted: HTTP status " + "code=" + code + " reason=" + urlConn.getResponseMessage()); - } - - // check for a returned peerId - int msglength = urlConn.getContentLength(); - - if (msglength <= 0) { - throw new IOException("Ping response was empty."); - } - - InputStream inputStream = urlConn.getInputStream(); - - // read the peerId - byte[] uniqueIdBytes = new byte[msglength]; - int bytesRead = 0; - - while (bytesRead < msglength) { - int thisRead = inputStream.read(uniqueIdBytes, bytesRead, msglength - bytesRead); - - if (thisRead < 0) { - break; - } - - bytesRead += thisRead; - } - - if (bytesRead < msglength) { - throw new IOException("Content ended before promised Content length"); - } - - String uniqueIdString; - - try { - uniqueIdString = new String(uniqueIdBytes, "UTF-8"); - } catch (UnsupportedEncodingException never) { - // utf-8 is always available, but we handle it anyway. - uniqueIdString = new String(uniqueIdBytes); - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - connectTime = TimeUtils.timeNow(); - transportBindingMeter = servletHttpTransport.getTransportBindingMeter(uniqueIdString, getDestinationAddress()); - if (transportBindingMeter != null) { - transportBindingMeter.connectionEstablished(true, connectTime - beginConnectTime); - transportBindingMeter.ping(connectTime); - transportBindingMeter.connectionClosed(true, connectTime - beginConnectTime); - } - } - - EndpointAddress remoteAddress = new EndpointAddress("jxta", uniqueIdString.trim(), null, null); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Ping (" + senderURL + ") -> " + remoteAddress); - } - - return remoteAddress; - } catch (IOException failure) { - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - connectTime = TimeUtils.timeNow(); - transportBindingMeter = servletHttpTransport.getTransportBindingMeter(null, getDestinationAddress()); - if (transportBindingMeter != null) { - transportBindingMeter.connectionFailed(true, connectTime - beginConnectTime); - } - } - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Ping (" + senderURL + ") -> failed"); - } - - throw failure; - } - } - - /** - * Connects to the http server and POSTs the message - */ - private void doSend(Message msg) throws IOException { - long beginConnectTime = 0; - long connectTime = 0; - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - beginConnectTime = TimeUtils.timeNow(); - } - - WireFormatMessage serialed = WireFormatMessageFactory.toWire(msg, EndpointServiceImpl.DEFAULT_MESSAGE_TYPE, null); - - for (int connectAttempt = 1; connectAttempt <= CONNECT_RETRIES; connectAttempt++) { - if (connectAttempt > 1) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Retrying connection to " + senderURL); - } - } - // open a connection to the other end - HttpURLConnection urlConn = (HttpURLConnection) senderURL.openConnection(); - - try { - urlConn.setRequestMethod("POST"); - urlConn.setDoOutput(true); - urlConn.setDoInput(true); - urlConn.setAllowUserInteraction(false); - urlConn.setUseCaches(false); - urlConn.setConnectTimeout(CONNECT_TIMEOUT); - urlConn.setReadTimeout(CONNECT_TIMEOUT); - // FIXME 20040907 bondolo Should set message encoding http header. - urlConn.setRequestProperty("content-length", Long.toString(serialed.getByteLength())); - urlConn.setRequestProperty("content-type", serialed.getMimeType().toString()); - // send the message - OutputStream out = urlConn.getOutputStream(); - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - connectTime = TimeUtils.timeNow(); - transportBindingMeter.connectionEstablished(true, connectTime - beginConnectTime); - } - serialed.sendToStream(out); - out.flush(); - int responseCode; - - try { - responseCode = urlConn.getResponseCode(); - } catch (SocketTimeoutException expired) { - // maybe a retry will help. - continue; - } catch (IOException ioe) { - // Could not connect. This seems to happen a lot with a loaded HTTP 1.0 - // proxy. Apparently, HttpUrlConnection can be fooled by the proxy - // in believing that the connection is still open and thus breaks - // when attempting to make a second transaction. We should not have to but it - // seems that it befalls us to retry. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("HTTP 1.0 proxy seems in use"); - } - // maybe a retry will help. - continue; - } - - // NOTE: If the proxy closed the connection 1.0 style without returning - // a status line, we do not get an exception: we get a -1 response code. - // Apparently, proxies no-longer do that anymore. Just in case, we issue a - // warning and treat it as OK.71 - if (responseCode == -1) { - if (neverWarned && Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Obsolete HTTP proxy does not issue HTTP_OK response. Assuming OK"); - neverWarned = false; - } - responseCode = HttpURLConnection.HTTP_OK; - } - - if (responseCode != HttpURLConnection.HTTP_OK) { - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.dataSent(true, serialed.getByteLength()); - transportBindingMeter.connectionDropped(true, TimeUtils.timeNow() - beginConnectTime); - } - throw new IOException( "Message not accepted: HTTP status " + "code=" + responseCode + - " reason=" + urlConn.getResponseMessage()); - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - long messageSentTime = TimeUtils.timeNow(); - - transportBindingMeter.messageSent(true, msg, messageSentTime - connectTime, serialed.getByteLength()); - transportBindingMeter.connectionClosed(true, messageSentTime - beginConnectTime); - } - - // note that we successfully sent a message - lastUsed = TimeUtils.timeNow(); - - return; - } finally { - // This does prevent the creation of an infinite number of connections - // if we happen to be going through a 1.0-only proxy or connect to a server - // that still does not set content length to zero for the response. With this, at - // least we close them (they eventualy close anyway because the other side closes - // them but it takes too much time). If content-length is set, then jdk ignores - // the disconnect AND reuses the connection, which is what we want. - urlConn.disconnect(); - } - } - - throw new IOException("Failed sending " + msg + " to " + senderURL); - } - - /** - * Polls for messages sent to us. - */ - private class MessagePoller implements Runnable { - - /** - * If true then this poller is stopped or stopping. - */ - private volatile boolean stopped = false; - - /** - * The thread that does the work. - */ - private Thread pollerThread; - - /** - * The URL we poll for messages. - */ - private final URL pollingURL; - - MessagePoller(String pollAddress, EndpointAddress destAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("new MessagePoller for " + senderURL); - } - - /* - * query string is of the format ?{response timeout},{extra response timeout},{dest address} - * - * The timeout's are expressed in milliseconds. -1 means do not wait - * at all, 0 means wait forever. - */ - try { - pollingURL = new URL(senderURL, - "/" + pollAddress + - "?" + Integer.toString(RESPONSE_TIMEOUT) + "," + - Integer.toString(EXTRA_RESPONSE_TIMEOUT) + "," + - destAddr); - } catch (MalformedURLException badAddr) { - IllegalArgumentException failure = new IllegalArgumentException("Could not construct polling URL"); - - failure.initCause(badAddr); - - throw failure; - } - - pollerThread = new Thread(this, "HttpClientMessenger poller for " + senderURL); - pollerThread.setDaemon(true); - pollerThread.start(); - } - - protected void stop() { - if (stopped) { - return; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Stop polling for " + senderURL); - } - - stopped = true; - - // Here, we are forced to abandon this object open. Because we could - // get blocked forever trying to close it. It will rot away after - // the current read returns. The best we can do is interrupt the - // thread; unlikely to have an effect per the current. - // HttpURLConnection implementation. - - Thread stopPoller = pollerThread; - - if (null != stopPoller) { - stopPoller.interrupt(); - } - } - - /** - * Returns {@code true} if this messenger is stopped otherwise - * {@code false}. - * - * @return returns {@code true} if this messenger is stopped otherwise - * {@code false}. - */ - protected boolean isStopped() { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(this + " " + senderURL + " --> " + (stopped ? "stopped" : "running")); - } - - return stopped; - } - - /** - * {@inheritDoc} - * - *

            Connects to the http server and waits for messages to be received and processes them. - */ - public void run() { - try { - long beginConnectTime = 0; - long connectTime = 0; - long noReconnectBefore = 0; - HttpURLConnection conn = null; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Message polling beings for " + pollingURL); - } - - int connectAttempt = 1; - - // get messages until the messenger is closed - while (!isStopped()) { - if (conn == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Opening new connection to " + pollingURL); - } - - conn = (HttpURLConnection) pollingURL.openConnection(); // Incomming data channel - - conn.setRequestMethod("GET"); - conn.setDoOutput(false); - conn.setDoInput(true); - conn.setAllowUserInteraction(false); - conn.setUseCaches(false); - conn.setConnectTimeout(CONNECT_TIMEOUT); - conn.setReadTimeout(RESPONSE_TIMEOUT); - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - beginConnectTime = TimeUtils.timeNow(); - } - - // Loop back and try again to connect - continue; - } - - long untilNextConnect = TimeUtils.toRelativeTimeMillis(noReconnectBefore); - - try { - if (untilNextConnect > 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Delaying for " + untilNextConnect + "ms before reconnect to " + senderURL); - } - Thread.sleep(untilNextConnect); - } - } catch (InterruptedException woken) { - Thread.interrupted(); - continue; - } - - InputStream inputStream; - MimeMediaType messageType; - - try { - if (connectAttempt > 1) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Reconnect attempt for " + senderURL); - } - } - - // Always connect (no cost if connected). - conn.connect(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Waiting for response code from " + senderURL); - } - - int responseCode = conn.getResponseCode(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "Response " + responseCode + " for Connection : " + senderURL + "\n\tContent-Type : " - + conn.getHeaderField("Content-Type") + "\tContent-Length : " - + conn.getHeaderField("Content-Length") + "\tTransfer-Encoding : " - + conn.getHeaderField("Transfer-Encoding")); - } - - connectTime = TimeUtils.timeNow(); - noReconnectBefore = TimeUtils.toAbsoluteTimeMillis(MIMIMUM_POLL_INTERVAL, connectTime); - - if (0 == conn.getContentLength()) { - continue; - } - - if (HttpURLConnection.HTTP_NO_CONTENT == responseCode) { - // the connection timed out. - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.connectionClosed(true, TimeUtils.toRelativeTimeMillis(beginConnectTime, connectTime)); - } - - conn = null; - continue; - } - - if (responseCode != HttpURLConnection.HTTP_OK) { - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.connectionClosed(true, TimeUtils.timeNow() - beginConnectTime); - } - - throw new IOException("HTTP Failure: " + conn.getResponseCode() + " : " + conn.getResponseMessage()); - } - - String contentType = conn.getHeaderField("Content-Type"); - - if (null == contentType) { - // XXX 20051219 bondolo Figure out why the mime type is not always set. - messageType = EndpointServiceImpl.DEFAULT_MESSAGE_TYPE; - } else { - messageType = MimeMediaType.valueOf(contentType); - } - - // FIXME 20040907 bondolo Should get message content-encoding from http header. - - inputStream = conn.getInputStream(); - - // reset connection attempt. - connectAttempt = 1; - } catch (InterruptedIOException broken) { - // We don't know where it was interrupted. Restart connection. - Thread.interrupted(); - - if (connectAttempt > CONNECT_RETRIES) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unable to connect to " + senderURL); - } - - stop(); - break; - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Failed connecting to " + senderURL); - } - - if (null != conn) { - conn.disconnect(); - } - conn = null; - connectAttempt++; - continue; - } - } catch (IOException ioe) { - if (connectAttempt > CONNECT_RETRIES) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Unable to connect to " + senderURL, ioe); - } - - stop(); - break; - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Failed connecting to " + senderURL); - } - - if (null != conn) { - conn.disconnect(); - } - conn = null; - connectAttempt++; - continue; - } - } - - // start receiving messages - try { - while (!isStopped() - && (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), connectTime) < RESPONSE_TIMEOUT)) { - // read a message! - long messageReceiveStart = TimeUtils.timeNow(); - Message incomingMsg; - - incomingMsg = WireFormatMessageFactory.fromWire(inputStream, messageType, null); - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.messageReceived(true, incomingMsg, incomingMsg.getByteLength(), - TimeUtils.timeNow() - messageReceiveStart); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received " + incomingMsg + " from " + senderURL); - } - - servletHttpTransport.executor.execute(new MessageProcessor(incomingMsg)); - - // note that we received a message - lastUsed = TimeUtils.timeNow(); - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.connectionClosed(true, TimeUtils.timeNow() - beginConnectTime); - } - } catch (EOFException e) { - // Connection ran out of messages. let it go. - conn = null; - } catch (InterruptedIOException broken) { - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.connectionDropped(true, TimeUtils.timeNow() - beginConnectTime); - } - - // We don't know where it was interrupted. Restart connection. - Thread.interrupted(); - if (null != conn) { - conn.disconnect(); - } - conn = null; - } catch (IOException e) { - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.connectionDropped(true, TimeUtils.timeNow() - beginConnectTime); - } - - // If we managed to get down here, it is really an error. - // However, being disconnected from the server, for - // whatever reason, is a common place event. No need to - // clutter the screen with scary messages. When the - // message layer believes it's serious, it prints the - // scary message already. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Failed to read message from " + senderURL, e); - } - // Time to call this connection dead. - stop(); - break; - } finally { - try { - inputStream.close(); - } catch (IOException ignored) { - //ignored - } - } - } - } catch (Throwable argh) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Poller exiting because of uncaught exception", argh); - } - stop(); - } finally { - pollerThread = null; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Message polling stopped for " + senderURL); - } - } - } - - /** - * A small class for processing individual messages. - */ - private class MessageProcessor implements Runnable { - - private Message msg; - - MessageProcessor(Message msg) { - this.msg = msg; - } - - public void run() { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Demuxing " + msg + " from " + senderURL); - } - - servletHttpTransport.getEndpointService().demux(msg); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpMessageReceiver.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpMessageReceiver.java deleted file mode 100644 index ad8ab55d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpMessageReceiver.java +++ /dev/null @@ -1,404 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.servlethttp; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.net.InetAddress; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; - -import java.io.IOException; -import java.io.FileNotFoundException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import org.mortbay.http.HttpContext; -import org.mortbay.http.HttpServer; -import org.mortbay.http.SocketListener; -import org.mortbay.http.handler.ResourceHandler; -import org.mortbay.jetty.servlet.ServletHandler; -import org.mortbay.util.InetAddrPort; -import org.mortbay.util.Log; -import org.mortbay.util.LoggerLogSink; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.MessageReceiver; -import net.jxta.endpoint.MessengerEvent; -import net.jxta.endpoint.MessengerEventListener; - -import net.jxta.exception.PeerGroupException; - -import net.jxta.impl.util.TimeUtils; - -/** - * Simple Message Receiver for server side. - */ -class HttpMessageReceiver implements MessageReceiver { - - /** - * logger - */ - private final static transient Logger LOG = Logger.getLogger(HttpMessageReceiver.class.getName()); - - /** - * the relative URI of where the message receiver servlet will be mounted. - */ - private final static String MSG_RECEIVER_RELATIVE_URI = "/*"; - - /** - * The ServletHttpTransport that created this MessageReceiver. - */ - final ServletHttpTransport servletHttpTransport; - - /** - * The public addresses for the this transport. - */ - private final List publicAddresses; - - /** - * The min threads that the HTTP server will use for handling requests. - */ - private static int MIN_LISTENER_THREADS = 10; - - /** - * The max threads that the HTTP server will use for handling requests. - */ - private static int MAX_LISTENER_THREADS = 200; - - /** - * How long a thread can remain idle until the worker thread is let go. - */ - private static long MAX_THREAD_IDLE_DURATION = 30 * TimeUtils.ASECOND; - - /** - * The Jetty HTTP Server instance. - */ - private final HttpServer server; - private final ServletHandler handler; - private final SocketListener listener; - - /** - * The listener to invoke when making an incoming messenger. - */ - private MessengerEventListener messengerEventListener; - - public HttpMessageReceiver(ServletHttpTransport servletHttpTransport, List publicAddresses, InetAddress useInterface, int port) throws PeerGroupException { - this.servletHttpTransport = servletHttpTransport; - this.publicAddresses = publicAddresses; - - // read settings from the properties file - Properties prop = getJxtaProperties( - new File(new File(servletHttpTransport.getEndpointService().getGroup().getStoreHome()), "jxta.properties")); - initFromProperties(prop); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring HTTP Servlet Message Transport : " + servletHttpTransport.assignedID); - - configInfo.append("\n\tMin threads=").append(MIN_LISTENER_THREADS); - configInfo.append("\n\tMax threads=").append(MAX_LISTENER_THREADS); - configInfo.append("\n\tMax thread idle time=").append(MAX_THREAD_IDLE_DURATION).append("ms"); - - LOG.config(configInfo.toString()); - } - - // Configure Jetty Logging - if (!(Logging.SHOW_FINER && LOG.isLoggable(Level.FINER))) { - Log.instance().disableLog(); - } - - org.mortbay.util.Code.setDebug(Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)); - org.mortbay.util.Code.setSuppressWarnings(!(Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING))); - org.mortbay.util.Code.setSuppressStack(!(Logging.SHOW_FINER && LOG.isLoggable(Level.FINER))); - - // Setup the logger to match the rest of JXTA unless explicitly configured. - // "LOG_CLASSES" is a Jetty thing. - if (System.getProperty("LOG_CLASSES") == null) { - LoggerLogSink logSink = new LoggerLogSink(); - Logger jettyLogger = Logger.getLogger(org.mortbay.http.HttpServer.class.getName()); - - logSink.setLogger(jettyLogger); - try { - logSink.start(); - Log.instance().add(logSink); - } catch (Exception ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not configure LoggerLogSink"); - } - } - } - - // Initialize the Jetty HttpServer - server = new HttpServer(); - - // Create the listener and attach it to server. - InetAddrPort addrPort = new InetAddrPort(useInterface, port); - - listener = new SocketListener(addrPort); - - listener.setMinThreads(MIN_LISTENER_THREADS); - listener.setMaxThreads(MAX_LISTENER_THREADS); - listener.setMaxIdleTimeMs((int) MAX_THREAD_IDLE_DURATION); - - server.addListener(listener); - - // Create a context for the handlers at the root, then add servlet - // handler for the specified servlet class and add it to the context - HttpContext handlerContext = server.getContext("/"); - - handler = new ServletHandler(); - - handler.setUsingCookies(false); - handler.initialize(handlerContext); - - // Use peer group class loader (useful for HttpMessageServlet) - handlerContext.setClassLoader(servletHttpTransport.getEndpointService().getGroup().getLoader()); - handlerContext.addHandler(handler); - - // Set up support for downloading midlets. - if (System.getProperty("net.jxta.http.allowdownload") != null) { - HttpContext context = server.addContext("/midlets/*"); - - context.setResourceBase("./midlets/"); - // context.setDirAllowed(false); - // context.setServingResources(true); - - // String methods[] = {"GET"}; - ResourceHandler resHandler = new ResourceHandler(); - - // resHandler.setAllowedMethods(methods); - context.addHandler(resHandler); - } - - handler.addServlet(MSG_RECEIVER_RELATIVE_URI, HttpMessageServlet.class.getName()); - } - - synchronized void start() throws PeerGroupException { - try { - server.start(); - handler.getServletContext().setAttribute("HttpMessageReceiver", this); - } catch (Exception e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not start server", e); - } - PeerGroupException failure = new PeerGroupException("Could not start server"); - failure.initCause(e); - throw failure; - } - - messengerEventListener = servletHttpTransport.getEndpointService().addMessageTransport(this); - if (messengerEventListener == null) { - throw new PeerGroupException("Transport registration refused"); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("HTTP Servlet Transport started."); - } - } - - synchronized void stop() { - servletHttpTransport.getEndpointService().removeMessageTransport(this); - messengerEventListener = null; - - try { - server.stop(); - } catch (InterruptedException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Interrupted during stop()", e); - } - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("HTTP Servlet Transport stopped."); - } - } - - /** - * {@inheritDoc} - */ - boolean messengerReadyEvent(HttpServletMessenger newMessenger, EndpointAddress connAddr) { - MessengerEventListener temp = messengerEventListener; - - return null != temp && temp.messengerReady(new MessengerEvent(this, newMessenger, connAddr)); - } - - /** - * {@inheritDoc} - */ - public Iterator getPublicAddresses() { - return Collections.unmodifiableList(publicAddresses).iterator(); - } - - /** - * {@inheritDoc} - */ - public String getProtocolName() { - return servletHttpTransport.HTTP_PROTOCOL_NAME; - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - return servletHttpTransport.getEndpointService(); - } - - /** - * {@inheritDoc} - */ - public Object transportControl(Object operation, Object Value) { - return null; - } - - ServletHttpTransport getServletHttpTransport() { - return servletHttpTransport; - } - - /** - * Returns a Properties instance for jxta.properties if the file exists; - * otherwise, returns null. - * - * @param fromFile properties file - * @return the properties object or null if properties file was not found - */ - private static Properties getJxtaProperties(File fromFile) { - Properties prop = new Properties(); - InputStream in = null; - - try { - in = new FileInputStream(fromFile); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Read properties from " + fromFile.getPath()); - } - } catch (FileNotFoundException e) { - return null; - } - - try { - prop.load(in); - } catch (IOException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Error reading " + fromFile.getPath(), e); - } - } finally { - try { - in.close(); - } catch (IOException ignored) { - //ignored - } - in = null; - } - return prop; - } - - /** - * Reads the properties from the jxta.properties file - * - * @param prop properties to init from - */ - private void initFromProperties(Properties prop) { - - if (prop == null) { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.fine("jxta.properties not found: using default values"); - } - } else { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Using jxta.properties to configure HTTP server"); - } - - String minThreadsStr = prop.getProperty("HttpServer.MinThreads"); - String maxThreadsStr = prop.getProperty("HttpServer.MaxThreads"); - String maxThreadIdleTimeStr = prop.getProperty("HttpServer.MaxThreadIdleTime"); - - try { - if (minThreadsStr != null) { - MIN_LISTENER_THREADS = Integer.parseInt(minThreadsStr); - } - } catch (NumberFormatException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Invalid HttpServer.MinThreads value; using default"); - } - } - - try { - if (maxThreadsStr != null) { - MAX_LISTENER_THREADS = Integer.parseInt(maxThreadsStr); - } - } catch (NumberFormatException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Invalid HttpServer.MaxThreads value; using default"); - } - } - - try { - if (maxThreadIdleTimeStr != null) { - MAX_THREAD_IDLE_DURATION = Integer.parseInt(maxThreadIdleTimeStr); - } - } catch (NumberFormatException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Invalid HttpServer.MaxThreadIdleTime value; using default"); - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpMessageSender.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpMessageSender.java deleted file mode 100644 index 72b07d07..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpMessageSender.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.servlethttp; - -import java.util.Iterator; -import java.util.Map; -import java.util.WeakHashMap; - -import java.net.SocketTimeoutException; -import java.net.ConnectException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageSender; -import net.jxta.endpoint.Messenger; - -import net.jxta.exception.PeerGroupException; - -/** - * Simple Client MessageSender - */ -class HttpMessageSender implements MessageSender { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(HttpMessageSender.class.getName()); - - /** - * The ServletHttpTransport that created this object - */ - private final ServletHttpTransport servletHttpTransport; - - /** - * The public address for this message sender - */ - private final EndpointAddress publicAddress; - - /** - * The Set of active messengers. We keep track so that we can aggressively - * close the Messengers when the transport is shut down. - */ - private final Map messengers = new WeakHashMap(); - - /** - * constructor - */ - public HttpMessageSender(ServletHttpTransport servletHttpTransport, EndpointAddress publicAddress) throws PeerGroupException { - - this.servletHttpTransport = servletHttpTransport; - this.publicAddress = publicAddress; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder( "Configuring HTTP Client Message Transport : " + servletHttpTransport.assignedID); - - configInfo.append("\n\tPublic Address = ").append(publicAddress); - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public EndpointAddress getPublicAddress() { - return publicAddress; - } - - /** - * {@inheritDoc} - */ - public boolean isConnectionOriented() { - return true; - } - - /** - * {@inheritDoc} - */ - public boolean allowsRouting() { - return true; - } - - /** - * {@inheritDoc} - */ - public Object transportControl(Object operation, Object Value) { - return null; - } - - /** - * shut down all client connections. - */ - public synchronized void start() throws PeerGroupException { - if (servletHttpTransport.getEndpointService().addMessageTransport(this) == null) { - throw new PeerGroupException("Transport registration refused"); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("HTTP Client Transport started."); - } - } - - /** - * shut down all client connections. - */ - public synchronized void stop() { - synchronized (messengers) { - Iterator eachMessenger = messengers.keySet().iterator(); - - while (eachMessenger.hasNext()) { - HttpClientMessenger aMessenger = eachMessenger.next(); - - eachMessenger.remove(); - - aMessenger.doShutdown(); - } - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("HTTP Client Transport stopped."); - } - } - - /** - * {@inheritDoc} - */ - public Messenger getMessenger(EndpointAddress destAddr, Object hintIgnored) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("getMessenger for : " + destAddr); - } - - if (!getProtocolName().equals(destAddr.getProtocolName())) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Cannot make messenger for protocol :" + destAddr.getProtocolName()); - } - - return null; - } - - try { - // Right now we do not want to "announce" outgoing messengers - // because they get pooled and so must not be grabbed by a listener. - // If "announcing" is to be done, that should be by the endpoint - // and probably with a subtly different interface. - - HttpClientMessenger result = new HttpClientMessenger(servletHttpTransport, publicAddress, destAddr); - - synchronized (messengers) { - messengers.put(result, null); - } - - return result; - } catch (SocketTimeoutException noConnect) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not connect to " + destAddr + " : " + noConnect.getMessage()); - } - } catch (ConnectException noConnect) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed to connect to " + destAddr + " : " + noConnect.getMessage()); - } - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not make messenger for " + destAddr, e); - } - } - - // If we got here, we failed. - return null; - } - - /** - * {@inheritDoc} - */ - public boolean ping(EndpointAddress addr) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Using http client sender to ping " + addr); - } - - Messenger messenger = getMessenger(addr, null); - - // XXX pool this messenger. - // Ping obsolete. And do not announce an outgoing messenger - - boolean pong = 0 != (Messenger.USABLE & messenger.getState()); - - messenger.close(); - - return pong; - } - - /** - * {@inheritDoc} - */ - public String getProtocolName() { - return servletHttpTransport.HTTP_PROTOCOL_NAME; - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - return servletHttpTransport.getEndpointService(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpMessageServlet.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpMessageServlet.java deleted file mode 100644 index 8a1a7093..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpMessageServlet.java +++ /dev/null @@ -1,908 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.servlethttp; - -import java.io.InputStream; -import java.io.OutputStream; -// import java.util.Enumeration; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Enumeration; -import java.util.NoSuchElementException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.Cookie; -// import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.linphone.p2pproxy.core.jxtaext.EndpointRegistry; - -import net.jxta.document.MimeMediaType; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.WireFormatMessage; -import net.jxta.endpoint.WireFormatMessageFactory; - -import net.jxta.impl.endpoint.EndpointServiceImpl; -import net.jxta.impl.endpoint.transportMeter.TransportBindingMeter; -import net.jxta.impl.endpoint.transportMeter.TransportMeterBuildSettings; -import net.jxta.impl.util.TimeUtils; - -/** - * This is a simple servlet that accepts JXTA Messages from clients using HTTP - * via {@code POST}. In addition to receiving messages via {@code POST} - * responses clients can also poll for messages using {@code GET}. - * - *

            It also supports a ping operation. When the URI is / the - * response consists of the unique value portion of the local peer id. - */ -public class HttpMessageServlet extends HttpServlet { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(HttpMessageServlet.class.getName()); - - /** - * The maximum duration in milliseconds we will keep a connection alive - * while generating a response. - */ - private final static long MAXIMUM_RESPONSE_DURATION = 2 * TimeUtils.AMINUTE; - - /** - * Owner of this servlet. - */ - private HttpMessageReceiver owner = null; - - /** - * The endpoint that the owner message transport is registered with. - */ - private EndpointService endpoint = null; - - /** - * Our address. - */ - private EndpointAddress localAddress = null; - private byte[] pingResponseBytes; - - private ServletHttpTransport servletHttpTransport = null; - - /** - * If {@code true} then this servlet has been (or is being) destroyed. - */ - private volatile boolean destroyed = false; - - /** - * Recovers the Message Transport which owns this servlet from the context - * information. - */ - @Override - public void init(ServletConfig config) throws ServletException { - super.init(config); - - try { - owner = (HttpMessageReceiver) getServletContext().getAttribute("HttpMessageReceiver"); - if (owner == null) { - throw new ServletException("Servlet Context did not contain 'HttpMessageReceiver'"); - } - } catch (ClassCastException e) { - throw new ServletException("'HttpMessageReceiver' attribute was not of the proper type in the Servlet Context"); - } - - servletHttpTransport = owner.servletHttpTransport; - endpoint = owner.getEndpointService(); - - String peerId = endpoint.getGroup().getPeerID().getUniqueValue().toString(); - - localAddress = new EndpointAddress("jxta", peerId, null, null); - - try { - pingResponseBytes = peerId.getBytes("UTF-8"); - } catch (java.io.UnsupportedEncodingException never) { - // UTF-8 is always available. - } - } - - /** - * {@inheritDoc} - */ - @Override - public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("GET " + req.getRequestURI() + " thread = " + Thread.currentThread()); - } - - processRequest(req, res); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("GET done for thread = " + Thread.currentThread()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("POST " + req.getRequestURI() + " thread = " + Thread.currentThread()); - } - - processRequest(req, res); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("POST done for thread = " + Thread.currentThread()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void destroy() { - // All we need to do is wakeup the threads that are waiting. (In truth - // we'll miss those that are waiting on a messenger, but that'll do for - // now, because we do that only when shutting down the group and then - // the relay will be shutdown as well, which will take care of the - // messengers. - destroyed = true; - notifyAll(); - } - - /** - * Handle a request and optionally generate a response. - * - * @param req The request we are being asked to process. - * @param res The response we should use for any response. - * @throws IOException For failures in IO processing. - */ - private void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException { - - long lastReadWriteTime; - int requestSize = 0; - TransportBindingMeter transportBindingMeter = null; - - if (Logging.SHOW_FINEST && LOG.isLoggable(Level.FINEST)) { - printRequest(req); - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - int contentLength = req.getContentLength(); - - requestSize += (contentLength != -1) ? contentLength : 0; - } - - JxtaRequest currentRequest = new JxtaRequest(req); - - /* - * We accept three request formats: - * - * o PING : no Message and no Requestor defined. - * o POLL : Requestor defined, positive response timeout and destination address. - * o SEND : Requestor defined, positive response timeout or no destination address. - */ - - // check if this is a ping request, no requestor peerId or incoming message - if (null == currentRequest.requestorAddr && !currentRequest.messageContent) { - // this is only a ping request - pingResponse(res); - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - long connectionTime = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), currentRequest.requestStartTime); - EndpointAddress sourceAddress = new EndpointAddress("http", req.getRemoteHost(), null, null); // - - transportBindingMeter = servletHttpTransport.getTransportBindingMeter(null, sourceAddress); - if (transportBindingMeter != null) { - transportBindingMeter.connectionEstablished(false, currentRequest.requestStartTime); - transportBindingMeter.dataReceived(false, requestSize); - transportBindingMeter.dataSent(false, 0); - transportBindingMeter.pingReceived(); - transportBindingMeter.connectionClosed(false, connectionTime); - } - } - - return; - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - lastReadWriteTime = TimeUtils.timeNow(); - long connectTime = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), currentRequest.requestStartTime); - EndpointAddress sourceAddress = new EndpointAddress("http", req.getRemoteHost(), null, null); // - - if (null != currentRequest.requestorAddr) { - transportBindingMeter = servletHttpTransport.getTransportBindingMeter(currentRequest.requestorAddr.toString(), - sourceAddress); - } else { - transportBindingMeter = servletHttpTransport.getTransportBindingMeter(req.getRemoteHost(), sourceAddress); - } - if (transportBindingMeter != null) { - transportBindingMeter.connectionEstablished(false, connectTime); - transportBindingMeter.dataReceived(false, requestSize); - } - } - - // check if the request included polling (valid requestor peerId and timeout not -1) - HttpServletMessenger messenger = null; - - if ((null != currentRequest.requestorAddr) && (currentRequest.responseTimeout >= 0) && (null != currentRequest.destAddr)) { - // create the back channel messenger - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( "Creating back channel messenger for " + currentRequest.requestorAddr + " (" + currentRequest.destAddr + ")"); - } - - long messengerAliveFor; - - if (0 == currentRequest.responseTimeout) { - messengerAliveFor = 0; - } else { - messengerAliveFor = Math.max(currentRequest.responseTimeout, currentRequest.extraResponsesTimeout); - } - - messenger = new HttpServletMessenger(owner.servletHttpTransport.group.getPeerGroupID(), localAddress, - currentRequest.requestorAddr, messengerAliveFor); - boolean taken = owner.messengerReadyEvent(messenger, currentRequest.destAddr); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Incoming messenger to: " + currentRequest.requestorAddr + " taken=" + taken); - } - - if (!taken) { - // nobody cares. Just destroy it. - messenger.close(); - messenger = null; - } - } - - // We may later decide that contentLength should not be set after all - // if we use chunking. Otherwise we must set it; specially to zero, so - // that jetty does not forcefully close the connection after each - // message in order to complete the transaction http-1.0-style. - - boolean mustSetContentLength = true; - - try { - // get the incoming message is there is one - if (currentRequest.messageContent) { - Message incomingMessage; - - // read the stream - InputStream in = req.getInputStream(); - - // construct the message. Send BAD_REQUEST if the message construction - // fails - try { - String contentType = req.getContentType(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Reading message from request : " + contentType); - } - - MimeMediaType contentMimeType = EndpointServiceImpl.DEFAULT_MESSAGE_TYPE; - - if (null != contentType) { - contentMimeType = MimeMediaType.valueOf(contentType); - } - - // FIXME 20040927 bondolo Should get message encoding from http header. - try { - incomingMessage = WireFormatMessageFactory.fromWire(in, contentMimeType, null); - } catch (NoSuchElementException noValidWireFormat) { - IOException failure = new IOException("Unrecognized content type MIME type : " + contentType); - - failure.initCause(noValidWireFormat); - throw failure; - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - lastReadWriteTime = TimeUtils.timeNow(); - long receiveTime = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), currentRequest.requestStartTime); - - transportBindingMeter.messageReceived(false, incomingMessage, receiveTime, 0); // size=0 since it was already incorporated in the request size - } - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Malformed JXTA message, responding with BAD_REQUEST", e); - } - - res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Message was not a valid JXTA message"); - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.connectionDropped(false, - TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), currentRequest.requestStartTime)); - } - return; - } - - // post the incoming message to the endpoint demux - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Handing " + incomingMessage + " to the endpoint."); - } - - try { - endpoint.demux(incomingMessage); - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure demuxing an incoming message", e); - } - } - } - - boolean beganResponse = false; - - // Check if the back channel is to be used for sending messages. - if ((currentRequest.responseTimeout >= 0) && (null != messenger)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Wait for message from the messenger. timeout = " + currentRequest.responseTimeout); - } - - long quitAt = (currentRequest.responseTimeout == 0) - ? Long.MAX_VALUE - : TimeUtils.toAbsoluteTimeMillis(currentRequest.requestStartTime, currentRequest.responseTimeout); - - while ((0 != (messenger.getState() & Messenger.USABLE)) && !destroyed) { - long remaining = TimeUtils.toRelativeTimeMillis(quitAt); - - if ((remaining <= 0)) { - // done processing the request - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Terminating expired request."); - } - - // We know we did not respond anything. - // In general it's better if jetty closes the connection - // here, because it could have been an unused - // back-channel and the client has to open a new one - // next time, thus making sure we get to see a different - // URL (if applicable). JDK should do that anyway, - // but ...). - break; - } - - Message outMsg; - - // Send a message if there is one - try { - outMsg = messenger.waitForMessage(remaining); - } catch (InterruptedException ie) { - // Ok. Leave early, then. - Thread.interrupted(); - continue; - } - - if (outMsg == null) { - // done processing the request - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Terminating request with no message to send."); - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.connectionClosed(false, - TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), currentRequest.requestStartTime)); - } - - // We know we did not respond anything. Do not set - // content-length In general it's better if jetty closes - // the connection here, because it could have been an - // unused back-channel and the client has to open a new - // one next time, thus making sure we get to see a - // different URL (if applicable). JDK should do that - // anyway, but ...). - break; - } - - long startMessageSend = TimeUtils.timeNow(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + outMsg + " on back channel to " + req.getRemoteHost()); - } - - if (!beganResponse) { - // valid request, send back OK response - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending OK in response to request"); - } - - beganResponse = true; - res.setStatus(HttpServletResponse.SC_OK); - res.setContentType(EndpointServiceImpl.DEFAULT_MESSAGE_TYPE.toString()); - } - - // send the message - WireFormatMessage serialed = WireFormatMessageFactory.toWire(outMsg, EndpointServiceImpl.DEFAULT_MESSAGE_TYPE, null); - - // if only one message is being returned, set the content - // length, otherwise try to use chunked encoding. - if (currentRequest.extraResponsesTimeout < 0) { - res.setContentLength((int) serialed.getByteLength()); - } - - // Either way, we've done what had to be done. - mustSetContentLength = false; - - // get the output stream for the response - OutputStream out = res.getOutputStream(); - - // send the message - try { - serialed.sendToStream(out); - out.flush(); - - messenger.messageSent(true); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Successfully sent " + outMsg + " on back channel to " + req.getRemoteHost()); - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - lastReadWriteTime = TimeUtils.timeNow(); - long sendTime = TimeUtils.toRelativeTimeMillis(lastReadWriteTime, startMessageSend); - long bytesSent = serialed.getByteLength(); - - transportBindingMeter.messageSent(false, outMsg, sendTime, bytesSent); - } - } catch (IOException ex) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Failed sending Message on back channel to " + req.getRemoteHost()); - } - - messenger.messageSent(false); - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.connectionDropped(false, - TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), currentRequest.requestStartTime)); - } - - throw ex; - } finally { - // make sure the response is pushed out - res.flushBuffer(); - } - - // Adjust the quit time based upon the extra response time available. - if (0 == currentRequest.extraResponsesTimeout) { - quitAt = Long.MAX_VALUE; - } else { - quitAt = TimeUtils.toAbsoluteTimeMillis(currentRequest.requestStartTime, currentRequest.extraResponsesTimeout); - } - - // If we never generated a response then make it clear we gave up waiting. - if (!beganResponse) { - res.setStatus(HttpServletResponse.SC_NO_CONTENT); - } - } - } else { - // No response was desired. - res.setStatus(HttpServletResponse.SC_OK); - } - } finally { - // close the messenger - if (null != messenger) { - messenger.close(); - } - } - - // If contentLength was never set and we have not decided *not* to set - // it, then we must set it to 0 (that's the truth in that case). This - // allows Jetty to keep to keep the connection open unless what's on the - // other side is a 1.0 proxy. - if (mustSetContentLength) { - res.setContentLength(0); - } - - // make sure the response is pushed out - res.flushBuffer(); - - // done processing the request - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Finished processing the request from " + req.getRemoteHost()); - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.connectionClosed(false, - TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), currentRequest.requestStartTime)); - } - } - - /** - * Returns a response to a ping request. The response is the PeerID of - * this peer. - * - * @param res The response to which the ping result should be sent. - */ - private void pingResponse(HttpServletResponse res) throws IOException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Responding to \'ping\' request with 200 and peerID"); - } - - res.setStatus(HttpServletResponse.SC_OK); - - res.setContentLength(pingResponseBytes.length); - res.setContentType(MimeMediaType.TEXTUTF8.toString()); - - OutputStream out = res.getOutputStream(); - - out.write(pingResponseBytes); - out.flush(); - out.close(); - } - - /** - * Debugging output. - */ - private static void printRequest(HttpServletRequest req) { - final char nl = '\n'; - StringBuilder builder = new StringBuilder(); - - builder.append("HTTP request:" + nl); - builder.append(" AUTH_TYPE: ").append(req.getAuthType()).append(nl); - builder.append(" CONTEXT_PATH: ").append(req.getContextPath()).append(nl); - - Cookie[] cookies = req.getCookies(); - - if (cookies != null) { - for (int i = 0; i < cookies.length; i++) { - builder.append(" COOKIE[").append(i).append("]:" + nl); - builder.append(" comment: ").append(cookies[i].getComment()).append(nl); - builder.append(" domain: ").append(cookies[i].getDomain()).append(nl); - builder.append(" max age: ").append(cookies[i].getMaxAge()).append(nl); - builder.append(" name: ").append(cookies[i].getName()).append(nl); - builder.append(" path: ").append(cookies[i].getPath()).append(nl); - builder.append(" secure: ").append(cookies[i].getSecure()).append(nl); - builder.append(" value: ").append(cookies[i].getValue()).append(nl); - builder.append(" version: ").append(cookies[i].getVersion()).append(nl); - } - } - - for (Enumeration headers = req.getHeaderNames(); headers.hasMoreElements();) { - String header = (String) headers.nextElement(); - builder.append(" HEADER[").append(header).append("]: ").append(req.getHeader(header)).append(nl); - } - - builder.append(" METHOD: ").append(req.getMethod()).append(nl); - builder.append(" PATH_INFO: ").append(req.getPathInfo()).append(nl); - builder.append(" PATH_TRANSLATED: ").append(req.getPathTranslated()).append(nl); - builder.append(" QUERY_STRING: ").append(req.getQueryString()).append(nl); - builder.append(" REMOTE_USER: ").append(req.getRemoteUser()).append(nl); - builder.append(" REQUESTED_SESSION_ID: ").append(req.getRequestedSessionId()).append(nl); - builder.append(" REQUEST_URI: ").append(req.getRequestURI()).append(nl); - builder.append(" SERVLET_PATH: ").append(req.getServletPath()).append(nl); - builder.append(" REMOTE_USER: ").append(req.getRemoteUser()).append(nl); - builder.append(" isSessionIdFromCookie: ").append(req.isRequestedSessionIdFromCookie()).append(nl); - builder.append(" isSessionIdFromURL: ").append(req.isRequestedSessionIdFromURL()).append(nl); - builder.append(" isSessionIdValid: ").append(req.isRequestedSessionIdValid()).append(nl); - - for (Enumeration attributes = req.getAttributeNames(); attributes.hasMoreElements();) { - String attribute = (String) attributes.nextElement(); - builder.append(" ATTRIBUTE[").append(attribute).append("]: ").append(req.getAttribute(attribute)).append(nl); - } - - builder.append(" ENCODING: ").append(req.getCharacterEncoding()).append(nl); - builder.append(" CONTENT_LENGTH: ").append(req.getContentLength()).append(nl); - builder.append(" CONTENT_TYPE: ").append(req.getContentType()).append(nl); - builder.append(" LOCALE: ").append(req.getLocale().toString()).append(nl); - - for (Enumeration parameters = req.getParameterNames(); parameters.hasMoreElements();) { - String parameter = (String) parameters.nextElement(); - builder.append(" PARAMETER[").append(parameter).append("]: ").append(req.getParameter(parameter)).append(nl); - } - - builder.append(" PROTOCOL: ").append(req.getProtocol()).append(nl); - builder.append(" REMOTE_ADDR: ").append(req.getRemoteAddr()).append(nl); - builder.append(" REMOTE_HOST: ").append(req.getRemoteHost()).append(nl); - builder.append(" SCHEME: ").append(req.getScheme()).append(nl); - builder.append(" SERVER_NAME: ").append(req.getServerName()).append(nl); - builder.append(" SERVER_PORT: ").append(req.getServerPort()).append(nl); - builder.append(" isSecure: ").append(req.isSecure()); - - LOG.finest(builder.toString()); - } - - /** - * A servlet request. - * - * @see JXTA Protocols Specification : Standard JXTA Transport Bindings : HTTP Bindings - */ - private static class JxtaRequest { - - /** - * Absolute time in milliseconds at which this request began processing. - */ - final long requestStartTime; - - /** - * Endpoint address of the requestor. - */ - final EndpointAddress requestorAddr; - - /** - * Duration of time to wait for the initial response message. - * - *

              - *
            • <0 : No response message wanted.
            • - *
            • 0 : Wait indefinitely for response message.
            • - *
            • >0 : Wait specified amount of time for response message.
            • - *
            - */ - final long responseTimeout; - - /** - * Duration of time to wait for additional response messages. - * - *

              - *
            • <0 : No additional response messages wanted.
            • - *
            • 0 : Wait indefinitely for additional response messages.
            • - *
            • >0 : Wait specified amount of time for additional response messages.
            • - *
            - */ - final long extraResponsesTimeout; - - /** - * Destination address for messages sent in this connection. - */ - final EndpointAddress destAddr; - - /** - * If true then the requestor is providing a Message. - */ - final boolean messageContent; - - /** - * Construct a request. - */ - JxtaRequest(HttpServletRequest req) { - - requestStartTime = TimeUtils.timeNow(); - - // check if a peerId was given - String requestorPeerId = getRequestorPeerId(req); - - if (null != requestorPeerId) { - requestorAddr = new EndpointAddress("jxta", requestorPeerId, null, null); - try { - EndpointRegistry.getInstance().add("urn:jxta:"+requestorPeerId, InetAddress.getByName(req.getRemoteHost())); - } catch (UnknownHostException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING,"cannot register ["+requestorPeerId+"]", e); - } - } - } else { - requestorAddr = null; - } - - // get the query string - String queryString = req.getQueryString(); - - if (queryString != null) { - // the query string is of the format responseTimeout,extraResponsesTimeout,destAdd - // the times given are in milliseconds - int commaIndex = queryString.indexOf(','); - - if (commaIndex == -1) { - // there is no extra responses timeout - responseTimeout = getResponseTimeout(queryString); - extraResponsesTimeout = -1; - destAddr = null; - } else { - responseTimeout = getResponseTimeout(queryString.substring(0, commaIndex)); - - String moreQueryParams = queryString.substring(commaIndex + 1); - - commaIndex = moreQueryParams.indexOf(','); - if (commaIndex == -1) { - extraResponsesTimeout = getExtraResponsesTimeout(moreQueryParams); - destAddr = null; - } else { - extraResponsesTimeout = getExtraResponsesTimeout(moreQueryParams.substring(0, commaIndex)); - destAddr = new EndpointAddress(moreQueryParams.substring(commaIndex + 1)); - } - } - } else { - responseTimeout = 0; - extraResponsesTimeout = -1; - destAddr = null; - } - - // check for incoming message - messageContent = hasMessageContent(req); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer( - "New JXTA Request for Requestor=" + requestorAddr + "\n\tResponse Timeout=" + responseTimeout - + "\tAdditional Response Timeout=" + extraResponsesTimeout + "\tRequest Destination Address=" + destAddr - + "\tHas Message Content=" + Boolean.toString(messageContent)); - } - } - - /** - * Returns the peerId of the peer making the request, if given - */ - private static String getRequestorPeerId(HttpServletRequest req) { - // get the potential PeerId from the PathInfo - String requestorPeerId = req.getPathInfo(); - - if (null != requestorPeerId) { - int begin = 0; - int end = requestorPeerId.length(); - - // check for all leading "/" - while (begin < end && requestorPeerId.charAt(begin) == '/') { - begin++; - } - - // check for all trailing "/" - while (end - begin > 0 && requestorPeerId.charAt(end - 1) == '/') { - end--; - } - - if (begin == end) { - // nothing left of the string - requestorPeerId = null; - } else { - // get the new substring - requestorPeerId = requestorPeerId.substring(begin, end); - } - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("requestorPeerId = " + requestorPeerId); - } - - return requestorPeerId; - } - - /** - * Returns the request timeout or -1 if a request timeout is not given - */ - private static long getResponseTimeout(String requestTimeoutString) { - // the default timeout is -1, which means do not return a message - long timeout = -1; - - try { - timeout = Long.parseLong(requestTimeoutString); - - // Protect agains clients that will try top have us keep - // connections for ever. If they re-establish all the time it's - // fine, but until we have a more sophisticated mechanism, we - // want to make sure we quit timely if the client's gone. - if (timeout > MAXIMUM_RESPONSE_DURATION || timeout == 0) { - timeout = MAXIMUM_RESPONSE_DURATION; - } - } catch (NumberFormatException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("The requestTimeout does not contain a decimal number " + requestTimeoutString); - } - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("requestTimeout = " + timeout); - } - - return timeout; - } - - /** - * Returns the lazy close timeout or -1 if a lazy close timeout is not given - */ - private static long getExtraResponsesTimeout(String extraResponseTimeoutString) { - // the default timeout is -1, which means do not wait for additional messages - long timeout = -1; - - try { - timeout = Long.parseLong(extraResponseTimeoutString); - - // Protect agains clients that will try top have us keep - // connections for ever. If they re-establish all the time it's - // fine, but until we have a more sophisticated mechanism, we - // want to make sure we quit timely if the client's gone. - if (timeout > (2 * TimeUtils.AMINUTE) || timeout == 0) { - timeout = (2 * TimeUtils.AMINUTE); - } - } catch (NumberFormatException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("The extraResponseTimeoutString does not contain a decimal number " + extraResponseTimeoutString); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("extraResponseTimeout = " + timeout); - } - - return timeout; - } - - /** - * Checks if the request includes a message as content. - * - * @param req The request to be inspected. - * @return true if there is content to be read from this request. - */ - private static boolean hasMessageContent(HttpServletRequest req) { - boolean hasContent = false; - - int contentLength = req.getContentLength(); - - // if the content length is not zero, there is an incoming message - // Either the message length is given or it is a chunked message - if (contentLength > 0) { - hasContent = true; - } else if (contentLength == -1) { - // check if the transfer encoding is chunked - String transferEncoding = req.getHeader("Transfer-Encoding"); - - hasContent = "chunked".equals(transferEncoding); - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("hasMessageContent = " + hasContent); - } - - return hasContent; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpServletMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpServletMessenger.java deleted file mode 100644 index 3d72bf21..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/HttpServletMessenger.java +++ /dev/null @@ -1,470 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.servlethttp; - -import java.util.Timer; -import java.util.TimerTask; - -import java.io.IOException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.peergroup.PeerGroupID; - -import net.jxta.impl.endpoint.BlockingMessenger; -import net.jxta.impl.endpoint.EndpointServiceImpl; -import net.jxta.impl.util.TimeUtils; - -/** - * Simple messenger that waits for a message to give back to the requesting client - * - *

            This messenger is not entirely thread-safe. You should not use any - * of the sendMessage methods from more than one thread. - * - */ -final class HttpServletMessenger extends BlockingMessenger { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(HttpServletMessenger.class.getName()); - - // We need an explicit idle state. outgoingMessage being null is not enough - // because there is an intermediate state where the http servlet must know - // that there is nothing new to be sent but the relay side must also know - // that status has not been collected yet (the messenger is not ready to be - // reused). We use outgoingMessage == null to know that the message - // has already been picked-up by the servlet thread, and - // sendResult != IDLE to know that the result has not yet been collected - // by the relay sender thread. - - private final static int SEND_IDLE = 0; - private final static int SEND_INPROGRESS = 1; - private final static int SEND_SUCCESS = 2; - private final static int SEND_FAIL = 3; - private final static int SEND_TOOLONG = 4; - - private final static long MAX_SENDING_BLOCK = 2 * TimeUtils.AMINUTE; - private final static long MAX_SENDING_WAIT = 3 * TimeUtils.ASECOND; - - private final static EndpointAddress nullEndpointAddr = new EndpointAddress("http", "0.0.0.0:0", null, null); - - private final static Timer closeMessengerTimer = new Timer("HttpServletMessenger Expiration timer", true); - - private final EndpointAddress logicalAddress; - private final MessageElement srcAddressElement; - private ScheduledExipry expirationTask; - - /** - * The message "queue" - */ - private Message outgoingMessage = null; - - private int sendResult = SEND_IDLE; - private long sendingSince = 0; - - /** - * Allows us to schedule the closing of a messenger. - */ - private static class ScheduledExipry extends TimerTask { - - /** - * The messenger we will be expiring. - */ - HttpServletMessenger messenger; - - ScheduledExipry(HttpServletMessenger toExpire) { - messenger = toExpire; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean cancel() { - // It is important we clear the messenger because Timer doesn't - // remove cancelled TimerTasks from it's queue until they fire. This - // means that the Messenger would not be GCed until the TimerTask - // fired. - messenger = null; - boolean result = super.cancel(); - - // take the opportunity to also purge canceled tasks - closeMessengerTimer.purge(); - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - HttpServletMessenger temp = messenger; - - messenger = null; - - if (null != temp) { - temp.close(); - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in timer task :" + Thread.currentThread().getName(), all); - } - } - } - } - - /** - * Standard constructor. - * - * @param peerGroupID the peer group id - * @param srcAddress source address - * @param logicalAddress logical address - * @param validFor validity in milliseconds - */ - HttpServletMessenger(PeerGroupID peerGroupID, EndpointAddress srcAddress, EndpointAddress logicalAddress, long validFor) { - - // We do not use self destruction. - super(peerGroupID, nullEndpointAddr, false); - - this.logicalAddress = logicalAddress; - - this.srcAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NAME, srcAddress.toString(), null); - - if ((0 != validFor) && (validFor < Long.MAX_VALUE)) { - expirationTask = new ScheduledExipry(this); - - closeMessengerTimer.schedule(expirationTask, validFor); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("HttpServletMessenger\n\t" + toString()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void closeImpl() { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("close\n\t" + toString()); - } - - ScheduledExipry cancelExpire = expirationTask; - - expirationTask = null; - if (null != cancelExpire) { - cancelExpire.cancel(); - } - - super.close(); - - notifyAll(); - } - - /** - * {@inheritDoc} - */ - @Override - public EndpointAddress getLogicalDestinationImpl() { - return logicalAddress; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isIdleImpl() { - // We do not use self destruction. - return false; - } - - /** - * Send messages. Messages are queued and processed by a thread - * running HttpClientConnection. - */ - @Override - public synchronized void sendMessageBImpl(Message message, String service, String serviceParam) throws IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Send " + message + " to " + dstAddress.toString() + "\n\t" + toString()); - } - - if (isClosed()) { - IOException failure = new IOException("Messenger was closed, it cannot be used to send messages."); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, failure.getMessage(), failure); - } - - throw failure; - } - - // Set the message with the appropriate src and dest address - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NS, srcAddressElement); - - EndpointAddress destAddressToUse = getDestAddressToUse(service, serviceParam); - - MessageElement dstAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NAME, - destAddressToUse.toString(), null); - - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NS, dstAddressElement); - - // doSend returns false only when this messenger is closed. - if (!doSend(message)) { - // send message failed - IOException failure = new IOException("Messenger was closed, it cannot be used to send messages."); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "sendMessage failed (messenger closed).\n\t" + toString(), failure); - } - - throw failure; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("sendMessage successful for " + message + "\n\t" + toString()); - } - } - - // Must be called from synchronized context only. - private boolean doSend(Message message) { - - // No need to wait for the messenger to be free. Transport - // messengers have no obligation to behave nicely if they're - // used by mltiple threads. If a thread comes here while - // we're already busy sending, then that's a congestion. Just - // drop the new message (pretend it went out). - // This is not even so nasty, because jetty has a sizeable - // output buffer. As long as that buffer is not full, sending - // is instantaneou. If sending starts blocking, then we can honestly - // drop messages. - - if (isClosed()) { - return false; - } - - long now = TimeUtils.timeNow(); - - if (sendResult != SEND_IDLE) { - // check if that connection is a lemon - if ((sendResult == SEND_TOOLONG) && (now > (sendingSince + MAX_SENDING_BLOCK))) { - close(); - } - return true; - } - - // put the message on the outgoing "queue" of size 1 - outgoingMessage = message; - sendResult = SEND_INPROGRESS; - sendingSince = now; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Queued " + message); - } - - // notify the servlet if it was waiting for a message - notifyAll(); - - // wait for the result of the send Since there is ample - // buffering underneath, we're not supposed to wait for long; - // unless we outdo the connection, in which case, we might as - // well start dropping. No point in blocking. - // FIXME: jice@jxta.org - this is a rudimentary fix. We need - // something like watchedOutputStream instead. Being forced - // to do a two-way handshake with a servlet thread is pretty - // ridiculous too. We need a simpler http transport. - - long absoluteTimeOut = TimeUtils.toAbsoluteTimeMillis(MAX_SENDING_WAIT); - - while (!isClosed()) { - if (sendResult != SEND_INPROGRESS) { - break; - } - - long waitfor = TimeUtils.toRelativeTimeMillis(absoluteTimeOut); - - if (waitfor <= 0) { - break; - } - - try { - wait(waitfor); - } catch (InterruptedException e) { - Thread.interrupted(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "InterruptedException timeout = " + MAX_SENDING_WAIT + "\n\t" + toString(), e); - } - break; - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Got result\n\t" + toString()); - } - - if (isClosed() && (SEND_INPROGRESS == sendResult)) { - return false; - } - - // If the operation completed just confirm that we're done - // reading the result too. Else mark that we don't care. - // When it completes the result will be discarded. By default, - // the we return ok. If the operation did not complete fast - // enough, that's what we return. - - boolean result = (sendResult != SEND_FAIL); - - if (sendResult == SEND_INPROGRESS) { - sendResult = SEND_TOOLONG; - outgoingMessage = null; - } else { - sendResult = SEND_IDLE; - } - - // Let another contending thread use this messenger. - notifyAll(); - - return result; - } - - /** - * Retrieve a message from the "queue" of messages for the servlet. - * - * @param timeout Number of milliseconds to wait for a message. Per Java - * convention 0 (zero) means wait forever. - * @return the message or null if no message was available - * before the timeout was reached. - * @throws InterruptedException If the thread is interrupted while waiting. - */ - protected synchronized Message waitForMessage(long timeout) throws InterruptedException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Waiting (" + (0 == timeout ? "forever" : Long.toString(timeout)) + ") for message\n\t" + toString()); - } - - if (0 == timeout) { - // it's forever - timeout = Long.MAX_VALUE; - } - - long absoluteTimeOut = TimeUtils.toAbsoluteTimeMillis(timeout); - - while (!isClosed() && (null == outgoingMessage)) { - long waitfor = TimeUtils.toRelativeTimeMillis(absoluteTimeOut); - - if (waitfor <= 0) { - break; - } - - wait(waitfor); - } - - // get the message - Message result = outgoingMessage; - - outgoingMessage = null; // Msg can only be picked-up once. - - if (!isClosed() && (result == null)) { - // ABSURD, but seems to happen: the message sent was NULL - // and the sender thread is waiting for the completion event. - // There would be no such thing, but we can make sure it stops - // waiting and still leave the messenger in a sane state if there - // was no such absurdity going on. - - sendResult = SEND_IDLE; - notifyAll(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Returning " + result + "\n\t" + toString()); - } - - return result; - } - - protected synchronized void messageSent(boolean wasSuccessful) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("messageSent(" + wasSuccessful + ")\n\t" + toString()); - } - - if (SEND_TOOLONG == sendResult) { - // No-one cares for the result any more. Let the next send go. - sendResult = SEND_IDLE; - } else { - sendResult = wasSuccessful ? SEND_SUCCESS : SEND_FAIL; - } - - notifyAll(); - } - - /** - * {@inheritDoc} - * - *

            An implementation for debugging. Do not depend on the format. - */ - @Override - public String toString() { - return "[" + super.toString() + "] isClosed=" + isClosed() + " sendResult=" + sendResult + " outmsg=" + outgoingMessage; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/ServletHttpTransport.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/ServletHttpTransport.java deleted file mode 100644 index fa19f854..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/ServletHttpTransport.java +++ /dev/null @@ -1,473 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.servlethttp; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; - -import java.net.UnknownHostException; -import java.util.concurrent.Executor; - -import java.util.logging.Logger; -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.id.ID; -import net.jxta.meter.MonitorResources; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.TransportAdvertisement; -import net.jxta.platform.Module; - -import net.jxta.exception.PeerGroupException; - -import net.jxta.impl.endpoint.transportMeter.TransportBindingMeter; -import net.jxta.impl.endpoint.transportMeter.TransportMeter; -import net.jxta.impl.endpoint.transportMeter.TransportMeterBuildSettings; -import net.jxta.impl.endpoint.transportMeter.TransportServiceMonitor; -import net.jxta.impl.endpoint.IPUtils; -import net.jxta.impl.protocol.HTTPAdv; - -import net.jxta.impl.meter.*; -import net.jxta.impl.peergroup.StdPeerGroup; - -/** - * A JXTA Message Transport - * - *

            This class is really a facade for the following:

              - *
            • An HTTP client message sender
            • - *
            • An HTTP-server-based message receiver
            • - *
            - */ -public final class ServletHttpTransport implements Module { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(ServletHttpTransport.class.getName()); - - /** - * The name of the protocol - */ - private final static String DEFAULT_HTTP_PROTOCOL_NAME = "http"; - - String HTTP_PROTOCOL_NAME = DEFAULT_HTTP_PROTOCOL_NAME; - - /** - * PeerGroup we are working for - */ - PeerGroup group; - ID assignedID; - ModuleImplAdvertisement implAdvertisement; - - /** - * The executor used by HttpClientMessenger - */ - Executor executor; - - /** - * The endpoint we attach to. - */ - private EndpointService endpoint = null; - - /** - * If {@code true} then we are configured to act as an HTTP client. This - * means we will poll for messages. - */ - private boolean configClient = false; - - /** - * If {@code true} then we are configured to act as an HTTP server. This - * means we will accept connections from polling clients. - */ - private boolean configServer = false; - - /** - * The HttpMessageSender instance - */ - private HttpMessageSender sender = null; - - /** - * The HttpMessageReceiver instance - */ - private HttpMessageReceiver receiver = null; - - /** - * The TransportMeter for this httpTransport - */ - private TransportMeter transportMeter; - - /** - * The TransportBindingMeter for unknown connections (pings/errors) - */ - private TransportBindingMeter unknownTransportBindingMeter; - - /** - * The InetAddress of the network interface we are bound to otherwise the - * ALL/ANY address. - */ - InetAddress usingInterface = null; - - /** - * Port number to which we are bound. - */ - int usingPort = 0; - - /** - * The addresses which we will advertise and by which we may be reached. - */ - private List publicAddresses = null; - - /** - * Our preferred return address which we will use as the "source" for - * messages we send. - */ - private EndpointAddress publicAddress; - - /** - * {@inheritDoc} - */ - public synchronized void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - this.group = group; - this.assignedID = assignedID; - implAdvertisement = (ModuleImplAdvertisement) impl; - - this.executor = ((StdPeerGroup) group).getExecutor(); - - // Get out invariable parameters from the implAdv - XMLElement param = (XMLElement) implAdvertisement.getParam(); - - if (param != null) { - Enumeration list = param.getChildren("Proto"); - - if (list.hasMoreElements()) { - XMLElement pname = (XMLElement) list.nextElement(); - String configProtoName = pname.getTextValue(); - if (null != configProtoName) { - HTTP_PROTOCOL_NAME = configProtoName.trim(); - } - } - } - - ConfigParams peerAdv = group.getConfigAdvertisement(); - - param = (XMLElement) peerAdv.getServiceParam(assignedID); - - Enumeration httpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType()); - - // get the TransportAdv - if (httpChilds.hasMoreElements()) { - param = (XMLElement) httpChilds.nextElement(); - Attribute typeAttr = param.getAttribute("type"); - - if (!HTTPAdv.getAdvertisementType().equals(typeAttr.getValue())) { - throw new IllegalArgumentException("Transport adv is not an http adv"); - } - - if (httpChilds.hasMoreElements()) { - throw new IllegalArgumentException("Configuration contained multiple http advertisements"); - } - } else { - throw new IllegalArgumentException("Configuration did not contain http advertisement"); - } - - Advertisement paramsAdv = AdvertisementFactory.newAdvertisement(param); - - if (!(paramsAdv instanceof HTTPAdv)) { - throw new IllegalArgumentException("Provided advertisement was not a " + HTTPAdv.getAdvertisementType()); - } - - HTTPAdv httpAdv = (HTTPAdv) paramsAdv; - - // determine the local interface to use. If the user specifies - // one, use that. Otherwise, use the all the available interfaces. - String interfaceAddressStr = httpAdv.getInterfaceAddress(); - boolean publicAddressOnly = httpAdv.getPublicAddressOnly(); - - if (interfaceAddressStr != null) { - try { - usingInterface = InetAddress.getByName(interfaceAddressStr); - } catch (UnknownHostException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Invalid address for local interface address, using default"); - } - usingInterface = IPUtils.ANYADDRESS; - } - } else { - usingInterface = IPUtils.ANYADDRESS; - } - - usingPort = httpAdv.getPort(); - - configClient = httpAdv.isClientEnabled(); - - configServer = httpAdv.isServerEnabled(); - - publicAddresses = getPublicAddresses(configServer, httpAdv.getServer(), usingInterface, usingPort, publicAddressOnly); - - if (!configClient && !configServer) { - throw new IllegalArgumentException("Neither incoming nor outgoing connections configured."); - } - - publicAddress = publicAddresses.get(0); - - // Tell tell the world about our configuration. - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring HTTP Message Transport : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation:"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description: ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI: ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code: ").append(implAdvertisement.getCode()); - } - configInfo.append("\n\tGroup Params:"); - configInfo.append("\n\t\tGroup: ").append(group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID: ").append(group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID: ").append(group.getPeerID()); - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tProtocol: ").append(httpAdv.getProtocol()); - configInfo.append("\n\t\tClient Enabled: ").append(configClient); - configInfo.append("\n\t\tServer Enabled: ").append(configServer); - configInfo.append("\n\t\tPublic address: ").append(httpAdv.getServer() == null ? "(unspecified)" : httpAdv.getServer()); - configInfo.append("\n\t\tInterface address: ").append(interfaceAddressStr == null ? "(unspecified)" : interfaceAddressStr); - configInfo.append("\n\t\tUnicast Server Bind Addr: ").append(IPUtils.getHostAddress(usingInterface)).append(":").append(usingPort); - configInfo.append("\n\t\tPublic Addresses: "); - configInfo.append("\n\t\t\tDefault Endpoint Addr : ").append(publicAddress); - for (EndpointAddress anAddr : publicAddresses) { - configInfo.append("\n\t\t\tEndpoint Addr : ").append(anAddr); - } - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public synchronized int startApp(String[] args) { - endpoint = group.getEndpointService(); - - if (null == endpoint) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - - return START_AGAIN_STALLED; - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - TransportServiceMonitor transportServiceMonitor = (TransportServiceMonitor) MonitorManager.getServiceMonitor(group, - MonitorResources.transportServiceMonitorClassID); - - if (transportServiceMonitor != null) { - transportMeter = transportServiceMonitor.createTransportMeter("HTTP", publicAddress); - unknownTransportBindingMeter = transportMeter.getTransportBindingMeter(TransportMeter.UNKNOWN_PEER, - TransportMeter.UNKNOWN_ADDRESS); - } - } - - if (configServer) { - // Start the http server that runs the receiver. - - try { - receiver = new HttpMessageReceiver(this, publicAddresses, usingInterface, usingPort); - receiver.start(); - } catch (PeerGroupException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not start http message receiver", e); - } - return -1; // Can't go on; if we were configured to be a server we must make the failure obvious. - } - } - - if (configClient) { - // create the MessageSender - - try { - sender = new HttpMessageSender(this, - new EndpointAddress("jxta", group.getPeerID().getUniqueValue().toString(), null, null)); - sender.start(); - } catch (PeerGroupException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not start http message sender", e); - } - return -1; // Can't go on; if we were configured to be a server we must make the failure obvious. - } - } - - return 0; - } - - /** - * {@inheritDoc} - */ - public synchronized void stopApp() { - if (receiver != null) { - receiver.stop(); - } - - if (sender != null) { - sender.stop(); - } - - endpoint = null; - } - - /** - * {@inheritDoc} - */ - EndpointService getEndpointService() { - return endpoint; - } - - private List getPublicAddresses(boolean serverEnabled, String serverName, InetAddress usingInterface, int serverSocketPort, boolean publicAddressOnly) { - List publicAddresses = new ArrayList(); - - if (serverEnabled) { - // Build the publicAddresses - - // first in the list is the "public server name". We don't try to - // resolve this since it might not be resolvable in the context - // we are running in, we just assume it's good. - if (serverName != null) { - // use speced server name. - EndpointAddress newAddr = new EndpointAddress(HTTP_PROTOCOL_NAME, serverName, null, null); - - publicAddresses.add(newAddr); - if (publicAddressOnly) { - return publicAddresses; - } - } - } - - // then add the rest of the local interfaces as appropriate - if (usingInterface.equals(IPUtils.ANYADDRESS)) { - // its wildcarded - Iterator eachLocal = IPUtils.getAllLocalAddresses(); - List wildAddrs = new ArrayList(); - - while (eachLocal.hasNext()) { - InetAddress anAddress = eachLocal.next(); - - String hostAddress = IPUtils.getHostAddress(anAddress); - - EndpointAddress newAddr = new EndpointAddress(HTTP_PROTOCOL_NAME, - hostAddress + ":" + Integer.toString(serverSocketPort), null, null); - - // don't add it if its already in the list - if (!publicAddresses.contains(newAddr)) { - wildAddrs.add(newAddr); - } - } - - // we sort them so that later equals() will be deterministic. - // the result of IPUtils.getAllLocalAddresses() is not known - // to be sorted. - Collections.sort(wildAddrs, new Comparator() { - public int compare(EndpointAddress one, EndpointAddress two) { - return one.toString().compareTo(two.toString()); - } - - @Override - public boolean equals(Object that) { - return this == that; - } - }); - - publicAddresses.addAll(wildAddrs); - } else { - // use specified interface - String hostAddress = IPUtils.getHostAddress(usingInterface); - - EndpointAddress newAddr = new EndpointAddress(HTTP_PROTOCOL_NAME, - hostAddress + ":" + Integer.toString(serverSocketPort), null, null); - - // don't add it if its already in the list - if (!publicAddresses.contains(newAddr)) { - publicAddresses.add(newAddr); - } - } - - return publicAddresses; - } - - TransportBindingMeter getTransportBindingMeter(String peerIDString, EndpointAddress destinationAddress) { - if (transportMeter != null) { - return transportMeter.getTransportBindingMeter((peerIDString != null) ? peerIDString : TransportMeter.UNKNOWN_PEER, - destinationAddress); - } else { - return null; - } - } - - TransportBindingMeter getUnknownTransportBindingMeter() { - return unknownTransportBindingMeter; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/package.html deleted file mode 100644 index 7a5ac9cc..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/servlethttp/package.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.endpoint.MessageTransport} implementation which - uses the HTTP protocol. - - @see net.jxta.endpoint.EndpointService - @see net.jxta.endpoint.MessageTransport - @see net.jxta.endpoint.MessageSender - @see net.jxta.endpoint.MessageReceiver - @see net.jxta.endpoint.Message - - @see IETF 2068 : Hypertext Transfer Protocol -- HTTP/1.1 - @see JXTA Protocols Specification : Standard JXTA Transport Bindings - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/IncomingUnicastServer.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/IncomingUnicastServer.java deleted file mode 100644 index 496d9f07..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/IncomingUnicastServer.java +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.tcp; - -import net.jxta.logging.Logging; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.*; -import java.nio.channels.*; -import java.nio.channels.spi.SelectorProvider; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.RejectedExecutionException; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This server handles incoming unicast TCP connections - */ -public class IncomingUnicastServer implements Runnable { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(IncomingUnicastServer.class.getName()); - - /** - * The transport which owns this server. - */ - private final TcpTransport transport; - - /** - * The interface address the serverSocket will try to bind to. - */ - private final InetAddress serverBindLocalInterface; - - /** - * The beginning of the port range the serverSocket will try to bind to. - */ - private final int serverBindStartLocalPort; - - /** - * The port the serverSocket will try to bind to. - */ - private int serverBindPreferedLocalPort; - - /** - * The end of the port range the serverSocket will try to bind to. - */ - private final int serverBindEndLocalPort; - - /** - * The socket we listen for connections on. - */ - private ServerSocket serverSocket; - - /** - * If true then the we are closed or closing. - */ - private volatile boolean closed = false; - - /** - * The thread on which connection accepts will take place. - */ - private Thread acceptThread = null; - - /** - * Channel Selector - */ - private Selector acceptSelector = null; - - /** - * ServerSocket Channel - */ - private ServerSocketChannel serverSocChannel = null; - - /** - * Constructor for the TCP server - * - * @param owner the TCP transport we are working for - * @param serverInterface the network interface to use. - * @param preferedPort the port we will be listening on. - * @param startPort starting port - * @param endPort the endport in port range - * @throws IOException if an io severe occurs - * @throws SecurityException if a security exception occurs - */ - public IncomingUnicastServer(TcpTransport owner, InetAddress serverInterface, int preferedPort, int startPort, int endPort) throws IOException, SecurityException { - this.transport = owner; - serverBindLocalInterface = serverInterface; - serverBindPreferedLocalPort = preferedPort; - serverBindStartLocalPort = startPort; - serverBindEndLocalPort = endPort; - - openServerSocket(); - } - - /** - * Start this server. - * - * @return true if successfully started - */ - public synchronized boolean start() { - - if (acceptThread != null) { - return false; - } - - // Start daemon thread - acceptThread = new Thread(transport.group.getHomeThreadGroup(), this, "TCP Transport ServerSocket accept for " + transport.getPublicAddress()); - acceptThread.setDaemon(true); - acceptThread.start(); - return true; - } - - /** - * Stop this server. - */ - public synchronized void stop() { - closed = true; - - Thread temp = acceptThread; - - if (null != temp) { - // interrupt does not seem to have an effect on threads blocked in accept. - temp.interrupt(); - } - - // Closing the socket works though. - try { - serverSocket.close(); - } catch (IOException ignored) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "IO error occured while closing server socket", ignored); - } - } - - try { - acceptSelector.close(); - } catch (IOException io) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "IO error occured while closing Selectors", io); - } - } - } - - /** - * Get the address of the network interface being used. - * - * @return the local socket address - */ - synchronized InetSocketAddress getLocalSocketAddress() { - ServerSocket localSocket = serverSocket; - - if (null != localSocket) { - return (InetSocketAddress) localSocket.getLocalSocketAddress(); - } else { - return null; - } - } - - /** - * Get the start port range we are using - * - * @return starting port range - */ - int getStartPort() { - return serverBindStartLocalPort; - } - - /** - * Get the end port range we are using - * - * @return the ending port range - */ - int getEndPort() { - return serverBindEndLocalPort; - } - - /** - * Daemon where we wait for incoming connections. - */ - public void run() { - try { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Server is ready to accept connections"); - } - - while (!closed) { - try { - if ((null == serverSocChannel) || !serverSocChannel.isOpen()) { - openServerSocket(); - if (null == serverSocChannel) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed to open Server Channel"); - } - break; - } - } - acceptSelector.select(); - Iterator it = acceptSelector.selectedKeys().iterator(); - - while (it.hasNext()) { - SelectionKey key = it.next(); - - // remove it - it.remove(); - if (key.isAcceptable()) { - ServerSocketChannel nextReady = (ServerSocketChannel) key.channel(); - SocketChannel inputSocket = nextReady.accept(); - - if ((inputSocket == null) || (inputSocket.socket() == null)) { - continue; - } - - MessengerBuilder builder = new MessengerBuilder(inputSocket, transport); - - try { - transport.executor.execute(builder); - transport.incrementConnectionsAccepted(); - } catch (RejectedExecutionException re) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, MessageFormat.format("Executor rejected task : {0}", builder.toString()), re); - } - } - } - } - } catch (ClosedSelectorException cse) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Accept Selector closed"); - } - if (closed) { - break; - } - } catch (InterruptedIOException woken) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Accept Thread woken"); - } - } catch (IOException e1) { - if (closed) { - break; - } - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, - "[1] ServerSocket.accept() failed on " + serverSocket.getInetAddress() + ":"+ serverSocket.getLocalPort(), e1); - } - } catch (SecurityException e2) { - if (closed) { - break; - } - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "[2] ServerSocket.accept() failed on " + serverSocket.getInetAddress() + ":" + serverSocket.getLocalPort(), e2); - } - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - synchronized (this) { - closed = true; - ServerSocket temp = serverSocket; - - serverSocket = null; - if (null != temp) { - try { - temp.close(); - } catch (IOException ignored) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Exception occurred while closing server socket", ignored); - } - } - } - acceptThread = null; - } - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Server has been shut down."); - } - } - } - - public List rangeCheckShuffle(int start, int end) { - if ((start < 1) || (start > 65535)) { - throw new IllegalArgumentException("Invalid start port"); - } - - if ((end < 1) || (end > 65535) || (end < start)) { - throw new IllegalArgumentException("Invalid end port"); - } - - // fill the inRange array. - List inRange = new ArrayList(); - - for (int eachInRange = start; eachInRange < end; eachInRange++) { - inRange.add(eachInRange); - } - Collections.shuffle(inRange); - return inRange; - } - - private synchronized void openServerSocket() throws IOException, SecurityException { - serverSocket = null; - while (true) { - try { - synchronized (this) { - acceptSelector = SelectorProvider.provider().openSelector(); - serverSocChannel = ServerSocketChannel.open(); - InetSocketAddress bindAddress; - - if (-1 != serverBindPreferedLocalPort) { - bindAddress = new InetSocketAddress(serverBindLocalInterface, serverBindPreferedLocalPort); - serverSocket = serverSocChannel.socket(); - int useBufferSize = Math.max(TcpTransport.RecvBufferSize, serverSocket.getReceiveBufferSize()); - - serverSocket.setReceiveBufferSize(useBufferSize); - serverSocket.bind(bindAddress, TcpTransport.MaxAcceptCnxBacklog); - } else { - List rangeList = rangeCheckShuffle(serverBindStartLocalPort, serverBindEndLocalPort); - - while (!rangeList.isEmpty()) { - int tryPort = rangeList.remove(0); - - if (tryPort > serverBindEndLocalPort) { - continue; - } - - try { - bindAddress = new InetSocketAddress(serverBindLocalInterface, tryPort); - serverSocket = serverSocChannel.socket(); - int useBufferSize = Math.max(TcpTransport.RecvBufferSize, serverSocket.getReceiveBufferSize()); - - serverSocket.setReceiveBufferSize(useBufferSize); - serverSocket.bind(bindAddress, TcpTransport.MaxAcceptCnxBacklog); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("ServerSocketChannel bound to " + bindAddress + ":" + tryPort); - } - } catch (SocketException failed) { - // this one is busy. try another. - } catch (Error err) { - // this can occur on some platforms where 2 instances are listenting on the same port - } - } - } - } - try { - // set the new channel non-blocking - serverSocChannel.configureBlocking(false); - serverSocChannel.register(acceptSelector, SelectionKey.OP_ACCEPT); - } catch (ClosedChannelException cce) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.log(Level.FINER, "Channel closed.", cce); - } - } - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Server will accept connections at " + serverSocket.getLocalSocketAddress()); - } - return; - } catch (BindException e0) { - if (-1 != serverBindStartLocalPort) { - serverBindPreferedLocalPort = (0 == serverBindStartLocalPort) ? 0 : -1; - continue; - } - closed = true; - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Cannot bind ServerSocket on " + serverBindLocalInterface + ":" + serverBindPreferedLocalPort, e0); - } - return; - } - } - } - - /** - * An Executor task that creates a messenger from an incoming SocketChannel - * object. - */ - private static class MessengerBuilder implements Runnable { - - private SocketChannel inputSocket; - private TcpTransport transport; - TcpMessenger newMessenger; - - MessengerBuilder(SocketChannel inputSocket, TcpTransport transport) { - assert inputSocket.socket() != null; - this.inputSocket = inputSocket; - this.transport = transport; - } - - /** - * {@inheritDoc} - */ - public void run() { - try { - if (inputSocket != null && inputSocket.isConnected()) { - newMessenger = new TcpMessenger(inputSocket, transport); - } - } catch (IOException io) { - // protect against invalid connections - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Messenger creation failure", io); - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.SEVERE, "Uncaught Throwable", all); - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/TcpMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/TcpMessenger.java deleted file mode 100644 index da61b40a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/TcpMessenger.java +++ /dev/null @@ -1,1128 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.tcp; - -import net.jxta.document.MimeMediaType; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.endpoint.WireFormatMessage; -import net.jxta.endpoint.WireFormatMessageFactory; -import net.jxta.id.ID; -import net.jxta.impl.endpoint.BlockingMessenger; -import net.jxta.impl.endpoint.EndpointServiceImpl; -import net.jxta.impl.endpoint.msgframing.MessagePackageHeader; -import net.jxta.impl.endpoint.msgframing.WelcomeMessage; -import net.jxta.impl.endpoint.transportMeter.TransportBindingMeter; -import net.jxta.impl.endpoint.transportMeter.TransportMeterBuildSettings; -import net.jxta.impl.util.TimeUtils; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketTimeoutException; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.SocketChannel; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.locks.ReentrantLock; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.linphone.p2pproxy.core.jxtaext.EndpointRegistry; - -/** - * Implements a messenger which sends messages via raw TCP sockets. - */ -public class TcpMessenger extends BlockingMessenger implements Runnable { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(TcpMessenger.class.getName()); - - /** - * The number of times we allow our write selector to be selected with no - * progress before we give up. - */ - private static final int MAX_WRITE_ATTEMPTS = 3; - - /** - * Description of our current location within the stream. - */ - private enum readState { - /** - * Reading the initial welcome - */ - WELCOME, - /** - * Reading a message header - */ - HEADER, - /** - * Reading a message - */ - BODY - } - - /** - * The source address of messages sent on this messenger. - */ - private final EndpointAddress srcAddress; - - private final MessageElement srcAddressElement; - - /** - * Cache of the logical destination of this messenger. (It helps if it works even after close) - */ - private EndpointAddress logicalDestAddress; - - /** - * The message tcpTransport we are working for. - */ - private final TcpTransport tcpTransport; - - private EndpointAddress dstAddress = null; - private EndpointAddress origAddress = null; - private EndpointAddress fullDstAddress = null; - private InetAddress inetAddress = null; - private int port = 0; - - private volatile boolean closed = false; - private boolean closingDueToFailure = false; - - private WelcomeMessage itsWelcome = null; - - private final long createdAt = TimeUtils.timeNow(); - private long lastUsed = TimeUtils.timeNow(); - - private SocketChannel socketChannel = null; - - private TransportBindingMeter transportBindingMeter; - - /** - * If this is an incoming connection we must not close it when the messenger - * disappears. It has many reasons to disappear while the connection must - * keep receiving messages. This is causing some problems for incoming - * messengers that are managed by some entity, such as the router or the - * relay. These two do call close explicitly when they discard a messenger, - * and their intent is truly to close the underlying connection. So - * basically we need to distinguish between incoming messengers that are - * abandoned without closing (for these we must protect the input side - * because that's the only reason for the connection being there) and - * incoming messengers that are explicitly closed (in which case we must let - * the entire connection be closed). - */ - private boolean initiator; - - private AtomicReference state = new AtomicReference(readState.WELCOME); - - private final static int MAX_LEN = 4096; - private ByteBuffer buffer = ByteBuffer.allocate(MAX_LEN); - - /** - * Header from the current incoming message (if any). - */ - private MessagePackageHeader header = null; - - /** - * Time at which we began receiving the current incoming message. - */ - long receiveBeginTime = 0; - - /** - * Enforces single writer on message write in case the messenger is being - * used on multiple threads. - */ - private final ReentrantLock writeLock = new ReentrantLock(); - - /** - * Create a new TcpMessenger for the specified address. - * - * @param socketChannel the SocketChannel for the messenger - * @param transport the tcp MessageSender we are working for. - * @throws java.io.IOException if an io error occurs - */ - TcpMessenger(SocketChannel socketChannel, TcpTransport transport) throws IOException { - super(transport.group.getPeerGroupID(), - new EndpointAddress(transport.getProtocolName(), - socketChannel.socket().getInetAddress().getHostAddress() + ":" + socketChannel.socket().getPort(), null, null), true); - - initiator = false; - this.socketChannel = socketChannel; - this.tcpTransport = transport; - this.srcAddress = transport.getPublicAddress(); - this.srcAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NAME, srcAddress.toString(), null); - - try { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Connection from " + socketChannel.socket().getInetAddress().getHostAddress() + ":" + socketChannel.socket().getPort()); - } - - // Set the socket options. - Socket socket = socketChannel.socket(); - - int useBufferSize = Math.max(TcpTransport.SendBufferSize, socket.getSendBufferSize()); - - socket.setSendBufferSize(useBufferSize); - - inetAddress = socketChannel.socket().getInetAddress(); - port = socketChannel.socket().getPort(); - - socket.setKeepAlive(true); - socket.setSoTimeout(TcpTransport.connectionTimeOut); - socket.setSoLinger(true, TcpTransport.LingerDelay); - - // Disable Nagle's algorithm (We do this to reduce latency) - socket.setTcpNoDelay(true); - - // Temporarily, our address for inclusion in the welcome message response. - dstAddress = new EndpointAddress(this.tcpTransport.getProtocolName(), inetAddress.getHostAddress() + ":" + port, null, null); - fullDstAddress = dstAddress; - - startMessenger(); - } catch (IOException io) { - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - transportBindingMeter = this.tcpTransport.getUnicastTransportBindingMeter(null, dstAddress); - if (transportBindingMeter != null) { - transportBindingMeter.connectionFailed(initiator, TimeUtils.timeNow() - createdAt); - } - } - // If we failed for any reason, make sure the socket is closed. - // We're the only one to know about it. - if (socketChannel != null) { - socketChannel.close(); - } - throw io; - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - transportBindingMeter = this.tcpTransport.getUnicastTransportBindingMeter((PeerID) getDestinationPeerID(), dstAddress); - if (transportBindingMeter != null) { - transportBindingMeter.connectionEstablished(initiator, TimeUtils.timeNow() - createdAt); - } - } - if (!isConnected()) { - throw new IOException("Failed to establish connection to " + dstAddress); - } - } - - - /** - * Create a new TcpMessenger for the specified address. - * - * @param destaddr the destination of the messenger - * @param tcpTransport the tcp MessageSender we are working for. - * @throws java.io.IOException if an io error occurs - */ - TcpMessenger(EndpointAddress destaddr, TcpTransport tcpTransport) throws IOException { - this(destaddr, tcpTransport, true); - } - - /** - * Create a new TcpMessenger for the specified address. - * - * @param destaddr the destination of the messenger - * @param tcpTransport the tcp MessageSender we are working for. - * @param selfDestruct indicates whether the messenger created will self destruct when idle - * @throws java.io.IOException if an io error occurs - */ - TcpMessenger(EndpointAddress destaddr, TcpTransport tcpTransport, boolean selfDestruct) throws IOException { - // We need self destruction: tcp messengers are expensive to make and they refer to - // a connection that must eventually be closed. - super(tcpTransport.group.getPeerGroupID(), destaddr, selfDestruct); - this.origAddress = destaddr; - - initiator = true; - this.tcpTransport = tcpTransport; - - this.fullDstAddress = destaddr; - this.dstAddress = new EndpointAddress(destaddr, null, null); - - this.srcAddress = tcpTransport.getPublicAddress(); - - srcAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NAME, srcAddress.toString(), null); - - String protoAddr = destaddr.getProtocolAddress(); - int portIndex = protoAddr.lastIndexOf(":"); - - if (portIndex == -1) { - throw new IllegalArgumentException("Invalid Protocol Address (port # missing) "); - } - - String portString = protoAddr.substring(portIndex + 1); - try { - port = Integer.valueOf(portString); - } catch (NumberFormatException caught) { - throw new IllegalArgumentException("Invalid Protocol Address (port # invalid): " + portString); - } - - // Check for bad port number. - if ((port <= 0) || (port > 65535)) { - throw new IllegalArgumentException("Invalid port number in Protocol Address : " + port); - } - - String hostString = protoAddr.substring(0, portIndex); - - inetAddress = InetAddress.getByName(hostString); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Creating new TCP Connection to : " + dstAddress + " / " + inetAddress.getHostAddress() + ":" + port); - } - - // See if we're attempting to use the loopback address. - // And if so, is the peer configured for the loopback network only? - // (otherwise the connection is not permitted). Btw, the otherway around - // is just as wrong, so we check both at once and pretend it cannot work, - // even if it might have. - // FIXME 20041130 This is not an appropriate check if the other peer is - // running on the same machine and the InetAddress.getByName returns the - // loopback address. - // if (inetAddress.isLoopbackAddress() != tcpTransport.usingInterface.isLoopbackAddress()) { - // throw new IOException("Network unreachable--connect to loopback attempted."); - // } - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Connecting to " + inetAddress.getHostAddress() + ":" + port + " via " - + this.tcpTransport.usingInterface.getHostAddress() + ":0"); - } - - socketChannel = SocketChannel.open(); - Socket socket = socketChannel.socket(); - - // Bind it to our outbound interface. - SocketAddress bindAddress = new InetSocketAddress(this.tcpTransport.usingInterface, 0); - - socket.bind(bindAddress); - // Set Socket options. - int useBufferSize = Math.max(TcpTransport.SendBufferSize, socket.getSendBufferSize()); - socket.setSendBufferSize(useBufferSize); - - useBufferSize = Math.max(TcpTransport.RecvBufferSize, socket.getReceiveBufferSize()); - socket.setReceiveBufferSize(useBufferSize); - - socket.setKeepAlive(true); - socket.setSoTimeout(TcpTransport.connectionTimeOut); - socket.setSoLinger(true, TcpTransport.LingerDelay); - // Disable Nagle's algorithm (We do this to reduce latency) - socket.setTcpNoDelay(true); - - SocketAddress connectAddress = new InetSocketAddress(inetAddress, port); - socketChannel.connect(connectAddress); - - startMessenger(); - } catch (IOException io) { - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - transportBindingMeter = this.tcpTransport.getUnicastTransportBindingMeter(null, dstAddress); - - if (transportBindingMeter != null) { - transportBindingMeter.connectionFailed(initiator, TimeUtils.timeNow() - createdAt); - } - } - // If we failed for any reason, make sure the socket is closed. This is the only place it is known. - if (socketChannel != null) { - socketChannel.close(); - } - throw io; - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - transportBindingMeter = this.tcpTransport.getUnicastTransportBindingMeter((PeerID) getDestinationPeerID(), dstAddress); - if (transportBindingMeter != null) { - transportBindingMeter.connectionEstablished(initiator, TimeUtils.timeNow() - createdAt); - } - // TODO: We need to add the bytes from the Welcome Messages to the transportBindingMeter, iam@jxta.org - } - - if (!isConnected()) { - throw new IOException("Failed to establish connection to " + dstAddress); - } - } - - /** - * The cost of just having a finalize routine is high. The finalizer is - * a bottleneck and can delay garbage collection all the way to heap - * exhaustion. Leave this comment as a reminder to future maintainers. - * Below is the reason why finalize is not needed here. - *

            - * These messengers are never given to application layers. Endpoint code - * always calls close when needed. - *

            - * There used to be an incoming special case in order to *prevent* - * closure because the inherited finalize used to call close. This is - * no-longer the case. For the outgoing case, we do not need to call close - * for the reason explained above. - */ - protected void finalize() throws Throwable { - closeImpl(); - super.finalize(); - } - - /** - * {@inheritDoc} - *

            - * Now everyone knows its closed and the connection can no-longer be - * obtained. So, we can go about our business of closing it. - * It can happen that a redundant close() is done but it does not matter. - * close() is idempotent. - */ - public synchronized void closeImpl() { - super.close(); - - if (closed) { - return; - } - - closed = true; - - // we are idle now. Way idle. - setLastUsed(0); - if (socketChannel != null) { - // unregister from selector. - tcpTransport.unregister(socketChannel); - try { - socketChannel.close(); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to close messenger " + toString(), e); - } - } - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info((closingDueToFailure ? "Failure" : "Normal") + " close (open " - + TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), createdAt) + "ms) of socket to : " + dstAddress + " / " - + inetAddress.getHostAddress() + ":" + port); - if (closingDueToFailure && Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "stack trace", new Throwable("stack trace")); - } - } - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - if (closingDueToFailure) { - transportBindingMeter.connectionDropped(initiator, TimeUtils.timeNow() - createdAt); - } else { - transportBindingMeter.connectionClosed(initiator, TimeUtils.timeNow() - createdAt); - } - } - } - - /** - * {@inheritDoc} - */ - public boolean isClosed() { - // FIXME - jice 20040413: Warning. this is overloading the standard - // isClosed(). Things were arranged so that it - // should still work, but it's a stretch. Transports should get a deeper - // retrofit eventually. - if (isConnected()) { - return false; - } - - // Ah, this connection is broken. So, we weren't closed, but now - // we are. That could happen redundantly since two threads could - // find that holdIt.isConnected() is false before one of them - // first zeroes conn. But it does not matter. super.close() is - // idempotent (and does pretty much nothing in our case, anyway). - super.close(); - return true; - } - - /** - * {@inheritDoc} - *

            - * Since we probe the connection status, we'll keep a messenger as long - * as the connection is active, even if only on the incoming side. - * So we're being a bit nice to the other side. Anyway, incoming - * connections do not go away when the messenger does. There's a receive - * timeout for that. - */ - public boolean isIdleImpl() { - return (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), getLastUsed()) > 15 * TimeUtils.AMINUTE); - } - - /** - * {@inheritDoc} - */ - public EndpointAddress getLogicalDestinationImpl() { - // FIXME 20070127 bondolo THIS IS BEING CALLED BEFORE IT IS INITED. - return logicalDestAddress; - } - - /** - * {@inheritDoc} - */ - public void sendMessageBImpl(Message message, String service, String serviceParam) throws IOException { - sendMessageDirect(message, service, serviceParam, false); - } - - public void sendMessageDirect(Message message, String service, String serviceParam, boolean direct) throws IOException { - if (isClosed()) { - IOException failure = new IOException("Messenger was closed, it cannot be used to send messages."); - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, failure.getMessage(), failure); - } - throw failure; - } - - // Set the message with the appropriate src and dest address - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NS, srcAddressElement); - EndpointAddress destAddressToUse; - if (direct) { - destAddressToUse = origAddress; - } else { - destAddressToUse = getDestAddressToUse(service, serviceParam); - } - - MessageElement dstAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NAME, destAddressToUse.toString(), null); - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NS, dstAddressElement); - - // send it - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + message + " to " + destAddressToUse + " on connection " + getDestinationAddress()); - } - xmitMessage(message); - } catch (IOException caught) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Message send failed for " + message, caught); - } - closeImpl(); - throw caught; - } - } - - private void startMessenger() throws IOException { - socketChannel.configureBlocking(true); - - // Send the welcome message - WelcomeMessage myWelcome = new WelcomeMessage(fullDstAddress, - tcpTransport.getPublicAddress(), - tcpTransport.group.getPeerID(), false); - long written = write(new ByteBuffer[]{myWelcome.getByteBuffer()}); - tcpTransport.incrementBytesSent(written); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("welcome message sent"); - } - while (state.get() == readState.WELCOME) { - if (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), this.createdAt) > (TcpTransport.connectionTimeOut)) { - throw new SocketTimeoutException("Failed to receive remote welcome message before timeout."); - } - read(); - processBuffer(); - } - if (!closed) { - socketChannel.configureBlocking(false); - tcpTransport.register(socketChannel, this); - } - } - - /** - * Send message to the remote peer. - * - * @param msg the message to send. - * @throws java.io.IOException For errors sending the message. - */ - private void xmitMessage(Message msg) throws IOException { - - if (closed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Connection was closed to : " + dstAddress); - } - throw new IOException("Connection was closed to : " + dstAddress); - } - - long sendBeginTime = TimeUtils.timeNow(); - long size = 0; - - try { - // todo 20020730 bondolo@jxta.org Do something with content-coding here - // serialize the message. - WireFormatMessage serialed = WireFormatMessageFactory.toWire(msg, WireFormatMessageFactory.DEFAULT_WIRE_MIME, null); - - // Build the package header - MessagePackageHeader header = new MessagePackageHeader(); - - header.setContentTypeHeader(serialed.getMimeType()); - size = serialed.getByteLength(); - header.setContentLengthHeader(size); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + " (" + size + ") to " + dstAddress + " via " + inetAddress.getHostAddress() + ":"+ port); - } - - List partBuffers = new ArrayList(); - - partBuffers.add(header.getByteBuffer()); - partBuffers.addAll(Arrays.asList(serialed.getByteBuffers())); - - long written; - writeLock.lock(); - try { - written = write(partBuffers.toArray(new ByteBuffer[partBuffers.size()])); - } finally { - writeLock.unlock(); - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.messageSent(initiator, msg, TimeUtils.timeNow() - sendBeginTime, written); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Sent {0} bytes {1} successfully via {2}:{3}", written, msg, - inetAddress.getHostAddress(), port)); - } - - tcpTransport.incrementBytesSent(written); - tcpTransport.incrementMessagesSent(); - setLastUsed(TimeUtils.timeNow()); - } catch (SocketTimeoutException failed) { - SocketTimeoutException failure = new SocketTimeoutException("Failed sending " + msg + " to : " + inetAddress.getHostAddress() + ":" + port); - failure.initCause(failed); - throw failure; - } catch (IOException failed) { - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.sendFailure(initiator, msg, TimeUtils.timeNow() - sendBeginTime, size); - } - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Message send failed for " + inetAddress.getHostAddress() + ":" + port, failed); - } - closingDueToFailure = true; - close(); - IOException failure = new IOException("Failed sending " + msg + " to : " + inetAddress.getHostAddress() + ":" + port); - - failure.initCause(failed); - throw failure; - } - } - - /** - * Blocking write of byte buffers to the socket channel. - * - * @param byteBuffers The bytes to write. - * @return The number of bytes written. - * @throws IOException Thrown for errors while writing message. - */ - private long write(final ByteBuffer[] byteBuffers) throws IOException { - - // Determine how many bytes there are to be written in the buffers. - long bytesToWrite = 0; - for (ByteBuffer byteBuffer : byteBuffers) { - bytesToWrite += byteBuffer.remaining(); - } - - if (bytesToWrite == 0L) { - return 0L; - } - - long bytesWritten = 0; - Selector writeSelector = null; - SelectionKey wKey = null; - int attempts = 1; - try { - do { - long wroteBytes; - // Write from the buffers until we write nothing. - do { - wroteBytes = socketChannel.write(byteBuffers); - bytesWritten += wroteBytes; - if (wroteBytes < 0) { - throw new EOFException(); - } - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer(MessageFormat.format("Wrote {0} bytes", wroteBytes)); - } - } while (wroteBytes != 0); - - // Are we done? - if (bytesWritten == bytesToWrite) { - break; - } - // This attempt failed, we may try again. - attempts++; - if (attempts > MAX_WRITE_ATTEMPTS) { - throw new IOException(MessageFormat.format("Max write attempts ({0}) exceeded ({1})", attempts, MAX_WRITE_ATTEMPTS)); - } - - // Get a write selector, we're going to do some waiting. - if (writeSelector == null) { - try { - writeSelector = tcpTransport.getSelector(); - } catch (InterruptedException woken) { - InterruptedIOException incompleteIO = new InterruptedIOException("Interrupted while acquiring write selector."); - incompleteIO.initCause(woken); - incompleteIO.bytesTransferred = (int) Math.min(bytesWritten, Integer.MAX_VALUE); - throw incompleteIO; - } - if (writeSelector == null) { - continue; - } - wKey = socketChannel.register(writeSelector, SelectionKey.OP_WRITE); - } - - // Wait until we are told we can write again. - int ready = writeSelector.select(TcpTransport.connectionTimeOut); - - if (ready == 0) { - throw new SocketTimeoutException("Timeout during socket write"); - } else { - attempts--; - } - } while (attempts <= MAX_WRITE_ATTEMPTS); - } finally { - // cancel the key before returning selector to the pool. - if (wKey != null) { - wKey.cancel(); - wKey = null; - } - - // put the selector back in the pool - if (writeSelector != null) { - // clean up the selector - writeSelector.selectNow(); - tcpTransport.returnSelector(writeSelector); - } - } - return bytesWritten; - } - - /** - * parses a welcome from a buffer - * - * @param buffer the buffer to parse, if successful the state is set to HEADER - * @return true if successfully parsed - */ - private boolean processWelcome(ByteBuffer buffer) { - try { - if (itsWelcome == null) { - itsWelcome = new WelcomeMessage(); - } - - if (!itsWelcome.read(buffer)) { - return false; - } - - // The correct value for dstAddr: that of the other party. - dstAddress = itsWelcome.getPublicAddress(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Creating a logical address from : " + itsWelcome.getWelcomeString()); - } - EndpointRegistry.getInstance().add(itsWelcome.getPeerID().toString(), socketChannel.socket().getInetAddress()); - fullDstAddress = dstAddress; - logicalDestAddress = new EndpointAddress("jxta", itsWelcome.getPeerID().getUniqueValue().toString(), null, null); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Hello from " + itsWelcome.getPublicAddress() + " [" + itsWelcome.getPeerID() + "] "); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Registering Messenger from " + socketChannel.socket().getInetAddress().getHostAddress() + ":"+ socketChannel.socket().getPort()); - } - - try { - // announce this messenger by connection address - tcpTransport.messengerReadyEvent(this, getConnectionAddress()); - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - IOException failure = new IOException("Failure announcing messenger."); - - failure.initCause(all); - throw failure; - } - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Error while parsing the welcome message", e); - } - closeImpl(); - return false; - } - return true; - } - - /** - * parses a header from a buffer - * - * @param buffer the buffer to parse, if successful the state is set to BODY - * @return true if successfully parsed - */ - private boolean processHeader(ByteBuffer buffer) { - - if (null == header) { - header = new MessagePackageHeader(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("{0} Processing message package header, buffer stats:{1}", Thread.currentThread(), buffer.toString())); - } - try { - if (!header.readHeader(buffer)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("{0} maintaining current state at header, buffer stats :{1}", Thread.currentThread(), buffer.toString())); - } - return false; - } - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Error while parsing the message header", e); - } - if (!socketChannel.isConnected()) { - // defunct connection close the messenger - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("SocketChannel closed. Closing the messenger"); - } - closeImpl(); - } - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("{0} setting current state to body, Buffer stats :{1}, remaining elements {2}:", - Thread.currentThread(), buffer.toString(), buffer.remaining())); - } - return true; - } - - private Message processMessage(ByteBuffer buffer, MessagePackageHeader header) throws IOException { - // TODO 20020730 bondolo@jxta.org Do something with content-coding here. - MimeMediaType msgMime = header.getContentTypeHeader(); - - return WireFormatMessageFactory.fromBuffer(buffer, msgMime, null); - } - - /** - * {@inheritDoc} - *

            - * This is what gets run by the Executor. It reads whatever is available, - * processes it and then goes back to the selector waiting for more IO - */ - public void run() { - try { - while (read()) { - List msgs = processBuffer(); - for (Message msg : msgs) { - // Use the group's threadpool to process the message - tcpTransport.executor.execute(new MessageProcessor(msg)); - } - } - - // resets the interestOPS and wakeup the selector - if (socketChannel != null) { - tcpTransport.register(socketChannel, this); - } - - } catch (Throwable all) { - if (Logging.SHOW_SEVERE) { - LOG.log(Level.SEVERE, "Uncaught Throwable", all); - } - } - } - - /** - * @return true to indicate read maybe required - */ - private boolean read() { - if (closed || socketChannel == null) { - return false; - } - if (!socketChannel.isConnected()) { - closeImpl(); - return false; - } - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("{0} State before read(): {1}, buffer stats : {2}, remaining :{3}", - Thread.currentThread(), state.get(), buffer.toString(), buffer.remaining())); - } - - int read = socketChannel.read(buffer); - if (read < 0) { - if (!socketChannel.isConnected() || read < 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("{0} Closing due to EOF", Thread.currentThread())); - } - closeImpl(); - } - return false; - } else if (read == 0) { - return false; - } - - tcpTransport.incrementBytesReceived(read); - // prepare the buffer for reading - buffer.flip(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("{0} SocketChannel.read() == {1} bytes. Buffer stats:{2}, remaining {3}", - Thread.currentThread(), read, buffer.toString(), buffer.remaining())); - } - return true; - } catch (ClosedChannelException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Channel closed while reading data", e); - } - closeImpl(); - return false; - } catch (InterruptedIOException woken) { - // Framing is maintained within this object, therefore a read maybe interrupted then resumed - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning(MessageFormat.format("tcp receive - interrupted : read() {0} {1}:{2}", woken.bytesTransferred, - inetAddress.getHostAddress(), port)); - } - } catch (IOException ioe) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "IOException occured while reading data", ioe); - } - closeImpl(); - return false; - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, MessageFormat.format("tcp receive - Error on connection {0}:{1}", inetAddress.getHostAddress(), port), e); - } - closingDueToFailure = true; - closeImpl(); - return false; - } - // if the channel has a valid read ops return true, otherwise false - return (socketChannel.validOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ; - } - - /** - * processes the input byte buffer - * @return the list of messages present in the buffer - */ - @SuppressWarnings("fallthrough") - public List processBuffer() { - - List msgs = new ArrayList(); - boolean done = false; - - while (!done) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("{0} processBuffer({1}). Buffer stats:{2}, elements remaining {3}", - Thread.currentThread(), state.getClass(), buffer.toString(), buffer.remaining())); - } - - switch (state.get()) { - case WELCOME: - // Parse Welcome message - boolean wseen = processWelcome(buffer); - - if (wseen) { - state.set(readState.HEADER); - } - done = true; - break; - - case HEADER: - // process the message header - boolean hseen = processHeader(buffer); - - if (!hseen) { - done = true; - break; - } - - receiveBeginTime = TimeUtils.timeNow(); - // todo add a check for MTU size - if (header.getContentLengthHeader() > buffer.capacity()) { - ByteBuffer src = buffer; - - // create an array backed buffer - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("{0} Reallocating a new buffer of size {1} to replace :{2}", - Thread.currentThread(), header.getContentLengthHeader(), buffer.toString())); - } - - // This implementation limits the message size to the MTU which is always < 2GB - buffer = ByteBuffer.allocate((int) header.getContentLengthHeader()); - buffer.put(src); - buffer.flip(); - } - state.set(readState.BODY); - /* FALLSTHROUGH */ - - case BODY: - // process the message body - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format(" {0} Proccessing Message Body. expecting {1}, {2} elements remaining {3}", - Thread.currentThread(), header.getContentLengthHeader(), buffer.toString(), buffer.remaining())); - } - if (buffer.remaining() >= (int) header.getContentLengthHeader()) { - Message msg; - try { - msg = processMessage(buffer, header); - } catch (IOException io) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Failed to parse a message from buffer. closing connection", io); - } - closeImpl(); - done = true; - break; - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { - transportBindingMeter.messageReceived(initiator, msg, TimeUtils.timeNow() - receiveBeginTime, - header.getContentLengthHeader()); - } - - tcpTransport.incrementMessagesReceived(); - setLastUsed(TimeUtils.timeNow()); - state.set(readState.HEADER); - header = null; - - msgs.add(msg); - } else { - done = true; - break; - } - } - } // while loop - - // prepare the buffer for more data - buffer.compact(); - return msgs; - } - - /** - * A small class for processing individual messages. - */ - private class MessageProcessor implements Runnable { - - private Message msg; - MessageProcessor(Message msg) { - this.msg = msg; - } - public void run() { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("{0} calling EndpointService.demux({1})", - Thread.currentThread(), - msg, inetAddress.getHostAddress(), port)); - } - tcpTransport.endpoint.demux(msg); - } - } - - /** - * return the current connection status. - * - * @return true if there is an active connection to the remote peer, otherwise false. - */ - private boolean isConnected() { - return !closed; - } - - /** - * Return the absolute time in milliseconds at which this Connection was last used. - * - * @return absolute time in milliseconds. - */ - private long getLastUsed() { - return lastUsed; - } - - /** - * Set the last used time for this connection in absolute milliseconds. - * - * @param time absolute time in milliseconds. - */ - private void setLastUsed(long time) { - lastUsed = time; - } - - /** - * Returns the metering object for this tcpTransport - * - * @return the metering object for this tcpTransport - */ - TransportBindingMeter getTransportBindingMeter() { - return transportBindingMeter; - } - - /** - * Returns the remote address - * - * @return the remote address - */ - private EndpointAddress getConnectionAddress() { - // Somewhat confusing but destinationAddress is the name of that thing - // for the welcome message. - return itsWelcome.getDestinationAddress(); - } - - /** - * Returns Remote PeerID - * - * @return Remote PeerID - */ - private ID getDestinationPeerID() { - return itsWelcome.getPeerID(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/TcpTransport.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/TcpTransport.java deleted file mode 100644 index ead443f6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/TcpTransport.java +++ /dev/null @@ -1,1236 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.endpoint.tcp; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.UnknownHostException; -import java.nio.channels.CancelledKeyException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.ClosedSelectorException; -import java.nio.channels.IllegalBlockingModeException; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.SocketChannel; -import java.nio.channels.spi.SelectorProvider; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.EmptyStackException; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.Stack; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executor; -import java.util.concurrent.RejectedExecutionException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.MessageReceiver; -import net.jxta.endpoint.MessageSender; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.MessengerEvent; -import net.jxta.endpoint.MessengerEventListener; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.logging.Logging; -import net.jxta.meter.MonitorResources; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.TransportAdvertisement; - -import net.jxta.impl.endpoint.IPUtils; -import net.jxta.impl.endpoint.LoopbackMessenger; -import net.jxta.impl.endpoint.transportMeter.TransportBindingMeter; -import net.jxta.impl.endpoint.transportMeter.TransportMeter; -import net.jxta.impl.endpoint.transportMeter.TransportMeterBuildSettings; -import net.jxta.impl.endpoint.transportMeter.TransportServiceMonitor; -import net.jxta.impl.meter.MonitorManager; -import net.jxta.impl.peergroup.StdPeerGroup; -import net.jxta.impl.protocol.TCPAdv; -import net.jxta.impl.util.TimeUtils; - - -/** - * This class implements the TCP Message Transport. - * - * @see net.jxta.endpoint.MessageTransport - * @see net.jxta.endpoint.MessagePropagater - * @see net.jxta.endpoint.MessageReceiver - * @see net.jxta.endpoint.MessageSender - * @see net.jxta.endpoint.EndpointService - * @see JXTA Protocols Specification : Standard JXTA Transport Bindings - */ -public class TcpTransport implements Module, MessageSender, MessageReceiver { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(TcpTransport.class.getName()); - - /** - * The TCP send buffer size. - * The size of the buffer used to store outgoing messages - * This should be set to the maximum message size (smaller is allowed). - */ - static final int SendBufferSize = 64 * 1024; // 64 KBytes - - /** - * The TCP receive buffer size - */ - static final int RecvBufferSize = 64 * 1024; // 64 KBytes - - /** - * The amount of time the socket "lingers" after we close it locally. - * Linger enables the remote socket to finish receiving any pending data - * at its own rate. - * Note: LingerDelay time unit is seconds - */ - static final int LingerDelay = 2 * 60; - - /** - * Connection timeout - * use the same system property defined by URLconnection, otherwise default to 10 seconds. - */ - static int connectionTimeOut = 10 * (int) TimeUtils.ASECOND; - - // Java's default is 50 - static final int MaxAcceptCnxBacklog = 50; - - private String serverName = null; - private final List publicAddresses = new ArrayList(); - private EndpointAddress publicAddress = null; - - private String interfaceAddressStr; - InetAddress usingInterface; - private int serverSocketPort; - private int restrictionPort = -1; - private IncomingUnicastServer unicastServer = null; - - private boolean isClosed = false; - - private long messagesSent = 0; - private long messagesReceived = 0; - private long bytesSent = 0; - private long bytesReceived = 0; - private long connectionsAccepted = 0; - - PeerGroup group = null; - EndpointService endpoint = null; - Executor executor; - - private String protocolName = "tcp"; - private TransportMeter unicastTransportMeter; - private TransportMeter multicastTransportMeter; - - private boolean publicAddressOnly = false; - - private MessengerEventListener messengerEventListener = null; - - private Thread messengerSelectorThread; - Selector messengerSelector = null; - - private final Map regisMap = new ConcurrentHashMap(); - private final Set unregisMap = Collections.synchronizedSet(new HashSet()); - - /** - * This is the thread group into which we will place all of the threads - * we create. THIS HAS NO EFFECT ON SCHEDULING. Java thread groups are - * only for organization and naming. - */ - ThreadGroup myThreadGroup = null; - - /** - * The maximum number of write selectors we will maintain in our cache per - * transport instance. - */ - protected final static int MAX_WRITE_SELECTORS = 50; - - /** - * A cache we maintain for selectors writing messages to the socket. - */ - private final static Stack writeSelectorCache = new Stack(); - - /** - * The number of excess write selectors believed to be in the pool. - */ - private int extraWriteSelectors = 0; - - /** - * Construct a new TcpTransport instance - */ - public TcpTransport() { - // Add some selectors to the pool. - try { - for (int i = 0; i < MAX_WRITE_SELECTORS; i++) { - writeSelectorCache.add(Selector.open()); - } - } catch (IOException ex) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Failed adding selector to write selector pool"); - } - } - - try { - String connectTOStr = System.getProperty("sun.net.client.defaultConnectTimeout"); - - if (connectTOStr != null) { - connectionTimeOut = Integer.parseInt(connectTOStr); - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not parse system property: sun.net.client.defaultConnectTimeout"); - } - } - } - - /** - * Gets the number of 'connectionsAccepted'. - * - * @return the number of 'connectionsAccepted'. - */ - public long getConnectionsAccepted() { - return connectionsAccepted; - } - - /** - * increment the number of connectionsAccepted sent by 1 - */ - public void incrementConnectionsAccepted() { - connectionsAccepted++; - } - - /** - * increment the number of messages sent by 1 - */ - public void incrementMessagesSent() { - messagesSent++; - } - - /** - * increment the number of messages received by 1 - */ - public void incrementMessagesReceived() { - messagesReceived++; - } - - /** - * increment the number of bytes sent - * - * @param bytes the number of bytes to be added - */ - public void incrementBytesSent(long bytes) { - bytesSent += bytes; - } - - /** - * increment the number of bytes received - * - * @param bytes the number of bytes to be added - */ - public void incrementBytesReceived(long bytes) { - bytesReceived += bytes; - } - - /** - * Gets the number of 'messagesSent'. - * - * @return the number of 'messagesSent'. - */ - public long getMessagesSent() { - return messagesSent; - } - - /** - * Gets the number of 'messagesReceived'. - * - * @return the number of 'messagesReceived'. - */ - public long getMessagesReceived() { - return messagesReceived; - } - - /** - * Gets the number of 'bytesSent'. - * - * @return the number of 'bytesSent'. - */ - public long getBytesSent() { - return bytesSent; - } - - /** - * Gets the number of 'bytesReceived'. - * - * @return the number of 'bytesReceived'. - */ - public long getBytesReceived() { - return bytesReceived; - } - - /** - * {@inheritDoc} - */ - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (null == target) { - return false; - } - - if (target instanceof TcpTransport) { - TcpTransport likeMe = (TcpTransport) target; - - if (!getProtocolName().equals(likeMe.getProtocolName())) { - return false; - } - - Iterator itsAddrs = likeMe.publicAddresses.iterator(); - - for (EndpointAddress publicAddress1 : publicAddresses) { - if (!itsAddrs.hasNext()) { - return false; - } // it has fewer than i do. - - EndpointAddress mine = publicAddress1; - EndpointAddress its = itsAddrs.next(); - - if (!mine.equals(its)) { - // content didnt match - return false; - } - } - // ran out at the same time? - return (!itsAddrs.hasNext()); - } - return false; - } - - /** - * {@inheritDoc} - */ - public int hashCode() { - return getPublicAddress().hashCode(); - } - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - - this.group = group; - ModuleImplAdvertisement implAdvertisement = (ModuleImplAdvertisement) impl; - - this.executor = ((StdPeerGroup) group).getExecutor(); - - ConfigParams configAdv = group.getConfigAdvertisement(); - - // Get out invariable parameters from the implAdv - XMLElement param = (XMLElement) implAdvertisement.getParam(); - - if (param != null) { - Enumeration list = param.getChildren("Proto"); - - if (list.hasMoreElements()) { - XMLElement pname = list.nextElement(); - protocolName = pname.getTextValue(); - } - } - - // Get our peer-defined parameters in the configAdv - param = (XMLElement) configAdv.getServiceParam(assignedID); - if (null == param) { - throw new IllegalArgumentException(TransportAdvertisement.getAdvertisementType() + " could not be located."); - } - - Enumeration tcpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType()); - - // get the TransportAdv - if (tcpChilds.hasMoreElements()) { - param = tcpChilds.nextElement(); - Attribute typeAttr = param.getAttribute("type"); - - if (!TCPAdv.getAdvertisementType().equals(typeAttr.getValue())) { - throw new IllegalArgumentException("transport adv is not a " + TCPAdv.getAdvertisementType()); - } - - if (tcpChilds.hasMoreElements()) { - throw new IllegalArgumentException("Multiple transport advs detected for " + assignedID); - } - } else { - throw new IllegalArgumentException(TransportAdvertisement.getAdvertisementType() + " could not be located."); - } - - Advertisement paramsAdv = null; - - try { - paramsAdv = AdvertisementFactory.newAdvertisement(param); - } catch (NoSuchElementException notThere) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Could not find parameter document", notThere); - } - } - - if (!(paramsAdv instanceof TCPAdv)) { - throw new IllegalArgumentException("Provided Advertisement was not a " + TCPAdv.getAdvertisementType()); - } - - TCPAdv adv = (TCPAdv) paramsAdv; - - // determine the local interface to use. If the user specifies - // one, use that. Otherwise, use the all the available interfaces. - interfaceAddressStr = adv.getInterfaceAddress(); - if (interfaceAddressStr != null) { - try { - usingInterface = InetAddress.getByName(interfaceAddressStr); - } catch (UnknownHostException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Invalid address for local interface address, using default"); - } - usingInterface = IPUtils.ANYADDRESS; - } - } else { - usingInterface = IPUtils.ANYADDRESS; - } - - serverName = adv.getServer(); - - // Even when server is not enabled, we use the serverSocketPort as a - // discriminant for the simulated network partitioning, human readable - // messages, and a few things of that sort. - serverSocketPort = adv.getPort(); - - // should we expose other than a public address if one was specified? - publicAddressOnly = adv.getPublicAddressOnly(); - - // Start the servers - if (adv.isServerEnabled()) { - try { - unicastServer = new IncomingUnicastServer(this, usingInterface, serverSocketPort, adv.getStartPort(), adv.getEndPort()); - } catch (IOException failed) { - throw new PeerGroupException("Failed to open server socket.", failed); - } - - InetSocketAddress boundAddress = unicastServer.getLocalSocketAddress(); - - // TODO bondolo 20040628 Save the port back as a preference to TCPAdv - /* - if(-1 != adv.getStartPort()) { - adv.setPort(boundAddress.getPort()); - } - */ - - // Build the publicAddresses : - // first in the list is the "public server name". We don't try to - // resolve this since it might not be resolvable in the context we - // are running in, we just assume it's good. - if (serverName != null) { - // use speced server name. - EndpointAddress newAddr = new EndpointAddress(protocolName, serverName, null, null); - publicAddresses.add(newAddr); - } - - // then add the rest of the local interfaces as appropriate. Unless - // we find an non-loopback interface, we're in local only mode. - boolean localOnly = true; - - if (usingInterface.equals(IPUtils.ANYADDRESS)) { - // its wildcarded - Iterator eachLocal = IPUtils.getAllLocalAddresses(); - List wildAddrs = new ArrayList(); - - while (eachLocal.hasNext()) { - InetAddress anAddress = (InetAddress) eachLocal.next(); - String hostAddress = IPUtils.getHostAddress(anAddress); - EndpointAddress newAddr = new EndpointAddress(protocolName, - hostAddress + ":" + Integer.toString(boundAddress.getPort()), null, null); - - // don't add it if its already in the list - if (!anAddress.isLoopbackAddress()) { - localOnly = false; - } - - if (!publicAddresses.contains(newAddr)) { - wildAddrs.add(newAddr); - } - } - - // we sort them so that later equals() will be deterministic. - // the result of IPUtils.getAllLocalAddresses() is not known to - // be sorted. - Collections.sort(wildAddrs, new Comparator() { - public int compare(EndpointAddress one, EndpointAddress two) { - return one.toString().compareTo(two.toString()); - } - - public boolean equals(Object that) { - return (this == that); - } - }); - - // Add public addresses: - // don't add them if we have a hand-set public address and the - // publicAddressOnly property is set. - if (!(serverName != null && publicAddressOnly)) { - publicAddresses.addAll(wildAddrs); - } - } else { - // use specified interface - if (!usingInterface.isLoopbackAddress()) { - localOnly = false; - } - - String hostAddress = IPUtils.getHostAddress(usingInterface); - EndpointAddress newAddr = new EndpointAddress(protocolName, - hostAddress + ":" + Integer.toString(boundAddress.getPort()), null, null); - - // Add public address: - // don't add it if its already in the list - // don't add it if specified as public address and publicAddressOnly - if (!(serverName != null && publicAddressOnly)) { - if (!publicAddresses.contains(newAddr)) { - publicAddresses.add(newAddr); - } - } - } - - // If the only available interface is LOOPBACK, then make sure we - // use only that (that includes resetting the outgoing/listening - // interface from ANYADDRESS to LOOPBACK). - - if (localOnly) { - usingInterface = IPUtils.LOOPBACK; - publicAddresses.clear(); - String hostAddress = IPUtils.getHostAddress(usingInterface); - EndpointAddress pubAddr = new EndpointAddress(protocolName, - hostAddress + ":" + Integer.toString(boundAddress.getPort()), null, null); - - publicAddresses.add(pubAddr); - } - - // Set the "preferred" public address. This is the address we will - // use for identifying outgoing requests. - publicAddress = publicAddresses.get(0); - } else { - // Only the outgoing interface matters. - // Verify that ANY interface does not in fact mean LOOPBACK only. If - // that's the case, we want to make that explicit, so that - // consistency checks regarding the allowed use of that interface - // work properly. - if (usingInterface.equals(IPUtils.ANYADDRESS)) { - boolean localOnly = true; - Iterator eachLocal = IPUtils.getAllLocalAddresses(); - - while (eachLocal.hasNext()) { - InetAddress anAddress = (InetAddress) eachLocal.next(); - - if (!anAddress.isLoopbackAddress()) { - localOnly = false; - break; - } - } - - if (localOnly) { - usingInterface = IPUtils.LOOPBACK; - } - } - - // The "public" address is just an internal label - // it is not usefull to anyone outside. - // IMPORTANT: we set the port to zero, to signify that this address - // is not realy usable. - String hostAddress = IPUtils.getHostAddress(usingInterface); - - publicAddress = new EndpointAddress(protocolName, hostAddress + ":0", null, null); - } - - // Tell tell the world about our configuration. - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring TCP Message Transport : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params:"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID: ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration:"); - configInfo.append("\n\t\tProtocol: ").append(protocolName); - configInfo.append("\n\t\tPublic address: ").append(serverName == null ? "(unspecified)" : serverName); - configInfo.append("\n\t\tInterface address: ").append( - interfaceAddressStr == null ? "(unspecified)" : interfaceAddressStr); - - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tUsing Interface: ").append(usingInterface.getHostAddress()); - - if (null != unicastServer) { - if (-1 == unicastServer.getStartPort()) { - configInfo.append("\n\t\tUnicast Server Bind Addr: ").append(usingInterface.getHostAddress()).append(":").append( - serverSocketPort); - } else { - configInfo.append("\n\t\tUnicast Server Bind Addr: ").append(usingInterface.getHostAddress()).append(":").append(serverSocketPort).append(" [").append(unicastServer.getStartPort()).append("-").append(unicastServer.getEndPort()).append( - "]"); - } - configInfo.append("\n\t\tUnicast Server Bound Addr: ").append(unicastServer.getLocalSocketAddress()); - } else { - configInfo.append("\n\t\tUnicast Server : disabled"); - } - - configInfo.append("\n\t\tPublic Addresses: "); - configInfo.append("\n\t\t\tDefault Endpoint Addr : ").append(publicAddress); - - for (EndpointAddress anAddr : publicAddresses) { - configInfo.append("\n\t\t\tEndpoint Addr : ").append(anAddr); - } - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public synchronized int startApp(String[] arg) { - endpoint = group.getEndpointService(); - - if (null == endpoint) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - return Module.START_AGAIN_STALLED; - } - - try { - messengerSelector = SelectorProvider.provider().openSelector(); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not create a messenger selector", e); - } - } - - messengerSelectorThread = new Thread(group.getHomeThreadGroup(), new MessengerSelectorThread(), "TCP Transport MessengerSelectorThread for " + this); - messengerSelectorThread.setDaemon(true); - messengerSelectorThread.start(); - - // We're fully ready to function. - messengerEventListener = endpoint.addMessageTransport(this); - - if (messengerEventListener == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Transport registration refused"); - } - return -1; - } - - // Cannot start before registration, we could be announcing new messengers while we - // do not exist yet ! (And get an NPE because we do not have the messenger listener set). - - if (unicastServer != null) { - if (!unicastServer.start()) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Unable to start TCP Unicast Server"); - } - return -1; - } - } - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - TransportServiceMonitor transportServiceMonitor = (TransportServiceMonitor) MonitorManager.getServiceMonitor(group, - MonitorResources.transportServiceMonitorClassID); - - if (transportServiceMonitor != null) { - unicastTransportMeter = transportServiceMonitor.createTransportMeter("TCP", publicAddress); - } - } - - isClosed = false; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("TCP Message Transport started."); - } - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - public synchronized void stopApp() { - if (isClosed) { - return; - } - - isClosed = true; - - if (unicastServer != null) { - unicastServer.stop(); - unicastServer = null; - } - - Thread temp = messengerSelectorThread; - - if (null != temp) { - temp.interrupt(); - try { - messengerSelector.close(); - } catch (IOException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "IO error occured while closing server socket", failed); - } - } - } - - // Inform the pool that we don't need as many write selectors. - synchronized (writeSelectorCache) { - extraWriteSelectors += MAX_WRITE_SELECTORS; - } - - endpoint.removeMessageTransport(this); - - endpoint = null; - group = null; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info(MessageFormat.format("Total bytes sent : {0}", getBytesSent())); - LOG.info(MessageFormat.format("Total Messages sent : {0}", getMessagesSent())); - LOG.info(MessageFormat.format("Total bytes received : {0}", getBytesReceived())); - LOG.info(MessageFormat.format("Total Messages received : {0}", getMessagesReceived())); - LOG.info(MessageFormat.format("Total connections accepted : {0}", getConnectionsAccepted())); - - LOG.info("TCP Message Transport shut down."); - } - } - - /** - * {@inheritDoc} - */ - public String getProtocolName() { - return protocolName; - } - - /** - * {@inheritDoc} - */ - public EndpointAddress getPublicAddress() { - return publicAddress; - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - return (EndpointService) endpoint.getInterface(); - } - - /** - * {@inheritDoc} - */ - public Object transportControl(Object operation, Object Value) { - return null; - } - - /** - * {@inheritDoc} - */ - public Iterator getPublicAddresses() { - return Collections.unmodifiableList(publicAddresses).iterator(); - } - - /** - * {@inheritDoc} - */ - public boolean isConnectionOriented() { - return true; - } - - /** - * {@inheritDoc} - */ - public boolean allowsRouting() { - return true; - } - - public Messenger getMessenger(EndpointAddress dst, Object hintIgnored) { - return getMessenger(dst, hintIgnored, true); - } - - /** - * {@inheritDoc} - */ - public Messenger getMessenger(EndpointAddress dst, Object hintIgnored, boolean selfDestruct) { - - if (!dst.getProtocolName().equalsIgnoreCase(getProtocolName())) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Cannot make messenger for protocol: " + dst.getProtocolName()); - } - return null; - } - - EndpointAddress plainAddr = new EndpointAddress(dst, null, null); - - // If the destination is one of our addresses including loopback, we - // return a loopback messenger. - if (publicAddresses.contains(plainAddr)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("return LoopbackMessenger for addr : " + dst); - } - return new LoopbackMessenger(group, endpoint, getPublicAddress(), dst, - new EndpointAddress("jxta", group.getPeerID().getUniqueValue().toString(), null, null)); - } - - try { - // Right now we do not want to "announce" outgoing messengers because they get pooled and so must - // not be grabbed by a listener. If "announcing" is to be done, that should be by the endpoint - // and probably with a subtely different interface. - return new TcpMessenger(dst, this, selfDestruct); - } catch (Exception caught) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.log(Level.FINER, "Could not get messenger for " + dst, caught); - } else { - LOG.warning("Could not get messenger for " + dst + " : " + caught.getMessage()); - } - } - if (caught instanceof RuntimeException) { - throw (RuntimeException) caught; - } - return null; - } - } - - /** - * {@inheritDoc} - *

            - * This implementation tries to open a connection, and after tests the - * result. - */ - public boolean ping(EndpointAddress addr) { - boolean result = false; - EndpointAddress endpointAddress; - long pingStartTime = 0; - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - pingStartTime = System.currentTimeMillis(); - } - - endpointAddress = new EndpointAddress(addr, null, null); - - try { - // Too bad that this one will not get pooled. On the other hand ping is - // not here too stay. - TcpMessenger tcpMessenger = new TcpMessenger(endpointAddress, this); - - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - TransportBindingMeter transportBindingMeter = tcpMessenger.getTransportBindingMeter(); - - if (transportBindingMeter != null) { - transportBindingMeter.ping(System.currentTimeMillis() - pingStartTime); - } - } - result = true; - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failure pinging " + addr.toString(), e); - } - if (TransportMeterBuildSettings.TRANSPORT_METERING) { - TransportBindingMeter transportBindingMeter = getUnicastTransportBindingMeter(null, endpointAddress); - - if (transportBindingMeter != null) { - transportBindingMeter.pingFailed(System.currentTimeMillis() - pingStartTime); - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("ping to " + addr.toString() + " == " + result); - } - return result; - } - - /** - * Getter for property 'restrictionPort'. - * - * @return Value for property 'restrictionPort'. - */ - int getRestrictionPort() { - return restrictionPort; - } - - TransportBindingMeter getUnicastTransportBindingMeter(PeerID peerID, EndpointAddress destinationAddress) { - if (unicastTransportMeter != null) { - return unicastTransportMeter.getTransportBindingMeter( - (peerID != null) ? peerID.toString() : TransportMeter.UNKNOWN_PEER, destinationAddress); - } else { - return null; - } - } - - void messengerReadyEvent(Messenger newMessenger, EndpointAddress connAddr) { - messengerEventListener.messengerReady(new MessengerEvent(this, newMessenger, connAddr)); - } - - /** - * Getter for property 'server'. - * - * @return Value for property 'server'. - */ - IncomingUnicastServer getServer() { - return unicastServer; - - } - - /** - * Get a write selector from the cache. - * - * @return A write selector. - * @throws InterruptedException If interrupted while waiting for a selector - * to become available. - */ - Selector getSelector() throws InterruptedException { - synchronized (writeSelectorCache) { - Selector selector = null; - try { - if (!writeSelectorCache.isEmpty()) { - selector = writeSelectorCache.pop(); - } - } catch (EmptyStackException ese) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No write selector available, waiting for one"); - } - } - - int attempts = 0; - while (selector == null && attempts < 2) { - writeSelectorCache.wait(connectionTimeOut); - try { - if (!writeSelectorCache.isEmpty()) { - selector = writeSelectorCache.pop(); - } - } catch (EmptyStackException ese) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Failed to get a write selector available, waiting for one", ese); - } - } - attempts++; - } - - return selector; - } - } - - /** - * Return the Selector to the cache - * - * @param selector the selector to put back into the pool - */ - void returnSelector(Selector selector) { - synchronized (writeSelectorCache) { - if (extraWriteSelectors > 0) { - // Allow the selector to be discarded. - extraWriteSelectors--; - } else { - writeSelectorCache.push(selector); - // it does not hurt to notify, even if there are no waiters - writeSelectorCache.notify(); - } - } - } - - /** - * Waits for incoming data on channels and sends it to the appropriate - * messenger object. - */ - private class MessengerSelectorThread implements Runnable { - - /** - * {@inheritDoc} - */ - public void run() { - try { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("MessengerSelectorThread polling started"); - } - - while (!isClosed) { - try { - int selectedKeys = 0; - - // Update channel registerations. - updateChannelRegisterations(); - - try { - // this can be interrupted through wakeup - selectedKeys = messengerSelector.select(); - } catch (CancelledKeyException cke) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Key was cancelled", cke); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("MessengerSelector has {0} selected keys", selectedKeys)); - } - - if (selectedKeys == 0 && messengerSelector.selectNow() == 0) { - // We were probably just woken. - continue; - } - - Set keySet = messengerSelector.selectedKeys(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("KeySet has {0} selected keys", keySet.size())); - } - - Iterator it = keySet.iterator(); - - while (it.hasNext()) { - SelectionKey key = it.next(); - - // remove it from the SelectedKeys Set - it.remove(); - - if (key.isValid()) { - try { - if (key.isReadable() && key.channel().isOpen()) { - // ensure this channel is not selected again until the thread is done with it - // TcpMessenger is expected to reset the interestOps back to OP_READ - // Without this, expect multiple threads to execute on the same event, until - // the first thread completes reading all data available - key.interestOps(key.interestOps() & ~SelectionKey.OP_READ); - - // get the messenger - TcpMessenger msgr = (TcpMessenger) key.attachment(); - - // process the data - try { - executor.execute(msgr); - } catch (RejectedExecutionException re) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, - MessageFormat.format("Executor rejected task for messenger :{0}", msgr.toString()), re); - } - } - } - } catch (CancelledKeyException cce) { - //in case the key was canceled after the selection - } - } else { - // unregister it, no need to keep invalid/closed channels around - try { - key.channel().close(); - } catch (IOException io) { - // avoids breaking out of the selector loop - } - key.cancel(); - key = null; - } - } - } catch (ClosedSelectorException cse) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("IO Selector closed"); - } - } catch (InterruptedIOException woken) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Thread inturrupted", woken); - } - } catch (IOException e1) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "An exception occurred while selecting keys", e1); - } - } catch (SecurityException e2) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "A security exception occurred while selecting keys", e2); - } - } - } - - // XXX 20070205 bondolo What should we do about the channels - // that are still registered with the selector and any pending - // updates? - - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && Logging.SHOW_SEVERE) { - LOG.log(Level.SEVERE, "Uncaught Throwable", all); - } - } finally { - messengerSelectorThread = null; - } - } - } - - /** - * Registers the channel with the Read selector and attaches the messenger to the channel - * - * @param channel the socket channel. - * @param messenger the messenger to attach to the channel. - */ - void register(SocketChannel channel, TcpMessenger messenger) { - regisMap.put(messenger, channel); - messengerSelector.wakeup(); - } - - /** - * Unregisters the channel with the Read selector - * - * @param channel the socket channel. - */ - void unregister(SocketChannel channel) { - unregisMap.add(channel); - messengerSelector.wakeup(); - } - - /** - * Registers all newly accepted and returned (by TcpMessenger) channels. - * Removes all closing TcpMessengers. - */ - private synchronized void updateChannelRegisterations() { - - if (!regisMap.isEmpty() && Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Registering {0} channels with MessengerSelectorThread", regisMap.size())); - } - - if (!regisMap.isEmpty()) { - Iterator> eachMsgr = regisMap.entrySet().iterator(); - - while (eachMsgr.hasNext()) { - Map.Entry anEntry = eachMsgr.next(); - TcpMessenger msgr = anEntry.getKey(); - SocketChannel channel = anEntry.getValue(); - SelectionKey key = channel.keyFor(messengerSelector); - - try { - if (key == null) { - key = channel.register(messengerSelector, SelectionKey.OP_READ, msgr); - } - key.interestOps(key.interestOps() | SelectionKey.OP_READ); - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer(MessageFormat.format("Key interestOps on channel {0}, bit set :{1}", channel, key.interestOps())); - } - } catch (ClosedChannelException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Failed to register Channel with messenger selector", e); - } - // it's best a new messenger is created when a new messenger is requested - msgr.close(); - } catch (CancelledKeyException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Key is already cancelled, removing key from registeration map", e); - } - } catch (IllegalBlockingModeException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Invalid blocking channel mode, closing messenger", e); - } - // messenger state is unknown - msgr.close(); - } - // remove it from the table - eachMsgr.remove(); - } - } - - // Unregister and close channels. - if (!unregisMap.isEmpty() && Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Unregistering {0} channels with MessengerSelectorThread", unregisMap.size())); - } - if (!unregisMap.isEmpty()) { - Iterator eachChannel; - - synchronized (unregisMap) { - List allChannels = new ArrayList(unregisMap); - unregisMap.clear(); - eachChannel = allChannels.iterator(); - } - - while (eachChannel.hasNext()) { - SocketChannel aChannel = eachChannel.next(); - SelectionKey key = aChannel.keyFor(messengerSelector); - if (null != key) { - try { - key.cancel(); - } catch (CancelledKeyException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Key is already cancelled, removing key from registeration map", e); - } - } - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/package.html deleted file mode 100644 index c3103497..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tcp/package.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - -A JXTA {@link net.jxta.endpoint.MessageTransport} implementation which uses raw TCP/IP sockets. - -@see net.jxta.endpoint.EndpointService -@see net.jxta.endpoint.MessageTransport -@see net.jxta.endpoint.MessageSender -@see net.jxta.endpoint.MessageReceiver -@see net.jxta.endpoint.Message -@see JXTA Protocols - Specification : Standard JXTA Transport Bindings - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/JTlsDefs.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/JTlsDefs.java deleted file mode 100644 index 5215f08f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/JTlsDefs.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.tls; - - -import net.jxta.document.MimeMediaType; - - -public class JTlsDefs { - // Until we decide otherwise, the tls is *by definition* handling - // peerID addressed messages. - static String tlsPName = "jxtatls"; - - static final String TLSNameSpace = "jxtatls"; // our name space - - static final String ServiceName = "TlsTransport"; - - static final int FAKEPORT = 1376911; // for TLS hashing only - - static final String ACKKEY = "TLSACK"; - static final String RETR = "MARKRetr"; - - static final MimeMediaType MTYPE = new MimeMediaType("application/x-jxta-msg"); - static final MimeMediaType BLOCKS = new MimeMediaType("application/x-jxta-tls-block"); - static final MimeMediaType ACKS = new MimeMediaType("application/x-jxta-tls-ack"); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/JTlsInputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/JTlsInputStream.java deleted file mode 100644 index cbebd9f4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/JTlsInputStream.java +++ /dev/null @@ -1,590 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.tls; - - -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.InputStream; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.io.InterruptedIOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import net.jxta.endpoint.ByteArrayMessageElement; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.impl.util.TimeUtils; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * Acts as the input for TLS. Accepts ciphertext which arrives in messages - * and orders it before passing it to TLS for decryption. - * - * TLS will do its raw reads off of this InputStream - * Here, we will have queued up the payload of TLS message - * elements to be passed to TLS code as TLS Records. - * - */ -class JTlsInputStream extends InputStream { - private static final Logger LOG = Logger.getLogger(JTlsInputStream.class.getName()); - - private static final boolean DEBUGIO = false; - - static private int MAXQUEUESIZE = 25; - - /** - * Connection we are working for. - */ - private TlsConn conn; - - private volatile boolean closed = false; - private boolean closing = false; - - private long timeout = 2 * TimeUtils.AMINUTE; - private JTlsRecord jtrec = null; - private volatile int sequenceNumber = 0; - private final Vector inputQueue = new Vector(MAXQUEUESIZE); // For incoming messages. - - /** - * Input TLS record Object - **/ - private static class JTlsRecord { - // This dummy message elt - public InputStream tlsRecord; // TLS Record - public long nextByte; // next inbuff byte - public long size; // size of TLS Record - - public JTlsRecord() { - tlsRecord = null; // allocated by caller - nextByte = 0; // We read here (set by caller) - size = 0; // TLS Record size(set by caller) - } - - // reset the jxta tls record element - - public void resetRecord() { - if (null != tlsRecord) { - try { - tlsRecord.close(); - } catch (IOException ignored) {// ignored - } - } - tlsRecord = null; - size = nextByte = 0; - } - } - - - // An input queue element which breaks out a - // received message in enqueueMessage(). - private static class IQElt { - int seqnum; - MessageElement elt; - boolean ackd; - } - - public JTlsInputStream(TlsConn conn, long timeout) { - this.timeout = timeout; - this.conn = conn; - jtrec = new JTlsRecord(); - // 1 <= seq# <= maxint, monotonically increasing - // Incremented before compare. - sequenceNumber = 0; - - } - - /** - * {@inheritDoc} - **/ - @Override - public void close() throws IOException { - super.close(); - - closed = true; - synchronized (inputQueue) { - inputQueue.clear(); - inputQueue.notifyAll(); - } - } - - /** - * prepare this input stream to being closed. It will still - * deliver the packets that have been received, but nothing - * more. This is meant to be called in response to the other side - * having initiated closure. We assume that when the other side does it - * it means that it is satified with what we have acknoleged so far. - */ - public void setClosing() throws IOException { - synchronized (inputQueue) { - closing = true; - inputQueue.notifyAll(); - } - } - - // Here we read the TLS Record data from the incoming JXTA message. - // (We will really have a full jxta message available.) - // - // TLS Record input only calls the following methods. - // They are called from SSLRecord.decode(SSLConn, Inputstream); - // - - /** - * {@inheritDoc} - */ - @Override - public int read() throws IOException { - if (closed) { - return -1; - } - - byte[] a = new byte[1]; - - while (true) { - int len = local_read(a, 0, 1); - - if (len < 0) { - break; - } - - if (len > 0) { - if (DEBUGIO && Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Read() : " + (a[0] & 255)); - } - - return (a[0] & 0xFF); // The byte - } - } - // If we've reached EOF, there's nothing to do but close(). - - close(); - return -1; - } - - /** - * {@inheritDoc} - */ - @Override - public int read(byte[] a, int offset, int length) throws IOException { - if (closed) { - return -1; - } - - if (0 == length) { - return 0; - } - - int i = local_read(a, offset, length); - - if (DEBUGIO && Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Read(byte[], int, " + length + "), bytes read = " + i); - } - - // If we've reached EOF; there's nothing to do but close(). - if (i == -1) { - close(); - } - return i; - } - - // protected accessor for sequence number - int getSequenceNumber() { - return sequenceNumber; - } - - // Our input queue max size - int getMaxIQSize() { - return MAXQUEUESIZE; - } - - /** - * Send a sequential ACK and selective ACKs for all of the queued messages. - * - * @param seqnAck the sequence number being sequential ACKed - **/ - private void sendACK(int seqnAck) { - List selectedAckList = new ArrayList(); - - synchronized (inputQueue) { - Iterator eachInQueue = inputQueue.iterator(); - - while (eachInQueue.hasNext() && (selectedAckList.size() < MAXQUEUESIZE)) { - IQElt anIQElt = eachInQueue.next(); - - if (anIQElt.seqnum > seqnAck) { - selectedAckList.add(new Integer(anIQElt.seqnum)); - } - } - } - - // PERMIT DUPLICATE ACKS. Just a list and one small message. - sendACK(seqnAck, selectedAckList); - } - - /** - * Build an ACK message. The message provides a sequential ACK count and - * an optional list of selective ACKs. - * - * @param seqnAck the sequence number being sequential ACKed - * @param sackList a list of selective ACKs. Must be sorted in increasing - * order. - */ - private void sendACK(int seqnAck, List sackList) { - ByteArrayOutputStream bos = new ByteArrayOutputStream((1 + sackList.size()) * 4); - DataOutputStream dos = new DataOutputStream(bos); - - try { - dos.writeInt(seqnAck); - - Iterator eachSACK = sackList.iterator(); - - while (eachSACK.hasNext()) { - int aSack = (eachSACK.next()).intValue(); - - dos.writeInt(aSack); - } - dos.close(); - bos.close(); - - Message ACKMsg = new Message(); - MessageElement elt = new ByteArrayMessageElement(JTlsDefs.ACKKEY, JTlsDefs.ACKS, bos.toByteArray(), null); - - ACKMsg.addMessageElement(JTlsDefs.TLSNameSpace, elt); - - conn.sendToRemoteTls(ACKMsg); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("SENT ACK, seqn#" + seqnAck + " and " + sackList.size() + " SACKs "); - } - } catch (IOException e) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "sendACK caught IOException:", e); - } - } - } - - /** - * queue messages by sequence number. - */ - public void queueIncomingMessage(Message msg) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Queue Incoming Message begins for " + msg); - } - - long startEnqueue = TimeUtils.timeNow(); - - Message.ElementIterator e = msg.getMessageElements(JTlsDefs.TLSNameSpace, JTlsDefs.BLOCKS); - - // OK look for jxta message - while (!closed && !closing && e.hasNext()) { - MessageElement elt = e.next(); - - e.remove(); - - int msgSeqn = 0; - - try { - msgSeqn = Integer.parseInt(elt.getElementName()); - } catch (NumberFormatException n) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Discarding element (" + elt.getElementName() + ") Not one of ours."); - } - continue; - } - - IQElt newElt = new IQElt(); - - newElt.seqnum = msgSeqn; - newElt.elt = elt; - newElt.ackd = false; - - // OK we must inqueue: - // Wait until someone dequeues if we are at the size limit - // see if this is a duplicate - if (newElt.seqnum <= sequenceNumber) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RCVD OLD MESSAGE : Discard seqn#" + newElt.seqnum + " now at seqn#" + sequenceNumber); - } - break; - } - synchronized (inputQueue) { - // dbl check with the lock held. - if (closing || closed) { - return; - } - - // Insert this message into the input queue. - // 1. Do not add duplicate messages - // 2. Store in increasing sequence nos. - int insertIndex = inputQueue.size(); - boolean duplicate = false; - - for (int j = 0; j < inputQueue.size(); j++) { - IQElt iq = inputQueue.elementAt(j); - - if (newElt.seqnum < iq.seqnum) { - insertIndex = j; - break; - } else if (newElt.seqnum == iq.seqnum) { - duplicate = true; - break; - } - } - - if (duplicate) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RCVD OLD MESSAGE : Discard duplicate msg, seqn#" + newElt.seqnum); - } - newElt = null; - break; - } - - inputQueue.add(insertIndex, newElt); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Enqueued msg with seqn#" + newElt.seqnum + " at index " + insertIndex); - } - - inputQueue.notifyAll(); - newElt = null; - } - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - long waited = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), startEnqueue); - - LOG.fine("Queue Incoming Message for " + msg + " completed in " + waited + " msec."); - } - } - - /** - * Dequeue the message with the desired sequence number waiting as needed - * until the message is available. - * - * @param desiredSeqn the sequence number to be dequeued. - * @return the Message Element with the desired sequence number or null if - * the queue has been closed. - **/ - private MessageElement dequeueMessage(int desiredSeqn) throws IOException { - IQElt iQ = null; - - // Wait for incoming message here - long startDequeue = TimeUtils.timeNow(); - long whenToTimeout = startDequeue + timeout; - int wct = 0; - - long nextRetransRequest = TimeUtils.toAbsoluteTimeMillis(TimeUtils.ASECOND); - - synchronized (inputQueue) { - while (!closed) { - if (inputQueue.size() == 0) { - if (closing) { - return null; - } - try { - wct++; - inputQueue.wait(TimeUtils.ASECOND); - if (whenToTimeout < TimeUtils.timeNow()) { - throw new SocketTimeoutException("Read timeout reached"); - } - } catch (InterruptedException e) { - Thread.interrupted(); // just continue - } - // we reset the retrans request timer since we don't want to - // immediately request retry after a long wait for out of - // order messages. - - nextRetransRequest = TimeUtils.toAbsoluteTimeMillis(TimeUtils.ASECOND); - continue; - } - - iQ = inputQueue.elementAt(0); // FIFO - - if (iQ.seqnum < desiredSeqn) { - // Ooops a DUPE slipped in the head of the queue undetected - // (seqnum consistency issue). - // Just drop it. - inputQueue.remove(0); - // if such is the case then notify the other end so that - // the message does not remain in the retry queue eventually - // triggering a broken pipe exception - sendACK(iQ.seqnum); - continue; - } else if (iQ.seqnum != desiredSeqn) { - if (TimeUtils.toRelativeTimeMillis(nextRetransRequest) < 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Trigger retransmission. Wanted seqn#" + desiredSeqn + " found seqn#" + iQ.seqnum); - } - sendACK(desiredSeqn - 1); - nextRetransRequest = TimeUtils.toAbsoluteTimeMillis(TimeUtils.ASECOND); - } - - try { - wct++; - inputQueue.wait(TimeUtils.ASECOND); - if (whenToTimeout < TimeUtils.timeNow()) { - throw new SocketTimeoutException("Read timeout reached"); - } - } catch (InterruptedException e) { - throw new InterruptedIOException("IO interrupted "); - } - continue; - } - - inputQueue.remove(0); - break; - } - } - - nextRetransRequest = 0; - sendACK(desiredSeqn); - // if we are closed then we return null - if (null == iQ) { - return null; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - long waited = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), startDequeue); - - LOG.info("DEQUEUED seqn#" + iQ.seqnum + " in " + waited + " msec on input queue"); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - if (wct > 0) { - LOG.fine("DEQUEUE waited " + wct + " times on input queue"); - } - } - } - - return iQ.elt; - } - - /** - * - */ - private int local_read(byte[] a, int offset, int length) throws IOException { - - synchronized (jtrec) { - if ((jtrec.size == 0) || (jtrec.nextByte == jtrec.size)) { - - // reset the record - jtrec.resetRecord(); // GC as necessary(tlsRecord byte[]) - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("local_read: getting next data block at seqn#" + (sequenceNumber + 1)); - } - - MessageElement elt = null; - - try { - elt = dequeueMessage(sequenceNumber + 1); - } catch (SocketTimeoutException ste) { - // timed out with no data - // SSLSocket expects a 0 data in this case - return 0; - } - - if (null == elt) { - return -1; - } - - sequenceNumber += 1; // next msg sequence number - - // Get the length of the TLS Record - jtrec.size = elt.getByteLength(); - jtrec.tlsRecord = elt.getStream(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("local_read: new seqn#" + sequenceNumber + ", bytes = " + jtrec.size); - } - } - - // return the requested TLS Record data - // These calls should NEVER ask for more data than is in the - // received TLS Record. - - long left = jtrec.size - jtrec.nextByte; - int copyLen = (int) Math.min(length, left); - int copied = 0; - - do { - int res = jtrec.tlsRecord.read(a, offset + copied, copyLen - copied); - - if (res < 0) { - break; - } - - copied += res; - } while (copied < copyLen); - - jtrec.nextByte += copied; - - if (DEBUGIO) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("local_read: Requested " + length + ", Read " + copied + " bytes"); - } - } - - return copied; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/JTlsOutputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/JTlsOutputStream.java deleted file mode 100644 index ab11a5b0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/JTlsOutputStream.java +++ /dev/null @@ -1,964 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.tls; - - -import java.io.OutputStream; -import java.io.IOException; -import java.net.*; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Vector; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.endpoint.ByteArrayMessageElement; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; - -import net.jxta.impl.endpoint.tls.TlsConn.HandshakeState; -import net.jxta.impl.util.TimeUtils; - - -/** - * Acts as the output for TLS. Accepts ciphertext from TLS and packages it into - * messages for sending to the remote. The messages are kept in a retry queue - * until the remote peer acknowledges receipt of the message. - **/ -class JTlsOutputStream extends OutputStream { - - /** - * Log4J Logger - **/ - private static final Logger LOG = Logger.getLogger(JTlsOutputStream.class.getName()); - - // constants - - /** - * This maximum is only enforced if we have not heard - * from the remote for RETRMAXAGE. - **/ - private static final int MAXRETRQSIZE = 100; - - /** - * Initial estimated Round Trip Time - **/ - private static final long initRTT = 1 * TimeUtils.ASECOND; - - private static final MessageElement RETELT = new StringMessageElement(JTlsDefs.RETR, "TLSRET", null); - - /** - * Retrans window. When reached, we up the RTO. - **/ - private static final int RWINDOW = 5; - - /** - * If true then the stream has been closed. - **/ - private volatile boolean closed = false; - - /** - * If true then the stream is being closed. - * It means that it still works completely for all messages already - * queued, but no new message may be enqueued. - **/ - private volatile boolean closing = false; - - /** - * Sequence number of the message we most recently sent out. - **/ - private volatile int sequenceNumber = 0; - - /** - * Sequence number of highest sequential ACK. - **/ - private volatile int maxACK = 0; - - /** - * Transport we are working for - **/ - private TlsTransport tp = null; - - /** - * connection we are working for - **/ - private TlsConn conn = null; - - private Retransmitter retransmitter = null; - - // for retransmission - - /** - * Average round trip time in milliseconds. - **/ - private volatile long aveRTT = initRTT; - - /** - * Number of ACK message received. - **/ - private int nACKS = 0; - - /** - * Retry Time Out measured in milliseconds. - **/ - private volatile long RTO = 0; - - /** - * Minimum Retry Timeout measured in milliseconds. - **/ - private volatile long minRTO = initRTT; - - /** - * Maximum Retry Timeout measured in milliseconds. - **/ - private volatile long maxRTO = initRTT * 5; - - /** - * absolute time in milliseconds of last sequential ACK. - **/ - private volatile long lastACKTime = 0; - - /** - * absolute time in milliseconds of last SACK based retransmit. - **/ - private volatile long sackRetransTime = 0; - - /** - * The collection of messages available for re-transmission. - */ - final List retrQ = new Vector(25, 5); - - // running average of receipients Input Queue - private int nIQTests = 0; - private int aveIQSize = 0; - - /** - * Our estimation of the current free space in the remote input queue. - **/ - private volatile int mrrIQFreeSpace = 0; - - /** - * Our estimation of the maximum sise of the remote input queue. - **/ - private int rmaxQSize = 0; - - /** - * retrans queue element - **/ - private static class RetrQElt { - int seqnum; // sequence number of this message. - long enqueuedAt; // absolute time of original enqueing. - volatile Message msg; // the message - int marked; // has been marked as retransmission - long sentAt; // when this msg was last transmitted - - public RetrQElt(int seqnum, Message msg) { - this.seqnum = seqnum; - this.msg = msg; - this.enqueuedAt = TimeUtils.timeNow(); - this.sentAt = this.enqueuedAt; - this.marked = 0; - } - } - - JTlsOutputStream(TlsTransport tp, TlsConn conn) { - this.conn = conn; // TlsConnection. - this.tp = tp; // our transport - - this.RTO = minRTO; // initial RTO - - // input free queue size - this.rmaxQSize = 20; - this.mrrIQFreeSpace = rmaxQSize; - - // Init last ACK Time to now - this.lastACKTime = TimeUtils.timeNow(); - this.sackRetransTime = TimeUtils.timeNow(); - - // Start retransmission thread - this.retransmitter = new Retransmitter(); - } - - /** - * {@inheritDoc} - * - *

            We don't current support linger. - **/ - @Override - public void close() throws IOException { - synchronized (this) { - super.close(); - closed = true; - } - synchronized (retrQ) { - retrQ.notifyAll(); - retrQ.clear(); - } - } - - /** - * indicate that we're in the process of closing. To respect the semantics - * of close()/isClosed(), we do not set the closed flag, yet. Instead, we - * set the flag "closing", which simply garantees that no new message - * will be queued. - * This, in combination with getSequenceNumber and getMaxAck, and - * waitQevent, enables fine grain control of the tear down process. - **/ - public void setClosing() { - synchronized (retrQ) { - closing = true; - retrQ.clear(); - retrQ.notifyAll(); - } - } - - /** - * {@inheritDoc} - **/ - @Override - public void write(int c) throws IOException { - byte[] a = new byte[1]; - - a[0] = (byte) (c & 0xFF); - write(a, 0, 1); - } - - /** - * {@inheritDoc} - * - *

            We override the write(byte[], offset, length); - * method which is called by SSLRecord.send(SSLConn conn) - * via tos.writeTo(conn.sock_out), tos a ByteArrayOutputStream - * which has buffered the TLS output record in the byte array. - * The actual call is write(byte[] b, 0, length); - * - *

            We put this TLS record into a msssage element for the output - * pipe to send along. - * - *

            This is reasonable since in fact, if more than 16K bytes of - * application data are sent, then the max TLS Record is a little - * larger than 16K bytes including the TLS overhead. - * - *

            Therefore, an app. message is N+r TLS Records, - * Message length = Nx16K + r, N >= 0, r >= 0, - * N > 0 || r > 0 true. - **/ - @Override - public void write(byte[] b, int off, int len) throws IOException { - // flag to allow connection closure in finally block - // Connection can not be closed when holding a lock on this - boolean closeStale = false; - // allocate new message - Message jmsg = new Message(); - - try { - if (closed) { - throw new IOException("stream is closed"); - } - if (closing) { - throw new IOException("stream is being closed"); - } - if (b == null) { - throw new IllegalArgumentException("buffer is null"); - } - - if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { - throw new IndexOutOfBoundsException(); - } - - if (len == 0) { - return; - } - - // Copy the data since it will be queued, and caller may - // overwrite the same byte[] buffer. - byte[] data = new byte[len]; - - System.arraycopy(b, off, data, 0, len); - - // sync so that writes don't get out of order. - synchronized (retrQ) { - // add TLS record as element - MessageElement ciphertext = new ByteArrayMessageElement(Integer.toString(++sequenceNumber), JTlsDefs.BLOCKS, data - , - null); - - jmsg.addMessageElement(JTlsDefs.TLSNameSpace, ciphertext); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("TLS CT WRITE : seqn#" + sequenceNumber + " length=" + len); - } - - // (1) See if the most recent remote input queue size is close to - // it's maximum input queue size - // Send only if at least 20% or more of the queue is free. - // (2) Also, if our retransQ is larger than the remotes inputQ, - // wait until we've received an ack. - // We assume some msgs are in transit or the remote system buffers - // We do not want to overrun the receiver. - // (3) We need to release from the loop because of possible deadlocks - // EG: retrQ.size() == 0 and mrrIQFreeSpace forces looping - // forever because the most recent SACK cleared it, and the receiver - // is waiting for more data. - - // max of 200ms wait - int maxwait = Math.min((int) aveRTT, 200); - // iterations to wait (max 3, min 1) - int waitCt = Math.max(maxwait / 60, 1); - - // check if the queue has gone dead. - if (retrQ.size() > 0) { - long inQueue = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), retrQ.get(0).enqueuedAt); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("write : Retry queue idle for " + inQueue); - } - - if (inQueue > tp.RETRMAXAGE) { - if (inQueue > (2 * tp.RETRMAXAGE)) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Closing stale connection " + conn); - } - // SPT - set flag for connection close in finally block - closeStale = true; - throw new IOException("Stale connection closure in progress"); - } else if (retrQ.size() >= MAXRETRQSIZE) { - // if the the queue is "full" and we are long idle, delay new writes forever. - waitCt = Integer.MAX_VALUE; - } - } - } - - int i = 0; - - while (!closed && ((mrrIQFreeSpace < rmaxQSize / 5) || (retrQ.size() > rmaxQSize))) { - - // see if max. wait has arrived. - if (i++ == waitCt) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("write() wait for ACK, maxwait timer expired while enqueuing seqn#" + sequenceNumber); - } - break; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("write() wait 60ms for ACK while enqueuing seqn#" + sequenceNumber + "\n\tremote IQ free space = " - + mrrIQFreeSpace + "\n\tMIN free space to continue = " + (rmaxQSize / 5) + "" + "\n\tretQ.size()=" - + retrQ.size()); - } - - // Less than 20% free queue space is left. Wait. - try { - retrQ.wait(60); - } catch (InterruptedException ignored) { - Thread.interrupted(); - } - } - - // place copy on retransmission queue - RetrQElt r = new RetrQElt(sequenceNumber, jmsg.clone()); - - retrQ.add(r); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Retrans Enqueue added seqn#" + sequenceNumber + " retQ.size()=" + retrQ.size()); - } - } - - // Here we will send the message to the transport - conn.sendToRemoteTls(jmsg); - // assume we have now taken a slot - mrrIQFreeSpace--; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("TLS CT SENT : seqn#" + sequenceNumber + " length=" + len); - } - } finally { - if (closeStale) { - // The retry queue has really gone stale. - try { - setClosing(); - // in this we close ourself - conn.close(HandshakeState.CONNECTIONDEAD); - } catch (IOException ignored) { - ; - } - } - } - } - - private void calcRTT(long enqueuedAt) { - long dt = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), enqueuedAt); - - if (dt == 0) { - dt += 1; - } - - int n = nACKS; - - nACKS += 1; - - aveRTT = ((n * aveRTT) + dt) / (nACKS); - - // Set retransmission time out: 2.5 x RTT - RTO = (aveRTT << 1) + (aveRTT >> 1); - - // Enforce a min/max - - RTO = Math.max(RTO, minRTO); - RTO = Math.min(RTO, maxRTO); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("TLS!! RTT = " + dt + "ms aveRTT = " + aveRTT + "ms" + " RTO = " + RTO + "ms"); - } - } - - private int calcAVEIQ(int iq) { - int n = nIQTests; - - nIQTests += 1; - - aveIQSize = ((n * aveIQSize) + iq) / nIQTests; - - return aveIQSize; - } - - /** - * Process an ACK Message. We remove ACKed messages from the retry queue. - * We only acknowledge messages received in sequence. - * - * The seqnum is for the largest unacknowledged seqnum - * the receipient has received. - * - * The sackList is a sequence of all of the received - * messages in the sender's input Q. All will be sequence numbers higher - * than the sequential ACK seqnum. - * - * Recepients are passive and only ack upon the receipt - * of an in sequence message. - * - * They depend on our RTO to fill holes in message - * sequences. - **/ - void ackReceived(int seqnum, int[] sackList) { - lastACKTime = TimeUtils.timeNow(); - int numberACKed = 0; - - // remove acknowledged messages from retrans Q. - - synchronized (retrQ) { - maxACK = Math.max(maxACK, seqnum); - - // dump the current Retry queue and the SACK list - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - StringBuilder dumpRETRQ = new StringBuilder("ACK RECEIVE : " + Integer.toString(seqnum)); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - dumpRETRQ.append('\n'); - } - dumpRETRQ.append("\tRETRQ (size=" + retrQ.size() + ")"); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - dumpRETRQ.append(" : "); - for (int y = 0; y < retrQ.size(); y++) { - if (0 != y) { - dumpRETRQ.append(", "); - } - RetrQElt r = retrQ.get(y); - - dumpRETRQ.append(r.seqnum); - } - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - dumpRETRQ.append('\n'); - } - dumpRETRQ.append("\tSACKLIST (size=" + sackList.length + ")"); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - dumpRETRQ.append(" : "); - for (int y = 0; y < sackList.length; y++) { - if (0 != y) { - dumpRETRQ.append(", "); - } - dumpRETRQ.append(sackList[y]); - } - } - LOG.fine(dumpRETRQ.toString()); - } - - Iterator eachRetryQueueEntry = retrQ.iterator(); - - // First remove monotonically increasing seq#s in retrans vector - while (eachRetryQueueEntry.hasNext()) { - RetrQElt r = (RetrQElt) eachRetryQueueEntry.next(); - - if (r.seqnum > seqnum) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("r.seqnum :" + r.seqnum + " > seqnum :" + seqnum); - } - break; - } - - // Acknowledged - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("seqnum :" + seqnum); - LOG.fine("Removing :" + r.seqnum + " from retransmit queue"); - } - eachRetryQueueEntry.remove(); - - // Update RTT, RTO - if (0 != r.enqueuedAt) { - calcRTT(r.enqueuedAt); - } - - r.msg.clear(); - r.msg = null; - r = null; - numberACKed++; - } - - // Update last accessed time in response to getting seq acks. - if (numberACKed > 0) { - conn.lastAccessed = TimeUtils.timeNow(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("TLS!! SEQUENTIALLY ACKD SEQN = " + seqnum + ", (" + numberACKed + " acked)"); - } - - // most recent remote IQ free space - rmaxQSize = Math.max(rmaxQSize, sackList.length); - mrrIQFreeSpace = rmaxQSize - sackList.length; - - // let's look at average sacs.size(). If it is big, then this - // probably means we must back off because the system is slow. - // Our retrans Queue can be large and we can overwhelm the - // receiver with retransmissions. - // We will keep the rwin <= ave real input queue size. - int aveIQ = calcAVEIQ(sackList.length); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("remote IQ free space = " + mrrIQFreeSpace + " remote avg IQ occupancy = " + aveIQ); - } - - int retrans = 0; - - if (sackList.length > 0) { - Iterator eachRetrQElement = retrQ.iterator(); - - int currentSACK = 0; - - while (eachRetrQElement.hasNext()) { - RetrQElt r = (RetrQElt) eachRetrQElement.next(); - - while (sackList[currentSACK] < r.seqnum) { - currentSACK++; - if (currentSACK == sackList.length) { - break; - } - } - - if (currentSACK == sackList.length) { - break; - } - - if (sackList[currentSACK] == r.seqnum) { - eachRetrQElement.remove(); - - // ack counter - numberACKed++; - - // for aveRTT calculation - long enqueuetime = r.enqueuedAt; - - // Update RTT, RTO - if (enqueuetime != 0) { - calcRTT(enqueuetime); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("TLS!! SACKD SEQN = " + r.seqnum); - } - - // GC this stuff - r.msg.clear(); - r.msg = null; - r = null; - - } else { - // Retransmit? Only if there is a hole in the selected - // acknowledgement list. Otherwise let RTO deal. - // Given that this SACK acknowledged messages still - // in the retrQ: - // seqnum is the max consectively SACKD message. - // seqnum < r.seqnum means a message has not reached - // receiver. EG: sacklist == 10,11,13 seqnum == 11 - // We retransmit 12. - if (seqnum < r.seqnum) { - retrans++; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETR: Fill hole, SACK, seqn#" + r.seqnum + ", Window =" + retrans); - } - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("TLS!! SELECTIVE ACKD (" + numberACKed + ") " + retrans + " retrans wanted"); - } - - // retransmit 1 retq mem. only - if (retrans > 0) { - retransmit(Math.min(RWINDOW, retrans), lastACKTime); - sackRetransTime = TimeUtils.timeNow(); - } - } - - retrQ.notify(); - } - } - - /** - * retransmit unacknowledged messages - * - * @param rwin max number of messages to retransmit - * @return number of messages retransmitted. - **/ - private int retransmit(int rwin, long triggerTime) { - List retransMsgs = new ArrayList(); - - int numberToRetrans; - - // build a list of retries. - synchronized (retrQ) { - numberToRetrans = Math.min(retrQ.size(), rwin); - - if (numberToRetrans > 0 && Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETRANSMITING [rwindow = " + numberToRetrans + "]"); - } - - for (int j = 0; j < numberToRetrans; j++) { - RetrQElt r = retrQ.get(j); - - // Mark message as retransmission - // need to know if a msg was retr or not for RTT eval - - if (r.marked == 0) { - - // First time: we're here because this message has not arrived, but - // the next one has. It may be an out of order message. - // Experience shows that such a message rarely arrives older than - // 1.2 * aveRTT. Beyond that, it's lost. It is also rare that we - // detect a hole within that delay. So, often enough, as soon as - // a hole is detected, it's time to resend...but not always. - - if (TimeUtils.toRelativeTimeMillis(triggerTime, r.sentAt) < (6 * aveRTT) / 5) { - - // Nothing to worry about, yet. - continue; - } - - } else { - - // That one has been retransmitted at least once already. - // So, we don't have much of a clue other than the age of the - // last transmission. It is unlikely that it arrives before aveRTT/2 - // but we have to anticipate its loss at the risk of making dupes. - // Otherwise the receiver will reach the hole, and that's really - // expensive. (Think that we've been trying for a while already.) - - if (TimeUtils.toRelativeTimeMillis(triggerTime, r.sentAt) < aveRTT) { - - // Nothing to worry about, yet. - continue; - } - } - - r.marked++; - // Make a copy to for sending - retransMsgs.add(r); - } - } - - // send the retries. - int retransmitted = 0; - - Iterator eachRetrans = retransMsgs.iterator(); - - while (eachRetrans.hasNext()) { - RetrQElt r = (RetrQElt) eachRetrans.next(); - - eachRetrans.remove(); - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("TLS!! RETRANSMIT seqn#" + r.seqnum); - } - - Message sending = r.msg; - - // its possible that the message was acked while we were working - // in this case r.msg will have been nulled. - if (null != sending) { - sending = sending.clone(); - sending.replaceMessageElement(JTlsDefs.TLSNameSpace, RETELT); - if (conn.sendToRemoteTls(sending)) { - mrrIQFreeSpace--; // assume we have now taken a slot - retransmitted++; - } else { - break; - } // don't bother continuing. - } - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "FAILED RETRANS seqn#" + r.seqnum, e); - } - break; // don't bother continuing. - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETRANSMITED " + retransmitted + " of " + numberToRetrans); - } - - return retransmitted; - } - - /** - * Retransmission daemon thread - **/ - private class Retransmitter implements Runnable { - - Thread retransmitterThread; - volatile int nretransmitted = 0; - int nAtThisRTO = 0; - - public Retransmitter() { - - this.retransmitterThread = new Thread(tp.myThreadGroup, this, "JXTA TLS Retransmiter for " + conn.destAddr); - retransmitterThread.setDaemon(true); - retransmitterThread.start(); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("STARTED TLS Retransmit thread, RTO = " + RTO); - } - } - - public int getRetransCount() { - return nretransmitted; - } - - /** - * {@inheritDoc] - **/ - public void run() { - - try { - int idleCounter = 0; - - while (!closed) { - long conn_idle = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), conn.lastAccessed); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETRANS : " + conn + " idle for " + conn_idle); - } - - // check to see if we have not idled out. - if (tp.CONNECTION_IDLE_TIMEOUT < conn_idle) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("RETRANS : Shutting down idle connection: " + conn); - } - try { - setClosing(); - // the following call eventually closes this stream - conn.close(HandshakeState.CONNECTIONDEAD); - // Leave. Otherwise we'll be spinning forever - return; - } catch (IOException ignored) { - ; - } - continue; - } - - synchronized (retrQ) { - try { - retrQ.wait(RTO); - } catch (InterruptedException e) { - Thread.interrupted(); - } - } - if (closed) { - break; - } - - // see if we recently did a retransmit triggered by a SACK - long sinceLastSACKRetr = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), sackRetransTime); - - if (sinceLastSACKRetr < RTO) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETRANS : SACK retrans " + sinceLastSACKRetr + "ms ago"); - } - - continue; - } - - // See how long we've waited since RTO was set - long sinceLastACK = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), lastACKTime); - long oldestInQueueWait; - - synchronized (retrQ) { - if (retrQ.size() > 0) { - oldestInQueueWait = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), retrQ.get(0).enqueuedAt); - } else { - oldestInQueueWait = 0; - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETRANS : Last ACK " + sinceLastACK + "ms ago. Age of oldest in Queue " + oldestInQueueWait + "ms"); - } - - // see if the queue has gone dead - if (oldestInQueueWait > (tp.RETRMAXAGE * 2)) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("RETRANS : Shutting down stale connection: " + conn); - } - try { - setClosing(); - conn.close(HandshakeState.CONNECTIONDEAD); - // Leave. Otherwise we'll be spinning forever. - return; - } catch (IOException ignored) { - ; - } - continue; - } - - // get real wait as max of age of oldest in retrQ and - // lastAck time - long realWait = Math.max(oldestInQueueWait, sinceLastACK); - - // Retransmit only if RTO has expired. - // a. real wait time is longer than RTO - // b. oldest message on Q has been there longer - // than RTO. This is necessary because we may - // have just sent a message, and we do not - // want to overrun the receiver. Also, we - // do not want to restransmit a message that - // has not been idle for the RTO. - if ((realWait >= RTO) && (oldestInQueueWait >= RTO)) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETRANS : RTO RETRANSMISSION [" + RWINDOW + "]"); - } - - // retrasmit - int retransed = retransmit(RWINDOW, TimeUtils.timeNow()); - - // Total - nretransmitted += retransed; - - // number at this RTO - nAtThisRTO += retransed; - - // See if real wait is too long and queue is non-empty - // Remote may be dead - double until max. - // Double after window restransmitted msgs at this RTO - // exceeds the RWINDOW, and we've had no response for - // twice the current RTO. - if ((retransed > 0) && (realWait >= 2 * RTO) && (nAtThisRTO >= 2 * RWINDOW)) { - RTO = (realWait > maxRTO ? maxRTO : 2 * RTO); - nAtThisRTO = 0; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETRANS : RETRANSMISSION " + retransed + " retrans " + nAtThisRTO + " at this RTO (" + RTO - + ") " + nretransmitted + " total retrans"); - } - } else { - idleCounter += 1; - - // reset RTO to min if we are idle - if (idleCounter == 2) { - RTO = minRTO; - idleCounter = 0; - nAtThisRTO = 0; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETRANS : IDLE : RTO=" + RTO + " WAIT=" + realWait); - } - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("STOPPED TLS Retransmit thread"); - } - - retransmitterThread = null; - retransmitter = null; - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsConn.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsConn.java deleted file mode 100644 index a3e80dd5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsConn.java +++ /dev/null @@ -1,741 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.tls; - -import java.io.BufferedOutputStream; -import java.io.InputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.security.cert.X509Certificate; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.Provider; -import java.security.Security; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import net.jxta.document.MimeMediaType; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.WireFormatMessage; -import net.jxta.endpoint.WireFormatMessageFactory; -import net.jxta.util.IgnoreFlushFilterOutputStream; -import net.jxta.impl.membership.pse.PSECredential; -import net.jxta.impl.util.TimeUtils; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * This class implements the TLS connection between two peers. - * - * - *

            Properties: - * - *

            net.jxta.impl.endpoint.tls.TMFAlgorithm - if defined provides the name of - * the trust manager factory algorithm to use. - */ -class TlsConn { - - /** - * Logger - **/ - private static final transient Logger LOG = Logger.getLogger(TlsConn.class.getName()); - static final int BOSIZE = 16000; - /** - * TLS transport this connection is working for. - **/ - final TlsTransport transport; - /** - * The address of the peer to which we will be forwarding ciphertext - * messages. - **/ - final EndpointAddress destAddr; - /** - * Are we client or server? - **/ - private boolean client; - /** - * State of the connection - **/ - private volatile HandshakeState currentState; - /** - * Are we currently closing? To prevent recursion in {@link close()} - **/ - private boolean closing = false; - /** - * Time that something "good" last happened on the connection - **/ - long lastAccessed; - final String lastAccessedLock = new String("lastAccessedLock"); - final String closeLock = new String("closeLock"); - /** - * Number of retransmissions we have received. - **/ - int retrans; - /** - * Our synthetic socket which sends and receives the ciphertext. - **/ - final TlsSocket tlsSocket; - private final SSLContext context; - /** - * For interfacing with TLS - **/ - private SSLSocket ssls; - /** - * We write our plaintext to this stream - **/ - private OutputStream plaintext_out = null; - /** - * Reads plaintext from the - **/ - private PlaintextMessageReader readerThread = null; - /** - * A string which we can lock on while acquiring new messengers. We don't - * want to lock the whole connection object. - **/ - private String acquireMessengerLock = new String("Messenger Acquire Lock"); - /** - * Cached messenger for sending to {@link destAddr} - **/ - private Messenger outBoundMessenger = null; - -/** - * Tracks the state of our TLS connection with a remote peer. - **/ - enum HandshakeState { - - /** - * Handshake is ready to begin. We will be the client side. - */ - CLIENTSTART - - , /** - * Handshake is ready to begin. We will be the server side. - */ - SERVERSTART - - , /** - * Handshake is in progress. - */ - HANDSHAKESTARTED - - , /** - * Handshake failed to complete. - */ - HANDSHAKEFAILED - - , /** - * Handshake completed successfully. - */ - HANDSHAKEFINISHED - - , /** - * Connection is closing. - */ - CONNECTIONCLOSING - - , /** - * Connection has died. - */ - CONNECTIONDEAD - } - - /** - * Create a new connection - **/ - TlsConn(TlsTransport tp, EndpointAddress destAddr, boolean client) throws Exception { - this.transport = tp; - this.destAddr = destAddr; - this.client = client; - this.currentState = client ? HandshakeState.CLIENTSTART : HandshakeState.SERVERSTART; - this.lastAccessed = TimeUtils.timeNow(); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info((client ? "Initiating" : "Accepting") + " new connection for : " + destAddr.getProtocolAddress()); - } - - boolean choseTMF = false; - javax.net.ssl.TrustManagerFactory tmf = null; - String overrideTMF = System.getProperty("net.jxta.impl.endpoint.tls.TMFAlgorithm"); - - if ((!choseTMF) && (null != overrideTMF)) { - tmf = javax.net.ssl.TrustManagerFactory.getInstance(overrideTMF); - choseTMF = true; - } - - Collection providers = Arrays.asList(Security.getProviders()); - - Set providerNames = new HashSet(); - - Iterator eachProvider = providers.iterator(); - - while (eachProvider.hasNext()) { - providerNames.add(((Provider) eachProvider.next()).getName()); - } - - if ((!choseTMF) && providerNames.contains("SunJSSE")) { - tmf = javax.net.ssl.TrustManagerFactory.getInstance("SunX509", "SunJSSE"); - choseTMF = true; - } - - if ((!choseTMF) && providerNames.contains("IBMJSSE")) { - tmf = javax.net.ssl.TrustManagerFactory.getInstance("IbmX509", "IBMJSSE"); - choseTMF = true; - } - - // XXX 20040830 bondolo Other solutions go here! - if (!choseTMF) { - tmf = javax.net.ssl.TrustManagerFactory.getInstance(javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm()); - LOG.warning("Using defeualt Trust Manager Factory algorithm. This may not work as expected."); - } - - KeyStore trusted = transport.membership.getPSEConfig().getKeyStore(); - - tmf.init(trusted); - - javax.net.ssl.TrustManager[] tms = tmf.getTrustManagers(); - - javax.net.ssl.KeyManager[] kms = new javax.net.ssl.KeyManager[]{new PSECredentialKeyManager(transport.credential, trusted)}; - - context = SSLContext.getInstance("TLS"); - context.init(kms, tms, null); - - javax.net.ssl.SSLSocketFactory factory = context.getSocketFactory(); - - // endpoint interface - TlsSocket newConnect = new TlsSocket(new JTlsInputStream(this, tp.MIN_IDLE_RECONNECT), new JTlsOutputStream(transport, this)); - - // open SSL socket and do the handshake - ssls = (SSLSocket) factory.createSocket(newConnect, destAddr.getProtocolAddress(), JTlsDefs.FAKEPORT, true); - ssls.setEnabledProtocols(new String[]{"TLSv1"}); - ssls.setUseClientMode(client); - if (!client) { - ssls.setNeedClientAuth(true); - } - - // We have to delay initialization of this until we have set the - // handshake mode. - tlsSocket = newConnect; - } - - /** - * @inheritDoc - * - *

            An implementation which is useful for debugging. - **/ - @Override - public String toString() { - return super.toString() + "/" + getHandshakeState() + ":" + (client ? "Client" : "Server") + " for " + destAddr; - } - - /** - * Returns the current state of the connection - * - * @return the current state of the connection. - **/ - HandshakeState getHandshakeState() { - return currentState; - } - - /** - * Changes the state of the connection. Calls - * {@link java.lang.Object#notifyAll()} to wake any threads waiting on - * connection state changes. - * - * @param newstate the new connection state. - * @return the previous state of the connection. - **/ - synchronized HandshakeState setHandshakeState(HandshakeState newstate) { - - HandshakeState oldstate = currentState; - - currentState = newstate; - notifyAll(); - return oldstate; - } - - /** - * Open the connection with the remote peer. - **/ - void finishHandshake() throws IOException { - - long startTime = 0; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - startTime = TimeUtils.timeNow(); - LOG.info((client ? "Client:" : "Server:") + " Handshake START"); - } - - setHandshakeState(HandshakeState.HANDSHAKESTARTED); - - // this starts a handshake - SSLSession newSession = ssls.getSession(); - - if ("SSL_NULL_WITH_NULL_NULL".equals(newSession.getCipherSuite())) { - setHandshakeState(HandshakeState.HANDSHAKEFAILED); - throw new IOException("Handshake failed"); - } - - setHandshakeState(HandshakeState.HANDSHAKEFINISHED); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - long hsTime = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), startTime) / TimeUtils.ASECOND; - - LOG.info((client ? "Client:" : "Server:") + "Handshake DONE in " + hsTime + " secs"); - } - - // set up plain text i/o - // writes to be encrypted - plaintext_out = new BufferedOutputStream(ssls.getOutputStream(), BOSIZE); - - // Start reader thread - readerThread = new PlaintextMessageReader(ssls.getInputStream()); - } - - /** - * Close this connection. - * - * @param finalstate state that the connection will be in after close. - **/ - void close(HandshakeState finalstate) throws IOException { - synchronized (lastAccessedLock) { - lastAccessed = Long.MIN_VALUE; - } - synchronized (closeLock) { - closing = true; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Shutting down " + this); - } - - setHandshakeState(HandshakeState.CONNECTIONCLOSING); - - try { - if (null != tlsSocket) { - try { - tlsSocket.close(); - } catch (IOException ignored) { - ; - } - } - - if (null != ssls) { - try { - ssls.close(); - } catch (IOException ignored) { - ; - } - ssls = null; - } - - if (null != outBoundMessenger) { - outBoundMessenger.close(); - outBoundMessenger = null; - } - } catch (Throwable failed) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "Throwable during close " + this, failed); - } - - IOException failure = new IOException("Throwable during close()"); - - failure.initCause(failed); - } finally { - closeLock.notifyAll(); - closing = false; - setHandshakeState(finalstate); - } - } - } - - /** - * Used by the TlsManager and the TlsConn in order to send a message, - * either a TLS connection establishment, or TLS fragments to the remote TLS. - * - * @param msg message to send to the remote TLS peer. - * @return if true then message was sent, otherwise false. - * @throws IOException if there was a problem sending the message. - **/ - boolean sendToRemoteTls(Message msg) throws IOException { - - synchronized (acquireMessengerLock) { - if ((null == outBoundMessenger) || outBoundMessenger.isClosed()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting messenger for " + destAddr); - } - - EndpointAddress realAddr = new EndpointAddress(destAddr, JTlsDefs.ServiceName, null); - - // Get a messenger. - outBoundMessenger = transport.endpoint.getMessenger(realAddr); - - if (outBoundMessenger == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Could not get messenger for " + realAddr); - } - return false; - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + " to " + destAddr); - } - - // Good we have a messenger. Send the message. - return outBoundMessenger.sendMessage(msg); - } - - /** - * sendMessage is called by the TlsMessenger each time a service or - * an application sends a new message over a TLS connection. - * IOException is thrown when something goes wrong. - * - *

            The message is encrypted by TLS ultimately calling - * JTlsOutputStream.write(byte[], int, int); with the resulting TLS - * Record(s). - * - * @param msg The plaintext message to be sent via this connection. - * @throws IOException for errors in sending the message. - **/ - void sendMessage(Message msg) throws IOException { - - try { - WireFormatMessage serialed = WireFormatMessageFactory.toWire(msg, JTlsDefs.MTYPE, (MimeMediaType[]) null); - - serialed.sendToStream(new IgnoreFlushFilterOutputStream(plaintext_out)); - - plaintext_out.flush(); - } catch (IOException failed) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.log(Level.INFO, "Closing " + this + " due to exception ", failed); - } - - close(HandshakeState.CONNECTIONDEAD); - throw failed; - } - } - -/** - * This is our message reader thread. This reads from the plaintext input - * stream and dispatches messages received to the endpoint. - **/ - private class PlaintextMessageReader implements Runnable { - - InputStream ptin = null; - Thread workerThread = null; - - public PlaintextMessageReader(InputStream ptin) { - this.ptin = ptin; - - // start our thread - workerThread = new Thread(TlsConn.this.transport.myThreadGroup, this, "JXTA TLS Plaintext Reader for " + TlsConn.this.destAddr); - workerThread.setDaemon(true); - workerThread.start(); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Started ReadPlaintextMessage thread for " + TlsConn.this.destAddr); - } - } - - /** - * @inheritDoc - **/ - public void run() { - try { - while (true) { - try { - Message msg = WireFormatMessageFactory.fromWire(ptin, JTlsDefs.MTYPE, null); - - if (null == msg) { - break; - } - - // dispatch it to TlsTransport for demuxing - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Dispatching " + msg + " to TlsTransport"); - } - - TlsConn.this.transport.processReceivedMessage(msg); - - synchronized (TlsConn.this.lastAccessedLock) { - TlsConn.this.lastAccessed = TimeUtils.timeNow(); // update idle timer - } - } catch (IOException iox) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "I/O error while reading decrypted Message", iox); - } - - break; - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - workerThread = null; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Finishing ReadPlaintextMessage thread"); - } - } - } - -/** - * A private key manager which selects based on the key and cert chain found - * in a PSE Credential. - * - *

            TODO Promote this class to a full featured interface for all of the - * active PSECredentials. Currently the alias "theone" is used to refer to - * the - **/ - private static class PSECredentialKeyManager implements javax.net.ssl.X509KeyManager { - - PSECredential cred; - KeyStore trusted; - - public PSECredentialKeyManager(PSECredential useCred, KeyStore trusted) { - this.cred = useCred; - this.trusted = trusted; - } - - /** - * {@inheritDoc} - **/ - public String chooseClientAlias(String[] keyType, java.security.Principal[] issuers, java.net.Socket socket) { - for (String aKeyType : Arrays.asList(keyType)) { - String result = checkTheOne(aKeyType, Arrays.asList(issuers)); - - if (null != result) { - return result; - } - } - - return null; - } - - /** - * Checks to see if a peer that trusts the given issuers would trust the - * special alias THE_ONE, returning it if so, and null otherwise. - * - * @param keyType the type of key a Certificate must use to be considered - * @param issuers the issuers trusted by the other peer - * @return "theone" if one of the Certificates in this peer's PSECredential's - * Certificate chain matches the given keyType and one of the issuers, - * or null - */ - private String checkTheOne(String keyType, Collection allIssuers) { - List certificates = Arrays.asList(cred.getCertificateChain()); - - for (X509Certificate certificate : certificates) { - if (!certificate.getPublicKey().getAlgorithm().equals(keyType)) { - continue; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("CHECKING: " + certificate.getIssuerX500Principal() + " in " + allIssuers); - } - - if (allIssuers.contains(certificate.getIssuerX500Principal())) { - return "theone"; - } - } - return null; - } - - /** - * {@inheritDoc} - **/ - public String chooseServerAlias(String keyType, java.security.Principal[] issuers, java.net.Socket socket) { - String[] available = getServerAliases(keyType, issuers); - - if (null != available) { - return available[0]; - } else { - return null; - } - } - - /** - * {@inheritDoc} - **/ - public X509Certificate[] getCertificateChain(String alias) { - if (alias.equals("theone")) { - return cred.getCertificateChain(); - } else { - try { - return (X509Certificate[]) trusted.getCertificateChain(alias); - } catch (KeyStoreException ignored) { - return null; - } - } - } - - /** - * {@inheritDoc} - **/ - public String[] getClientAliases(String keyType, java.security.Principal[] issuers) { - List clientAliases = new ArrayList(); - - try { - Enumeration eachAlias = trusted.aliases(); - - Collection allIssuers = null; - - if (null != issuers) { - allIssuers = Arrays.asList(issuers); - } - - while (eachAlias.hasMoreElements()) { - String anAlias = (String) eachAlias.nextElement(); - - if (trusted.isCertificateEntry(anAlias)) { - try { - X509Certificate aCert = (X509Certificate) trusted.getCertificate(anAlias); - - if (null == aCert) { - // strange... it should have been there... - continue; - } - - if (!aCert.getPublicKey().getAlgorithm().equals(keyType)) { - continue; - } - - if (null != allIssuers) { - if (allIssuers.contains(aCert.getIssuerX500Principal())) { - clientAliases.add(anAlias); - } - } else { - clientAliases.add(anAlias); - } - } catch (KeyStoreException ignored) { - ; - } - } - } - } catch (KeyStoreException ignored) { - ; - } - - return (String[]) clientAliases.toArray(new String[clientAliases.size()]); - } - - /** - * {@inheritDoc} - **/ - public java.security.PrivateKey getPrivateKey(String alias) { - if (alias.equals("theone")) { - return cred.getPrivateKey(); - } else { - return null; - } - } - - /** - * {@inheritDoc} - **/ - public String[] getServerAliases(String keyType, java.security.Principal[] issuers) { - if (keyType.equals(cred.getCertificate().getPublicKey().getAlgorithm())) { - if (null == issuers) { - return new String[]{"theone"}; - } else { - Collection allIssuers = Arrays.asList(issuers); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Looking for : " + cred.getCertificate().getIssuerX500Principal()); - LOG.fine("Issuers : " + allIssuers); - java.security.Principal prin = cred.getCertificate().getIssuerX500Principal(); - - LOG.fine(" Principal Type :" + prin.getClass().getName()); - Iterator it = allIssuers.iterator(); - - while (it.hasNext()) { - java.security.Principal tmp = (java.security.Principal) it.next(); - - LOG.fine("Issuer Type : " + tmp.getClass().getName()); - LOG.fine("Issuer value : " + tmp); - LOG.fine("tmp.equals(prin) : " + tmp.equals(prin)); - } - } - - X509Certificate[] chain = cred.getCertificateChain(); - for (X509Certificate aCert : Arrays.asList(chain)) { - if (allIssuers.contains(aCert.getIssuerX500Principal())) { - return new String[]{"theone"}; - } - } - } - } - return null; - } - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsManager.java deleted file mode 100644 index 2cfd1573..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsManager.java +++ /dev/null @@ -1,612 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.tls; - - -import java.io.DataInputStream; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import java.io.IOException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; - -import net.jxta.impl.util.TimeUtils; - -import net.jxta.impl.endpoint.tls.TlsConn.HandshakeState; - - -/** - * Manages the connection pool between peers. - **/ -class TlsManager implements EndpointListener { - - /** - * Log4J Logger - **/ - private final static transient Logger LOG = Logger.getLogger(TlsManager.class.getName()); - - /** - * Transport we are working for. - **/ - private TlsTransport transport = null; - - /** - * Hash table for known connections - * - *

              - *
            • keys are {@link String } containing {@link net.jxta.peer.PeerID#getUniqueValue() PeerID.getUniqueValue()}
            • - *
            • values are {@link TlsConn}
            • - *
            - **/ - private Map connections = new HashMap(); - - /** - * The last time at which we printed a warning about discarding messages - * due to no authentication. - **/ - private long lastNonAuthenticatedWarning = 0; - - /** - * Standard Constructor for TLS Manager - **/ - TlsManager(TlsTransport tp) { - this.transport = tp; - } - - /** - * Close this manager. This involves closing all registered connections. - * - **/ - void close() { - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Shutting down all connections"); - } - - synchronized (connections) { - Iterator eachConnection = connections.values().iterator(); - - while (eachConnection.hasNext()) { - TlsConn aConnection = (TlsConn) eachConnection.next(); - - try { - aConnection.close(HandshakeState.CONNECTIONDEAD); - } catch (IOException ignored) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Non-fatal problem shutting down connection to " + aConnection); - } - } - - eachConnection.remove(); - } - } - } - - /** - * Returns or creates a TLS Connection to the specified peer. If an - * existing connection exists, it will be returned. - * - * @param dstAddr the EndpointAddress of the remote peer. - * @return A TLS Connection or null if the connection could not be opened. - **/ - TlsConn getTlsConn(EndpointAddress dstAddr) { - - if (null == transport.credential) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Not authenticated. Cannot open connections."); - } - - return null; - } - - boolean startHandshake = false; - - // see if we have an existing conn, and if so, then reuse it - // if it has not timed out. - String paddr = dstAddr.getProtocolAddress(); - - TlsConn conn = null; - - synchronized (connections) { - conn = (TlsConn) connections.get(paddr); - - // remove it if it is dead - if (null != conn) { - if ((HandshakeState.CONNECTIONDEAD == conn.getHandshakeState()) - || (HandshakeState.HANDSHAKEFAILED == conn.getHandshakeState())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing connection for: " + paddr); - } - connections.remove(paddr); - conn = null; - } - } - - // create the connection info entry as needed - if (null == conn) { - try { - conn = new TlsConn(transport, dstAddr, true); // true means client - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed making connection to " + paddr, failed); - } - - return null; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Adding connection for: " + paddr); - } - connections.put(paddr, conn); - startHandshake = true; - } - } - - // if we got to be the first one to start the handshake then do it here. - // We do this outside of the synchro block so that others can enter the - // state machine. - if (startHandshake) { - try { - // OK. We are originating the connection: - // Open the connection (returns when handshake is completed) - // or throws an IOException if a TLS internal error occurs. - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Start of client handshake for " + paddr); - } - - conn.finishHandshake(); - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed making connection to " + paddr, e); - } - - synchronized (connections) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing connection for: " + paddr); - } - connections.remove(paddr); - } - try { - conn.close(HandshakeState.HANDSHAKEFAILED); - } catch (IOException ignored) { - ; - } - - return null; - } - } - - do { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("getting " + conn); - } - - synchronized (conn) { - HandshakeState currentState = conn.getHandshakeState(); - - if ((HandshakeState.SERVERSTART == currentState) || (HandshakeState.CLIENTSTART == currentState)) { - // wait for the handshake to get going on another thread. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sleeping until handshake starts for " + paddr); - } - - try { - conn.wait(TimeUtils.ASECOND); - } catch (InterruptedException woken) { - Thread.interrupted(); - } - continue; - } else if (HandshakeState.HANDSHAKESTARTED == currentState) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Handshake in progress for " + paddr); - } - - try { - // sleep forever waiting for the state to change. - conn.wait(200); - } catch (InterruptedException woken) { - Thread.interrupted(); - } - continue; - } else if (HandshakeState.HANDSHAKEFINISHED == currentState) { - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Returning active connection to " + paddr); - } - - conn.lastAccessed = TimeUtils.timeNow(); // update idle timer - - return conn; - } else if (HandshakeState.HANDSHAKEFAILED == currentState) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Handshake failed. " + paddr + " unreachable"); - } - - return null; - } else if (HandshakeState.CONNECTIONDEAD == currentState) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Connection dead for " + paddr); - } - - return null; - } else if (HandshakeState.CONNECTIONCLOSING == currentState) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Connection closing for " + paddr); - } - - return null; - } else { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Unhandled Handshake state: " + currentState); - } - } - } - } while (true); - } - - /** - * Handle an incoming message from the endpoint. This method demultiplexes - * incoming messages to the connection objects by their source address. - * - *

            Several types of messages may be received for a connection: - * - *

              - *
            • TLS Elements
            • - *
            • Element Acknowledgements
            • - *
            - * - * @param msg is the incoming message - * @param srcAddr is the address of the source of the message - * @param dstAddr is the address of the destination of the message - **/ - public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Starts for " + msg); - } - - if (null == transport.credential) { - // ignore ALL messages until we are authenticated. - if (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), lastNonAuthenticatedWarning) > TimeUtils.AMINUTE) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("NOT AUTHENTICATED--Discarding all incoming messages"); - } - - lastNonAuthenticatedWarning = TimeUtils.timeNow(); - } - - return; - } - - // determine if its a retry. - MessageElement retryElement = msg.getMessageElement(JTlsDefs.TLSNameSpace, JTlsDefs.RETR); - boolean retrans = (null != retryElement); - - if (retrans) { - msg.removeMessageElement(retryElement); - retryElement = null; - } - - int seqN = getMsgSequenceNumber(msg); - - // Extract unique part of source address - String paddr = srcAddr.getProtocolAddress(); - - TlsConn conn = null; - - boolean serverStart = false; - - synchronized (connections) { - // Will be in our hash table unless this is for a first time - // incoming connection request - conn = (TlsConn) connections.get(paddr); - - if (null != conn) { - // check if the connection has idled out and remote is asking for a restart. - if (TlsTransport.ACT_AS_SERVER && (1 == seqN)) { - synchronized (conn) { - long idle = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), conn.lastAccessed); - - if (idle > transport.MIN_IDLE_RECONNECT) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Restarting : " + conn + " which has been idle for " + idle + " millis"); - } - try { - conn.close(HandshakeState.CONNECTIONDEAD); - } catch (IOException ignored) { - ; - } - } - } - } - - // remove it if it is dead - if ((HandshakeState.CONNECTIONDEAD == conn.getHandshakeState()) - || (HandshakeState.HANDSHAKEFAILED == conn.getHandshakeState())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing connection for: " + paddr); - } - connections.remove(paddr); - conn = null; - } - } - - // we don't have a connection to this destination, make a new connection if seqn#1 - if (null == conn) { - if (TlsTransport.ACT_AS_SERVER && (1 == seqN)) { - try { - conn = new TlsConn(transport, srcAddr, false); // false means Server - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed making connection for" + paddr, failed); - } - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Adding connection for: " + paddr); - } - connections.put(paddr, conn); - serverStart = true; - } else { - // Garbage from an old connection. discard it - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning(msg + " is not start of handshake (seqn#" + seqN + ") for " + paddr); - } - - msg.clear(); - return; - } - } - } - - // if this is a new connection, get it started. - if (serverStart) { - try { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Start of SERVER handshake for " + paddr); - } - - // Queue message up for TlsInputStream on that connection - conn.tlsSocket.input.queueIncomingMessage(msg); - - // Start the TLS Server and complete the handshake - conn.finishHandshake(); // open the TLS connection - - conn.lastAccessed = TimeUtils.timeNow(); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Handshake complete for SERVER TLS for: " + paddr); - } - - return; - } catch (Throwable e) { - // Handshake failure or IOException - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "TLS Handshake failure for connection: " + paddr, e); - } - - synchronized (connections) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing connection for: " + paddr); - } - connections.remove(paddr); - } - try { - conn.close(HandshakeState.HANDSHAKEFAILED); - } catch (IOException ignored) { - ; - } - - return; - } - } - - // handle an ongoing connection. - do { - HandshakeState currentState; - - synchronized (conn) { - if (retrans) { - conn.retrans++; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("retrans received, " + conn.retrans + " total."); - } - retrans = false; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Process incoming message for " + conn); - } - - currentState = conn.getHandshakeState(); - - if ((HandshakeState.HANDSHAKESTARTED == currentState) || (HandshakeState.HANDSHAKEFINISHED == currentState) - || (HandshakeState.CONNECTIONCLOSING == currentState)) {// we will process the message once we get out of sync. - } else if (HandshakeState.CONNECTIONDEAD == currentState) { - // wait for the handshake to get going on another thread. - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Connection failed, discarding msg with seqn#" + seqN + " for " + paddr); - } - - return; - } else if ((HandshakeState.SERVERSTART == currentState) || (HandshakeState.CLIENTSTART == currentState)) { - // wait for the handshake to get going on another thread. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sleeping msg with seqn#" + seqN + " until handshake starts for " + paddr); - } - - try { - conn.wait(TimeUtils.AMINUTE); - } catch (InterruptedException woken) { - Thread.interrupted(); - } - continue; - } else if (HandshakeState.HANDSHAKEFAILED == currentState) { - // wait for the handshake to get going on another thread. - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Handshake failed, discarding msg with seqn#" + seqN + " for " + paddr); - } - - return; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unexpected state : " + currentState); - } - } - } - - // Process any message outside of the sync on the connection. - if ((HandshakeState.HANDSHAKESTARTED == currentState) || (HandshakeState.HANDSHAKEFINISHED == currentState) - || (HandshakeState.CONNECTIONCLOSING == currentState)) { - // process any ACK messages. - Iterator eachACK = msg.getMessageElements(JTlsDefs.TLSNameSpace, JTlsDefs.ACKS); - - while (eachACK.hasNext()) { - MessageElement elt = (MessageElement) eachACK.next(); - - eachACK.remove(); - - int sackCount = ((int) elt.getByteLength() / 4) - 1; - - try { - DataInputStream dis = new DataInputStream(elt.getStream()); - - int seqack = dis.readInt(); - - int[] sacs = new int[sackCount]; - - for (int eachSac = 0; eachSac < sackCount; eachSac++) { - sacs[eachSac] = dis.readInt(); - } - - Arrays.sort(sacs); - - // take care of the ACK here; - conn.tlsSocket.output.ackReceived(seqack, sacs); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure processing ACK", failed); - } - } - } - - if (0 == seqN) { - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Queue " + msg + " seqn#" + seqN + " for " + conn); - } - - // Queue message up for TlsInputStream on that connection - TlsSocket bound = conn.tlsSocket; - - if (null != bound) { - bound.input.queueIncomingMessage(msg); - } - - return; - } - } while (true); - } - - /** - * getMsgSequenceNumber - * - * @param msg Input message - * @return int sequence number or 0 (zero) if no tls records in message. - **/ - private static int getMsgSequenceNumber(Message msg) { - - int seqN = 0; - - Iterator eachElement = msg.getMessageElements(JTlsDefs.TLSNameSpace, JTlsDefs.BLOCKS); - - while (eachElement.hasNext()) { - MessageElement elt = (MessageElement) eachElement.next(); - - try { - seqN = Integer.parseInt(elt.getElementName()); - } catch (NumberFormatException e) { - // This element was not a TLS element. Get the next one - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Bad tls record name=" + elt.getElementName()); - } - - eachElement.remove(); - continue; - } - - break; - } - - return seqN; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsMessenger.java deleted file mode 100644 index 4e80d913..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsMessenger.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.tls; - - -import java.io.*; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.endpoint.*; -import net.jxta.impl.endpoint.*; -import net.jxta.impl.endpoint.tls.TlsConn.HandshakeState; - - -/** - * This class implements sending messages through a TLS connection. - */ -public class TlsMessenger extends BlockingMessenger { - - private static final Logger LOG = Logger.getLogger(TlsMessenger.class.getName()); - - private TlsTransport transport = null; - private TlsConn conn = null; - - /** - * The source address of messages sent on this messenger. - */ - private final EndpointAddress srcAddress; - - private final MessageElement srcAddressElement; - - TlsMessenger(EndpointAddress destAddress, TlsConn conn, TlsTransport tp) { - - // No need for self destruction. - super(tp.getPeerGroup().getPeerGroupID(), destAddress, false); - - if (conn == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("null TLS connection!"); - } - throw new IllegalArgumentException("null TLS connection!"); - } - - this.conn = conn; - this.transport = tp; - - this.srcAddress = transport.getPublicAddress(); - - srcAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NAME, srcAddress.toString() - , - (MessageElement) null); - } - - /* - * The cost of just having a finalize routine is high. The finalizer is - * a bottleneck and can delay garbage collection all the way to heap - * exhaustion. Leave this comment as a reminder to future maintainers. - * Below is the reason why finalize is not needed here. - * - * These messengers never go to the application layer. The endpoint code - * always invokes close when needed. - - protected void finalize() { - } - - */ - - /** - * {@inheritDoc} - */ - @Override - public synchronized void closeImpl() { - super.close(); - conn = null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isIdleImpl() { - // No need for self destruction. - return false; - } - - /** - * {@inheritDoc} - * - *

            The peer that is the destination is the logical address - */ - @Override - public EndpointAddress getLogicalDestinationImpl() { - return new EndpointAddress("jxta", dstAddress.getProtocolAddress(), null, null); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void sendMessageBImpl(Message message, String service, String serviceParam) throws IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Starting send for " + message); - } - - // check if the connection has died. - if (HandshakeState.CONNECTIONDEAD == conn.getHandshakeState()) { - - // FIXME - jice@jxta.org 20040413: This will do but it causes the below exception to be shown as the cause of the - // failure, which is not true: nobody realy closed the messenger before it failed. It failed first. Also, it used to - // shutdown this messenger, now it does not. What does is the call to closeImpl() that follows our IOException...(and - // that's how it should be). Transports should get a deeper retrofit eventually. - - close(); - } - - if (isClosed()) { - IOException failure = new IOException("Messenger is closed, it cannot be used to send messages."); - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, failure.getMessage(), failure); - } - - throw failure; - } - - // Set the message with the appropriate src and dest address - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NS, srcAddressElement); - - MessageElement dstAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NAME - , - getDestAddressToUse(service, serviceParam).toString(), (MessageElement) null); - - message.replaceMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NS, dstAddressElement); - - // Give the message to the TLS connection - try { - conn.sendMessage(message); - } catch (IOException caught) { - close(); - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Message send to \'" + dstAddress + "\' failed for " + message, caught); - } - throw caught; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Message send to \'" + dstAddress + "\' succeeded for " + message); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsSocket.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsSocket.java deleted file mode 100644 index a38e1b81..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsSocket.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.tls; - - -import java.io.InputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.nio.channels.SocketChannel; -import net.jxta.impl.endpoint.IPUtils; - - -/** - * A "shim" socket which we provide to the TLS layer. - */ -public class TlsSocket extends Socket { - - final JTlsInputStream input; - final JTlsOutputStream output; - - boolean connected = true; - - /** - * Creates a new instance of TlsSocket - */ - public TlsSocket(JTlsInputStream useInput, JTlsOutputStream useOutput) { - input = useInput; - output = useOutput; - } - - /** - * {@inheritDoc} - */ - @Override - public void close() throws IOException { - input.close(); - output.close(); - connected = false; - } - - /** - * {@inheritDoc} - */ - @Override - public InputStream getInputStream() throws IOException { - return input; - } - - /** - * {@inheritDoc} - */ - @Override - public OutputStream getOutputStream() throws IOException { - return output; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isBound() { - return connected; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isConnected() { - return connected; - } - - /** - * {@inheritDoc} - */ - @Override - public InetAddress getInetAddress() { - return IPUtils.LOOPBACK; - } - - /** - * {@inheritDoc} - */ - @Override - public InetAddress getLocalAddress() { - return IPUtils.ANYADDRESS; - } - - /** - * {@inheritDoc} - */ - @Override - public SocketAddress getRemoteSocketAddress() { - return new InetSocketAddress(IPUtils.LOOPBACK, 0); - } - - /** - * {@inheritDoc} - */ - @Override - public SocketAddress getLocalSocketAddress() { - return new InetSocketAddress(IPUtils.ANYADDRESS, 0); - } - - /** - * {@inheritDoc} - */ - @Override - public SocketChannel getChannel() { - return null; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsTransport.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsTransport.java deleted file mode 100644 index b1fc8cf4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/TlsTransport.java +++ /dev/null @@ -1,772 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.tls; - - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.net.URI; -import java.security.cert.X509Certificate; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.ResourceBundle; -import javax.security.auth.x500.X500Principal; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.security.KeyStoreException; -import java.security.SignatureException; -import java.util.MissingResourceException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageReceiver; -import net.jxta.endpoint.MessageSender; -import net.jxta.endpoint.Messenger; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.ModuleImplAdvertisement; - -import net.jxta.exception.PeerGroupException; - -import net.jxta.impl.endpoint.LoopbackMessenger; -import net.jxta.impl.membership.pse.PSECredential; -import net.jxta.impl.membership.pse.PSEMembershipService; -import net.jxta.impl.peergroup.GenericPeerGroup; -import net.jxta.impl.util.TimeUtils; - - -/** - * A JXTA {@link net.jxta.endpoint.MessageTransport} implementation which - * uses TLS sockets. - */ -public class TlsTransport implements Module, MessageSender, MessageReceiver { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(TlsTransport.class.getName()); - - /** - * If true then we can accept incoming connections. Eventually this should - * be coming out of the transport advertisement. - */ - static final boolean ACT_AS_SERVER = true; - - private PeerGroup group = null; - ID assignedID = null; - ModuleImplAdvertisement implAdvertisement = null; - - EndpointService endpoint = null; - PSEMembershipService membership = null; - private membershipPCL membershipListener = null; - - X509Certificate[] serviceCert = null; - - PSECredential credential = null; - private credentialPCL credentialListener = null; - - EndpointAddress localPeerAddr = null; - EndpointAddress localTlsPeerAddr = null; - - /** - * local peerID - */ - PeerID localPeerId = null; - - /** - * Amount of a connection must be idle before a reconnection attempt will - * be considered. - */ - long MIN_IDLE_RECONNECT = 1 * TimeUtils.AMINUTE; - - /** - * Amount of time after which a connection is considered idle and may be - * scavenged. - */ - long CONNECTION_IDLE_TIMEOUT = 5 * TimeUtils.AMINUTE; - - /** - * Amount if time which retries may remain queued for retransmission. If - * still unACKed after this amount of time then the connection is - * considered dead. - */ - long RETRMAXAGE = 2 * TimeUtils.AMINUTE; - - /** - * Will manage connections to remote peers. - */ - private TlsManager manager = null; - - /** - * This is the thread group into which we will place all of the threads - * we create. THIS HAS NO EFFECT ON SCHEDULING. Java thread groups are - * only for organization and naming. - */ - ThreadGroup myThreadGroup = null; - - /** - * Extends LoopbackMessenger to add a message property to passed messages - * so that TLS pipes and other users can be sure that the message - * originate with the local TLS transport. - */ - class TlsLoopbackMessenger extends LoopbackMessenger { - TlsLoopbackMessenger(EndpointService ep, EndpointAddress src, EndpointAddress dest, EndpointAddress logicalDest) { - super(group, ep, src, dest, logicalDest); - } - - /** - * {@inheritDoc} - **/ - @Override - public void sendMessageBImpl(Message message, String service, String serviceParam) throws IOException { - - // add a property to the message to indicate it came from us. - message.setMessageProperty(TlsTransport.class, TlsTransport.this); - - super.sendMessageBImpl(message, service, serviceParam); - } - } - - /** - * Default constructor - **/ - public TlsTransport() { - - // initialize connection timeout - try { - ResourceBundle jxtaRsrcs = ResourceBundle.getBundle("net.jxta.user"); - - try { - String override_str = jxtaRsrcs.getString("impl.endpoint.tls.connection.idletimeout"); - - if (null != override_str) { - long override_long = Long.parseLong(override_str.trim()); - - if (override_long >= 1) { - CONNECTION_IDLE_TIMEOUT = override_long * TimeUtils.AMINUTE; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Adjusting TLS connection idle timeout to " + CONNECTION_IDLE_TIMEOUT + " millis."); - } - } - } - } catch (NumberFormatException badvalue) { - ; - } - - try { - String override_str = jxtaRsrcs.getString("impl.endpoint.tls.connection.minidlereconnect"); - - if (null != override_str) { - long override_long = Long.parseLong(override_str.trim()); - - if (override_long >= 1) { - MIN_IDLE_RECONNECT = override_long * TimeUtils.AMINUTE; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Adjusting TLS min reconnection idle to " + MIN_IDLE_RECONNECT + " millis."); - } - } - } - } catch (NumberFormatException badvalue) { - ; - } - - try { - String override_str = jxtaRsrcs.getString("impl.endpoint.tls.connection.maxretryage"); - - if (null != override_str) { - long override_long = Long.parseLong(override_str.trim()); - - if (override_long >= 1) { - RETRMAXAGE = override_long * TimeUtils.AMINUTE; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Adjusting TLS maximum retry queue age to " + RETRMAXAGE + " millis."); - } - } - } - } catch (NumberFormatException badvalue) { - ; - } - - // reconnect must be less the idle interval. - - MIN_IDLE_RECONNECT = Math.min(MIN_IDLE_RECONNECT, CONNECTION_IDLE_TIMEOUT); - - // max retry queue age must be less the idle interval. - RETRMAXAGE = Math.min(RETRMAXAGE, CONNECTION_IDLE_TIMEOUT); - - } catch (MissingResourceException notthere) { - ; - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (null == target) { - return false; - } - - if (target instanceof TlsTransport) { - TlsTransport likeMe = (TlsTransport) target; - - if (!getProtocolName().equals(likeMe.getProtocolName())) { - return false; - } - - return localTlsPeerAddr.equals(likeMe.localTlsPeerAddr); - } - - return false; - } - - /** - * {@inheritDoc} - */ - PeerGroup getPeerGroup() { - return group; - } - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - - this.group = group; - this.assignedID = assignedID; - this.implAdvertisement = (ModuleImplAdvertisement) impl; - - localPeerId = group.getPeerID(); - - localPeerAddr = mkAddress(group.getPeerID(), null, null); - - localTlsPeerAddr = new EndpointAddress(JTlsDefs.tlsPName, localPeerId.getUniqueValue().toString(), null, null); - - myThreadGroup = new ThreadGroup(group.getHomeThreadGroup(), "TLSTransport " + localTlsPeerAddr); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring TLS Transport : " + assignedID); - - if (null != implAdvertisement) { - configInfo.append("\n\tImplementation:"); - configInfo.append("\n\t\tModule Spec ID: " + implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : " + implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : " + implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : " + implAdvertisement.getCode()); - } - configInfo.append("\n\tGroup Params:"); - configInfo.append("\n\t\tGroup: " + group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID: " + group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID: " + group.getPeerID()); - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tProtocol: " + JTlsDefs.tlsPName); - configInfo.append("\n\t\tOutgoing Connections Enabled: " + Boolean.TRUE); - configInfo.append("\n\t\tIncoming Connections Enabled: " + ACT_AS_SERVER); - configInfo.append("\n\t\tMinimum idle for reconnect : " + MIN_IDLE_RECONNECT + "ms"); - configInfo.append("\n\t\tConnection idle timeout : " + CONNECTION_IDLE_TIMEOUT + "ms"); - configInfo.append("\n\t\tRetry queue maximum age : " + RETRMAXAGE + "ms"); - configInfo.append("\n\t\tPeerID : " + localPeerId); - configInfo.append("\n\t\tRoute through : " + localPeerAddr); - configInfo.append("\n\t\tPublic Address : " + localTlsPeerAddr); - - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public synchronized int startApp(String[] args) { - - endpoint = group.getEndpointService(); - - if (null == endpoint) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - - return START_AGAIN_STALLED; - } - - MembershipService groupMembership = group.getMembershipService(); - - if (null == groupMembership) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a membership service"); - } - - return START_AGAIN_STALLED; - } - - if (!(groupMembership instanceof PSEMembershipService)) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("TLS Transport requires PSE Membership Service"); - } - return -1; - } - - if (endpoint.addMessageTransport(this) == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Transport registration refused"); - } - return -1; - } - - membership = (PSEMembershipService) groupMembership; - - PropertyChangeListener mpcl = new membershipPCL(); - - membership.addPropertyChangeListener(mpcl); - - try { - serviceCert = membership.getPSEConfig().getTrustedCertificateChain(assignedID); - - Enumeration eachCred = membership.getCurrentCredentials(); - - while (eachCred.hasMoreElements()) { - PSECredential aCred = (PSECredential) eachCred.nextElement(); - - // send a fake property change event. - mpcl.propertyChange(new PropertyChangeEvent(membership, "addCredential", null, aCred)); - } - } catch (IOException failed) { - serviceCert = null; - } catch (KeyStoreException failed) { - serviceCert = null; - } - - // Create the TLS Manager - manager = new TlsManager(this); - - // Connect ourself to the EndpointService - try { - endpoint.addIncomingMessageListener(manager, JTlsDefs.ServiceName, null); - } catch (Throwable e2) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "TLS could not register listener...as good as dead", e2); - } - return -1; - } - - return 0; - } - - /** - * {@inheritDoc} - */ - public synchronized void stopApp() { - if (null != endpoint) { - endpoint.removeIncomingMessageListener(JTlsDefs.ServiceName, null); - endpoint.removeMessageTransport(this); - endpoint = null; - } - - if (null != manager) { - manager.close(); - manager = null; - } - - if (null != membership) { - membership.removePropertyChangeListener(membershipListener); - membershipListener = null; - membership = null; - } - - PSECredential temp = credential; - - if (null != temp) { - temp.removePropertyChangeListener(credentialListener); - credentialListener = null; - credential = null; - } - } - - /** - * {@inheritDoc} - **/ - public boolean isConnectionOriented() { - - return true; - } - - /** - * {@inheritDoc} - */ - public boolean allowsRouting() { - // The TLS connection should not be used for default routing - return false; - } - - /** - * {@inheritDoc} - */ - public Object transportControl(Object operation, Object Value) { - return null; - } - - /** - * {@inheritDoc} - */ - public EndpointAddress getPublicAddress() { - return localTlsPeerAddr; - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - return endpoint; - } - - /** - * {@inheritDoc} - */ - public Iterator getPublicAddresses() { - return Collections.singletonList(getPublicAddress()).iterator(); - } - - /** - * {@inheritDoc} - */ - public String getProtocolName() { - return JTlsDefs.tlsPName; - } - - /** - * {@inheritDoc} - */ - public boolean ping(EndpointAddress addr) { - - return null != getMessenger(addr, null); - } - - /** - * {@inheritDoc} - * - * XXX bondolo 20040522 The hint could be used in request for the - * underlying messenger. - */ - public Messenger getMessenger(EndpointAddress addr, Object hintIgnored) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("getMessenger for " + addr); - } - - EndpointAddress plainAddress = new EndpointAddress(addr, null, null); - - // If the dest is the local peer, just loop it back without going - // through the TLS. Local communication do not use TLS. - if (plainAddress.equals(localTlsPeerAddr)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("returning LoopbackMessenger"); - } - return new TlsLoopbackMessenger(endpoint, plainAddress, addr, localPeerAddr); - } - - // Create a Peer EndpointAddress - EndpointAddress dstPAddr = mkAddress(ID.URIEncodingName + ":" + ID.URNNamespace + ":" + addr.getProtocolAddress(), null - , - null); - - TlsConn conn = manager.getTlsConn(dstPAddr); - - if (conn == null) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Cannot get a TLS connection for " + dstPAddr); - } - // No connection was either available or created. Cannot do TLS - // with the destination address. - return null; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("TlsMessanger with TlsConn DONE"); - } - - // Build a TlsMessenger around it that will add our header. - // Right now we do not want to "announce" outgoing messengers because they get pooled and so must - // not be grabbed by a listener. If "announcing" is to be done, that should be by the endpoint - // and probably with a subtely different interface. - return new TlsMessenger(addr, conn, this); - } - - /** - * processReceivedMessage is invoked by the TLS Manager when a message has been - * completely received and is ready to be delivered to the service/application - */ - void processReceivedMessage(final Message msg) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("processReceivedMessage starts"); - } - - // add a property to the message to indicate it came from us. - msg.setMessageProperty(TlsTransport.class, this); - - // let the message continue to its final destination. - try { - ((GenericPeerGroup)group).getExecutor().execute( new Runnable() { - public void run() { - try { - endpoint.demux(msg); - } catch(Throwable uncaught) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure demuxing an incoming message", uncaught); - } - } - } - }); - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure demuxing an incoming message", e); - } - } - } - - /** - * Convenience method for constructing an endpoint address from an id - * - * @param destPeer peer id - * @param serv the service name (if any) - * @param parm the service param (if any) - * @param endpointAddress for this peer id. - */ - private final static EndpointAddress mkAddress(String destPeer, String serv, String parm) { - - ID asID = null; - - try { - asID = IDFactory.fromURI(new URI(destPeer)); - } catch (URISyntaxException caught) { - throw new IllegalArgumentException(caught.getMessage()); - } - - return mkAddress(asID, serv, parm); - } - - /** - * Convenience method for constructing an endpoint address from an id - * - * @param destPeer peer id - * @param serv the service name (if any) - * @param parm the service param (if any) - * @param endpointAddress for this peer id. - */ - private final static EndpointAddress mkAddress(ID destPeer, String serv, String parm) { - - EndpointAddress addr = new EndpointAddress("jxta", destPeer.getUniqueValue().toString(), serv, parm); - - return addr; - } - - /** - * Listener for Property Changed Events on our credential - **/ - class credentialPCL implements PropertyChangeListener { - - /** - * {@inheritDoc} - * - *

            Handle events on our active credential. - **/ - public synchronized void propertyChange(PropertyChangeEvent evt) { - - if (credential == evt.getSource()) { - if (!credential.isValid()) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Clearing credential/certfile "); - } - - credential.removePropertyChangeListener(this); - credential = null; - } - } - } - } - - - /** - * Listener for Property Changed Events on membership service - **/ - class membershipPCL implements PropertyChangeListener { - - /** - * {@inheritDoc} - **/ - public synchronized void propertyChange(PropertyChangeEvent evt) { - - String evtProp = evt.getPropertyName(); - PSECredential cred = (PSECredential) evt.getNewValue(); - - boolean validCertificate = true; - - if (null != serviceCert) { - try { - serviceCert[0].checkValidity(); - } catch (Exception notValidException) { - validCertificate = false; - } - } - - if ("addCredential".equals(evtProp) && ((null == serviceCert) || !validCertificate)) { - // no service Cert or Non-valid Cert? Make one. - Exception failure = null; - - try { - X509Certificate peerCert = membership.getPSEConfig().getTrustedCertificate(group.getPeerID()); - - X500Principal credSubjectDN = cred.getCertificate().getSubjectX500Principal(); - X500Principal peerCertSubjectDN = peerCert.getSubjectX500Principal(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Checking credential cert for match to peer cert" + "\n\tcred subject=" + credSubjectDN - + "\n\tpeer subject=" + peerCertSubjectDN); - } - - if (peerCertSubjectDN.equals(credSubjectDN)) { - - serviceCert = cred.generateServiceCertificate(assignedID); - - } - } catch (IOException failed) { - failure = failed; - } catch (KeyStoreException failed) { - failure = failed; - } catch (InvalidKeyException failed) { - failure = failed; - } catch (SignatureException failed) { - failure = failed; - } - - if (null != failure) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failure building service certificate", failure); - } - - return; - } - } - - if ("addCredential".equals(evtProp)) { - Exception failure = null; - - try { - X509Certificate credCert = cred.getCertificate(); - - X500Principal credSubjectDN = credCert.getSubjectX500Principal(); - X500Principal serviceIssuerDN = serviceCert[0].getIssuerX500Principal(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Checking credential cert for match to service issuer cert" + "\n\tcred subject=" + credSubjectDN - + "\n\t svc issuer=" + serviceIssuerDN); - } - - if (credSubjectDN.equals(serviceIssuerDN)) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Setting credential/certfile "); - } - - credential = cred.getServiceCredential(assignedID); - - if (null != credential) { - credentialListener = new credentialPCL(); - credential.addPropertyChangeListener(credentialListener); - } - } - } catch (IOException failed) { - failure = failed; - } catch (PeerGroupException failed) { - failure = failed; - } catch (InvalidKeyException failed) { - failure = failed; - } catch (SignatureException failed) { - failure = failed; - } - - if (null != failure) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failure building service credential", failure); - } - - return; - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/package.html deleted file mode 100644 index 4190d5a7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/tls/package.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.endpoint.MessageTransport} implementation which - which provides secure, private message transmission using TLS sockets. A - virtual transport, the messages are transfered between peers using some - other message transport. - - @see JXTA Protocols Specification : Standard JXTA Transport Bindings - @see IETF RFC 2246: The TLS Protocol-Version 1.0 - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/ConditionalTransportMeterBuildSettings.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/ConditionalTransportMeterBuildSettings.java deleted file mode 100644 index 3f2e70ca..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/ConditionalTransportMeterBuildSettings.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * The Sun Project JXTA(TM) Software License - * - * Copyright (c) 2001-2006 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: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at https://jxta.dev.java.net. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * https://jxta.dev.java.net/ - * - * This license is based on the BSD license adopted by the Apache Foundation. - * - */ - - -/* **** THIS IS A GENERATED FILE. DO NOT EDIT. **** */ - -package net.jxta.impl.endpoint.transportMeter; - -import java.util.ResourceBundle; -import net.jxta.impl.meter.*; - -public class ConditionalTransportMeterBuildSettings { - public static boolean isRuntimeMetering() { - boolean runtimeMetering = false; - - try { - ResourceBundle userResourceBundle = ResourceBundle.getBundle( "net.jxta.user" ); - String meteringProperty = "net.jxta.meter.conditionalTransportMetering"; - String meteringValue = userResourceBundle.getString( meteringProperty ); - runtimeMetering = "on".equalsIgnoreCase( meteringValue ); - } catch (Exception ignored) { - } - - return runtimeMetering; - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportBindingMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportBindingMeter.java deleted file mode 100644 index 2fc3bb68..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportBindingMeter.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.transportMeter; - - -import net.jxta.peer.PeerID; -import net.jxta.endpoint.*; - - -public class TransportBindingMeter { - private PeerID peerID; - private EndpointAddress endpointAddress; - - private TransportBindingMetric cumulativeMetrics; - private TransportBindingMetric deltaMetrics; - - public TransportBindingMeter(PeerID peerID, EndpointAddress endpointAddress) { - this(peerID, endpointAddress, false, false); - } - - public TransportBindingMeter(PeerID peerID, EndpointAddress endpointAddress, boolean initiatorConnected, boolean acceptorConnected) { - this.peerID = peerID; - this.endpointAddress = endpointAddress; - cumulativeMetrics = new TransportBindingMetric(this, initiatorConnected, acceptorConnected); - } - - @Override - public String toString() { - return "TransportBindingMeter(" + endpointAddress + ";" + peerID + ")"; - } - - public synchronized TransportBindingMetric collectMetrics() { - TransportBindingMetric prevDelta = deltaMetrics; - - deltaMetrics = null; - return prevDelta; - } - - private void createDeltaMetric() { - deltaMetrics = new TransportBindingMetric(cumulativeMetrics); - } - - public TransportBindingMetric getCumulativeMetrics() { - return cumulativeMetrics; - } - - public PeerID getPeerID() { - return peerID; - } - - public EndpointAddress getEndpointAddress() { - return endpointAddress; - } - - public void setPeerID(PeerID peerID) { - this.peerID = peerID; - cumulativeMetrics.setPeerID(peerID); - - if (deltaMetrics != null) { - deltaMetrics.setPeerID(peerID); - } - } - - public synchronized void connectionEstablished(boolean initator, long timeToConnect) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - long now = System.currentTimeMillis(); - - deltaMetrics.connectionEstablished(initator, timeToConnect, now); - cumulativeMetrics.connectionEstablished(initator, timeToConnect, now); - } - - public synchronized void connectionFailed(boolean initator, long timeToConnect) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - long now = System.currentTimeMillis(); - - deltaMetrics.connectionFailed(initator, timeToConnect, now); - cumulativeMetrics.connectionFailed(initator, timeToConnect, now); - } - - public synchronized void connectionClosed(boolean initator, long connectionLife) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - long now = System.currentTimeMillis(); - - deltaMetrics.connectionClosed(initator, now); - cumulativeMetrics.connectionClosed(initator, now); - } - - public synchronized void connectionDropped(boolean initator, long connectionLife) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - long now = System.currentTimeMillis(); - - deltaMetrics.connectionDropped(initator, now); - cumulativeMetrics.connectionDropped(initator, now); - } - - public synchronized void pingReceived() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.pingReceived(); - cumulativeMetrics.pingReceived(); - } - - public synchronized void ping(long time) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.ping(time); - cumulativeMetrics.ping(time); - } - - public synchronized void pingFailed(long time) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.pingFailed(time); - cumulativeMetrics.pingFailed(time); - } - - public synchronized void dataReceived(boolean initator, int size) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.dataReceived(initator, size); - cumulativeMetrics.dataReceived(initator, size); - } - - public synchronized void messageReceived(boolean initator, Message message, long time, long size) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.messageReceived(initator, message, time, size); - cumulativeMetrics.messageReceived(initator, message, time, size); - } - - public synchronized void receiveFailure(boolean initator, long time, long size) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.receiveFailure(initator, time, size); - cumulativeMetrics.receiveFailure(initator, time, size); - } - - public synchronized void dataSent(boolean initator, long size) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.dataSent(initator, size); - cumulativeMetrics.dataSent(initator, size); - } - - public synchronized void sendFailure(boolean initator, Message message, long time, long size) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.sendFailure(initator, message, time, size); - cumulativeMetrics.sendFailure(initator, message, time, size); - } - - public synchronized void messageSent(boolean initator, Message message, long time, long size) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.messageSent(initator, message, time, size); - cumulativeMetrics.messageSent(initator, message, time, size); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportBindingMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportBindingMetric.java deleted file mode 100644 index 1af8e6af..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportBindingMetric.java +++ /dev/null @@ -1,1135 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.transportMeter; - - -import net.jxta.document.Element; -import net.jxta.document.TextElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.impl.meter.MetricUtilities; -import net.jxta.peer.PeerID; -import net.jxta.util.documentSerializable.DocumentSerializable; -import net.jxta.util.documentSerializable.DocumentSerializableUtilities; -import net.jxta.util.documentSerializable.DocumentSerializationException; - -import java.util.Enumeration; - - -public class TransportBindingMetric implements DocumentSerializable { - public static final String CONNECTED = "connected"; - public static final String CLOSED = "closed"; - public static final String DROPPED = "dropped"; - public static final String FAILED = "failed"; - - private PeerID peerID; - private EndpointAddress endpointAddress; - - private String initiatorState = null; - private String acceptorState = null; - private long initiatorTransitionTime; - private long acceptorTransitionTime; - - private int acceptorBytesReceived; - private int acceptorBytesSent; - private int acceptorConnections; - private int acceptorConnectionsClosed; - private int acceptorConnectionsDropped; - private int acceptorConnectionsFailed; - private int acceptorMessagesReceived; - private int acceptorMessagesSent; - private long acceptorReceiveFailureProcessingTime; - private int acceptorReceiveFailures; - private long acceptorReceiveProcessingTime; - private long acceptorSendFailureProcessingTime; - private int acceptorSendFailures; - private long acceptorSendProcessingTime; - private long acceptorTotalTimeConnected; - private long acceptorTimeToConnect; - private long acceptorTimeToFail; - private int initiatorBytesReceived; - private int initiatorBytesSent; - private long initiatorTotalTimeConnected; - private int initiatorConnections; - private int initiatorConnectionsClosed; - private int initiatorConnectionsDropped; - private int initiatorConnectionsFailed; - private int initiatorMessagesReceived; - private int initiatorMessagesSent; - private long initiatorReceiveFailureProcessingTime; - private int initiatorReceiveFailures; - private long initiatorReceiveProcessingTime; - private long initiatorSendFailureProcessingTime; - private int initiatorSendFailures; - private long initiatorSendProcessingTime; - private long initiatorTimeToConnect; - private long initiatorTimeToFail; - - private int numPings; - private int numFailedPings; - private long pingTime; - private long pingFailedTime; - private int numPingsReceived; - - public TransportBindingMetric(TransportBindingMeter transportBindingMeter, boolean initiatorConnected, boolean acceptorConnected) { - this.peerID = transportBindingMeter.getPeerID(); - this.endpointAddress = transportBindingMeter.getEndpointAddress(); - this.initiatorState = initiatorConnected ? CONNECTED : CLOSED; - this.acceptorState = acceptorConnected ? CONNECTED : CLOSED; - } - - public TransportBindingMetric() {} - - public TransportBindingMetric(TransportBindingMetric prototype) { - this.peerID = prototype.peerID; - this.endpointAddress = prototype.endpointAddress; - this.initiatorState = prototype.initiatorState; - this.acceptorState = prototype.acceptorState; - this.initiatorTransitionTime = prototype.initiatorTransitionTime; - this.acceptorTransitionTime = prototype.acceptorTransitionTime; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof TransportBindingMetric) { - TransportBindingMetric other = (TransportBindingMetric) obj; - - return endpointAddress.equals(other.endpointAddress); - } else { - return false; - } - } - - @Override - public int hashCode() { - return peerID.hashCode() + endpointAddress.hashCode(); - } - - public PeerID getPeerID() { - return peerID; - } - - public void setPeerID(PeerID peerID) { - this.peerID = peerID; - } - - public EndpointAddress getEndpointAddress() { - return endpointAddress; - } - - /** - * State of this Initiator Binding - * - * @return TransportBindingMetric.CONNECTED, TransportBindingMetric.DISCONNECTED or TransportBindingMetric.FAILED - */ - public String getInitiatorState() { - return initiatorState; - } - - /** - * State of this Acceptor Binding - * - * @return TransportBindingMetric.CONNECTED, TransportBindingMetric.DISCONNECTED or TransportBindingMetric.FAILED - */ - public String getAcceptorState() { - return acceptorState; - } - - /** - * Get the time that it entered the current state - * - * @return transition time in ms since January 1, 1970, 00:00:00 GMT - */ - public long getInitiatorTransitionTime() { - return initiatorTransitionTime; - } - - /** - * Get the time that it entered the current state - * - * @return transition time in ms since January 1, 1970, 00:00:00 GMT - */ - public long getAcceptorTransitionTime() { - return acceptorTransitionTime; - } - - public boolean isAcceptorConnected() { - return (acceptorState != null) && acceptorState.equals(CONNECTED); - } - - public boolean isInitiatorConnected() { - return (initiatorState != null) && initiatorState.equals(CONNECTED); - } - - public long getTimeAcceptorConnectionEstablished() { - return isAcceptorConnected() ? acceptorTransitionTime : 0; - } - - public long getTimeInitiatorConnectionEstablished() { - return isInitiatorConnected() ? initiatorTransitionTime : 0; - } - - public int getAcceptorBytesReceived() { - return acceptorBytesReceived; - } - - public int getAcceptorBytesSent() { - return acceptorBytesSent; - } - - public int getAcceptorConnections() { - return acceptorConnections; - } - - public int getAcceptorConnectionsClosed() { - return acceptorConnectionsClosed; - } - - public int getAcceptorConnectionsDropped() { - return acceptorConnectionsDropped; - } - - public int getAcceptorConnectionsFailed() { - return acceptorConnectionsFailed; - } - - public int getAcceptorMessagesReceived() { - return acceptorMessagesReceived; - } - - public int getAcceptorMessagesSent() { - return acceptorMessagesSent; - } - - public long getAcceptorReceiveFailureProcessingTime() { - return acceptorReceiveFailureProcessingTime; - } - - public int getAcceptorReceiveFailures() { - return acceptorReceiveFailures; - } - - public long getAcceptorReceiveProcessingTime() { - return acceptorReceiveProcessingTime; - } - - public long getAcceptorSendFailureProcessingTime() { - return acceptorSendFailureProcessingTime; - } - - public int getAcceptorSendFailures() { - return acceptorSendFailures; - } - - public long getAcceptorSendProcessingTime() { - return acceptorSendProcessingTime; - } - - public long getAcceptorTimeToConnect() { - return acceptorTimeToConnect; - } - - public long getAcceptorTimeToFail() { - return acceptorTimeToFail; - } - - public int getInitiatorBytesReceived() { - return initiatorBytesReceived; - } - - public int getInitiatorBytesSent() { - return initiatorBytesSent; - } - - public int getInitiatorConnections() { - return initiatorConnections; - } - - public int getInitiatorConnectionsClosed() { - return initiatorConnectionsClosed; - } - - public int getInitiatorConnectionsDropped() { - return initiatorConnectionsDropped; - } - - public int getInitiatorConnectionsFailed() { - return initiatorConnectionsFailed; - } - - public int getInitiatorMessagesReceived() { - return initiatorMessagesReceived; - } - - public int getInitiatorMessagesSent() { - return initiatorMessagesSent; - } - - public long getInitiatorReceiveFailureProcessingTime() { - return initiatorReceiveFailureProcessingTime; - } - - public int getInitiatorReceiveFailures() { - return initiatorReceiveFailures; - } - - public long getInitiatorReceiveProcessingTime() { - return initiatorReceiveProcessingTime; - } - - public long getInitiatorSendFailureProcessingTime() { - return initiatorSendFailureProcessingTime; - } - - public int getInitiatorSendFailures() { - return initiatorSendFailures; - } - - public long getInitiatorSendProcessingTime() { - return initiatorSendProcessingTime; - } - - public long getInitiatorTimeToConnect() { - return initiatorTimeToConnect; - } - - public long getInitiatorTimeToFail() { - return initiatorTimeToFail; - } - - public int getNumPings() { - return numPings; - } - - public int getNumFailedPings() { - return numFailedPings; - } - - public long getPingTime() { - return pingTime; - } - - public long getPingFailedTime() { - return pingFailedTime; - } - - public int getNumPingsReceived() { - return numPingsReceived; - } - - public int getBytesReceived() { - return acceptorBytesReceived + initiatorBytesReceived; - } - - public int getBytesSent() { - return acceptorBytesSent + initiatorBytesSent; - } - - public int getConnections() { - return acceptorConnections + initiatorConnections; - } - - public int getConnectionsClosed() { - return acceptorConnectionsClosed + initiatorConnectionsClosed; - } - - public int getConnectionsDropped() { - return acceptorConnectionsDropped + initiatorConnectionsDropped; - } - - public int getConnectionsFailed() { - return acceptorConnectionsFailed + initiatorConnectionsFailed; - } - - public int getMessagesReceived() { - return acceptorMessagesReceived + initiatorMessagesReceived; - } - - public int getMessagesSent() { - return acceptorMessagesSent + initiatorMessagesSent; - } - - public long getReceiveFailureProcessingTime() { - return acceptorReceiveFailureProcessingTime + initiatorReceiveFailureProcessingTime; - } - - public int getReceiveFailures() { - return acceptorReceiveFailures + initiatorReceiveFailures; - } - - public long getReceiveProcessingTime() { - return acceptorReceiveProcessingTime + initiatorReceiveProcessingTime; - } - - public long getSendFailureProcessingTime() { - return acceptorSendFailureProcessingTime + initiatorSendFailureProcessingTime; - } - - public int getSendFailures() { - return acceptorSendFailures + initiatorSendFailures; - } - - public long getSendProcessingTime() { - return acceptorSendProcessingTime + initiatorSendProcessingTime; - } - - public long getTotalTimeConnected() { - return acceptorTotalTimeConnected + initiatorTotalTimeConnected; - } - - public long getTimeToConnect() { - return acceptorTimeToConnect + initiatorTimeToConnect; - } - - public long getTimeToFail() { - return acceptorTimeToFail + initiatorTimeToFail; - } - - public int getAveragePingTime() { - return (int) ((numPings != 0) ? (pingTime / numPings) : 0); - } - - public int getAveragePingFailedTime() { - return (int) ((numFailedPings != 0) ? (pingFailedTime / numFailedPings) : 0); - } - - public int getAverageAcceptorReceiveFailureProcessingTime() { - return (int) ((acceptorReceiveFailures != 0) ? (acceptorReceiveFailureProcessingTime / acceptorReceiveFailures) : 0); - } - - public int getAverageAcceptorReceiveProcessingTime() { - return (int) ((acceptorMessagesReceived != 0) ? (acceptorReceiveProcessingTime / acceptorMessagesReceived) : 0); - } - - public int getAverageAcceptorSendFailureProcessingTime() { - return (int) ((acceptorSendFailures != 0) ? (acceptorSendFailureProcessingTime / acceptorSendFailures) : 0); - } - - public int getAverageAcceptorSendProcessingTime() { - return (int) ((acceptorMessagesSent != 0) ? (acceptorSendProcessingTime / acceptorMessagesSent) : 0); - } - - public int getAverageAcceptorTimeToConnect() { - return (int) ((acceptorConnections != 0) ? (acceptorTimeToConnect / acceptorConnections) : 0); - } - - public int getAverageAcceptorTimeToFail() { - return (int) ((acceptorConnectionsFailed != 0) ? (acceptorTimeToFail / acceptorConnectionsFailed) : 0); - } - - public int getAverageInitiatorReceiveFailureProcessingTime() { - return (int) ((initiatorReceiveFailures != 0) ? (initiatorReceiveFailureProcessingTime / initiatorReceiveFailures) : 0); - } - - public int getAverageInitiatorReceiveProcessingTime() { - return (int) ((initiatorMessagesReceived != 0) ? (initiatorReceiveProcessingTime / initiatorMessagesReceived) : 0); - } - - public int getAverageInitiatorSendFailureProcessingTime() { - return (int) ((initiatorSendFailures != 0) ? (initiatorSendFailureProcessingTime / initiatorSendFailures) : 0); - } - - public int getAverageInitiatorSendProcessingTime() { - return (int) ((initiatorMessagesSent != 0) ? (initiatorSendProcessingTime / initiatorMessagesSent) : 0); - } - - public int getAverageInitiatorTimeToConnect() { - return (int) ((initiatorConnections != 0) ? (initiatorTimeToConnect / initiatorConnections) : 0); - } - - public int getAverageInitiatorTimeToFail() { - return (int) ((initiatorConnectionsFailed != 0) ? (initiatorTimeToFail / initiatorConnectionsFailed) : 0); - } - - public int getAverageReceiveFailureProcessingTime() { - return (int) (((initiatorReceiveFailures + acceptorReceiveFailures) != 0) - ? ((initiatorReceiveFailureProcessingTime + acceptorReceiveFailureProcessingTime) - / (initiatorReceiveFailures + acceptorReceiveFailures)) - : 0); - } - - public int getAverageReceiveProcessingTime() { - return (int) (((initiatorMessagesReceived + acceptorMessagesReceived) != 0) - ? ((initiatorReceiveProcessingTime + acceptorReceiveProcessingTime) - / (initiatorMessagesReceived + acceptorMessagesReceived)) - : 0); - } - - public int getAverageSendFailureProcessingTime() { - return (int) (((initiatorSendFailures + acceptorSendFailures) != 0) - ? ((initiatorSendFailureProcessingTime + acceptorSendFailureProcessingTime) - / (initiatorSendFailures + acceptorSendFailures)) - : 0); - } - - public int getAverageSendProcessingTime() { - return (int) (((initiatorMessagesSent + acceptorMessagesSent) != 0) - ? ((initiatorSendProcessingTime + acceptorSendProcessingTime) / (initiatorMessagesSent + acceptorMessagesSent)) - : 0); - } - - public int getAverageTimeToConnect() { - return (int) (((initiatorConnections + acceptorConnections) != 0) - ? ((initiatorTimeToConnect + acceptorTimeToConnect) / (initiatorConnections + acceptorConnections)) - : 0); - } - - public int getAverageTimeToFail() { - return (int) (((initiatorConnectionsFailed + acceptorConnectionsFailed) != 0) - ? ((initiatorTimeToFail + acceptorTimeToFail) / (initiatorConnectionsFailed + acceptorConnectionsFailed)) - : 0); - } - - /** - * Get the total time this intiated connection has been connected. - *

            - * Note: This does not include the current time connected (if it is currently connected) - * - * @return time in ms (see note above) - * @see #getTotalTimeConnected() - */ - public long getInitiatorTotalTimeConnected() { - return initiatorTotalTimeConnected; - } - - /** - * Get the total time this initiating connection has been connected. If it is currently - * connected, then the total time is adjusted to include the time since the transition time - * to become connected until the provided time - * - * @param adjustmentTime The time of this metric will be adjusted to - * @return time in ms (see note above) - * @see #getTotalTimeConnected() - */ - public long getInitiatorTotalTimeConnected(long adjustmentTime) { - long result = initiatorTotalTimeConnected; - - if (isInitiatorConnected()) { - result += (adjustmentTime - this.initiatorTransitionTime); - } - - return result; - } - - /** - * Get the duration of current connection relative to local clock (from transition time) - *

            - * Note: This assumes the clocks are in sync with the reporting peer - * - * @return time in ms (see note above) or 0 if not connected - * @see #getTotalTimeConnected() - */ - public long getInitiatorTimeConnected() { - return getInitiatorTimeConnected(System.currentTimeMillis()); - } - - /** - * Get the duration of current connection until the specified time - * - * @param adjustmentTime The time of this metric will be computed until - * @return time in ms (see note above) or 0 if not connected - */ - public long getInitiatorTimeConnected(long adjustmentTime) { - - if (isInitiatorConnected()) { - return (adjustmentTime - this.initiatorTransitionTime); - } else { - return 0; - } - } - - /** - * Get the total time this intiated connection has been connected. - *

            - * Note: This does not include the current time connected (if it is currently connected) - * - * @return time in ms (see note above) - * @see #getTotalTimeConnected() - */ - public long getAcceptorTotalTimeConnected() { - return acceptorTotalTimeConnected; - } - - /** - * Get the total time this initiating connection has been connected. If it is currently - * connected, then the total time is adjusted to include the time since the transition time - * to become connected until the provided time - * - * @param adjustmentTime The time of this metric will be adjusted to - * @return time in ms (see note above) - * @see #getTotalTimeConnected() - */ - public long getAcceptorTotalTimeConnected(long adjustmentTime) { - long result = acceptorTotalTimeConnected; - - if (isAcceptorConnected()) { - result += (adjustmentTime - this.acceptorTransitionTime); - } - - return result; - } - - /** - * Get the duration of current connection relative to local clock (from transition time) - *

            - * Note: This assumes the clocks are in sync with the reporting peer - * - * @return time in ms (see note above) or 0 if not connected - * @see #getTotalTimeConnected() - */ - public long getAcceptorTimeConnected() { - return getAcceptorTimeConnected(System.currentTimeMillis()); - } - - /** - * Get the duration of current connection until the specified time - * - * @param adjustmentTime The time of this metric will be computed until - * @return time in ms (see note above) or 0 if not connected - */ - public long getAcceptorTimeConnected(long adjustmentTime) { - - if (isAcceptorConnected()) { - return (adjustmentTime - this.acceptorTransitionTime); - } else { - return 0; - } - } - - void resetInitiatorState(String state, long transitionTime) { - if (isInitiatorConnected()) { - acceptorTotalTimeConnected += (System.currentTimeMillis() - this.initiatorTransitionTime); - } - - this.initiatorState = state; - this.initiatorTransitionTime = transitionTime; - // System.out.println("initiatorState: " + initiatorState + " " + endpointAddress); - } - - void resetAcceptorState(String state, long transitionTime) { - if (isAcceptorConnected()) { - initiatorTotalTimeConnected += (System.currentTimeMillis() - this.acceptorTransitionTime); - } - - this.acceptorState = state; - this.acceptorTransitionTime = transitionTime; - // System.out.println("acceptorState: " + acceptorState + " " + endpointAddress); - } - - void connectionEstablished(boolean initiator, long timeToConnect, long transitionTime) { - if (initiator) { - resetInitiatorState(CONNECTED, transitionTime); - initiatorConnections++; - initiatorTimeToConnect += timeToConnect; - } else { - resetAcceptorState(CONNECTED, transitionTime); - acceptorConnections++; - acceptorTimeToConnect += timeToConnect; - } - - } - - void connectionFailed(boolean initiator, long timeToConnect, long transitionTime) { - if (initiator) { - resetInitiatorState(FAILED, transitionTime); - initiatorConnectionsFailed++; - initiatorTimeToFail += timeToConnect; - } else { - resetAcceptorState(FAILED, transitionTime); - acceptorConnectionsFailed++; - acceptorTimeToFail += timeToConnect; - } - } - - void connectionClosed(boolean initiator, long transitionTime) { - if (initiator) { - resetInitiatorState(CLOSED, transitionTime); - initiatorConnectionsClosed++; - } else { - resetAcceptorState(CLOSED, transitionTime); - acceptorConnectionsClosed++; - } - } - - void connectionDropped(boolean initiator, long transitionTime) { - if (initiator) { - resetInitiatorState(DROPPED, transitionTime); - initiatorConnectionsDropped++; - } else { - resetAcceptorState(DROPPED, transitionTime); - acceptorConnectionsDropped++; - } - } - - void pingReceived() { - numPingsReceived++; - } - - void ping(long time) { - numPings++; - pingTime += time; - } - - void pingFailed(long time) { - numFailedPings++; - pingFailedTime += time; - } - - void dataReceived(boolean initiator, int size) { - if (initiator) { - initiatorBytesReceived += size; - } else { - acceptorBytesReceived += size; - } - } - - void messageReceived(boolean initiator, Message message, long time, long size) { - if (initiator) { - initiatorMessagesReceived++; - initiatorReceiveProcessingTime += time; - initiatorBytesReceived += size; - } else { - acceptorMessagesReceived++; - acceptorReceiveProcessingTime += time; - acceptorBytesReceived += size; - } - } - - void receiveFailure(boolean initiator, long time, long size) { - if (initiator) { - initiatorReceiveFailures++; - initiatorReceiveFailureProcessingTime += time; - initiatorBytesReceived += size; - } else { - acceptorReceiveFailures++; - acceptorReceiveFailureProcessingTime += time; - acceptorBytesReceived += size; - } - } - - void dataSent(boolean initiator, long size) { - if (initiator) { - initiatorBytesSent += size; - } else { - acceptorBytesSent += size; - } - } - - void sendFailure(boolean initiator, Message message, long time, long size) { - if (initiator) { - initiatorSendFailures++; - initiatorSendFailureProcessingTime += time; - initiatorBytesSent += size; - } else { - acceptorSendFailures++; - acceptorSendFailureProcessingTime += time; - acceptorBytesSent += size; - } - } - - void messageSent(boolean initiator, Message message, long time, long size) { - if (initiator) { - initiatorMessagesSent++; - initiatorSendProcessingTime += time; - initiatorBytesSent += size; - } else { - acceptorMessagesSent++; - acceptorSendProcessingTime += time; - acceptorBytesSent += size; - } - } - - public void mergeMetrics(TransportBindingMetric other) { - peerID = other.peerID; - - if (other.initiatorState != null) { - initiatorState = other.initiatorState; - } - - if (other.initiatorTransitionTime != 0) { - initiatorTransitionTime = other.initiatorTransitionTime; - } - - if (other.acceptorState != null) { - acceptorState = other.acceptorState; - } - - if (other.initiatorTransitionTime != 0) { - acceptorTransitionTime = other.acceptorTransitionTime; - } - - acceptorBytesReceived += other.acceptorBytesReceived; - acceptorBytesSent += other.acceptorBytesSent; - acceptorConnections += other.acceptorConnections; - acceptorConnectionsClosed += other.acceptorConnectionsClosed; - acceptorConnectionsDropped += other.acceptorConnectionsDropped; - acceptorConnectionsFailed += other.acceptorConnectionsFailed; - acceptorMessagesReceived += other.acceptorMessagesReceived; - acceptorMessagesSent += other.acceptorMessagesSent; - acceptorReceiveFailureProcessingTime += other.acceptorReceiveFailureProcessingTime; - acceptorReceiveFailures += other.acceptorReceiveFailures; - acceptorReceiveProcessingTime += other.acceptorReceiveProcessingTime; - acceptorSendFailureProcessingTime += other.acceptorSendFailureProcessingTime; - acceptorSendFailures += other.acceptorSendFailures; - acceptorSendProcessingTime += other.acceptorSendProcessingTime; - acceptorTotalTimeConnected += other.acceptorTotalTimeConnected; - acceptorTimeToConnect += other.acceptorTimeToConnect; - acceptorTimeToFail += other.acceptorTimeToFail; - initiatorBytesReceived += other.initiatorBytesReceived; - initiatorBytesSent += other.initiatorBytesSent; - initiatorTotalTimeConnected += other.initiatorTotalTimeConnected; - initiatorConnections += other.initiatorConnections; - initiatorConnectionsClosed += other.initiatorConnectionsClosed; - initiatorConnectionsDropped += other.initiatorConnectionsDropped; - initiatorConnectionsFailed += other.initiatorConnectionsFailed; - initiatorMessagesReceived += other.initiatorMessagesReceived; - initiatorMessagesSent += other.initiatorMessagesSent; - initiatorReceiveFailureProcessingTime += other.initiatorReceiveFailureProcessingTime; - initiatorReceiveFailures += other.initiatorReceiveFailures; - initiatorReceiveProcessingTime += other.initiatorReceiveProcessingTime; - initiatorSendFailureProcessingTime += other.initiatorSendFailureProcessingTime; - initiatorSendFailures += other.initiatorSendFailures; - initiatorSendProcessingTime += other.initiatorSendProcessingTime; - initiatorTimeToConnect += other.initiatorTimeToConnect; - initiatorTimeToFail += other.initiatorTimeToFail; - numPings += other.numPings; - numFailedPings += other.numFailedPings; - pingTime += other.pingTime; - pingFailedTime += other.pingFailedTime; - numPingsReceived += other.numPingsReceived; - - } - - public void serializeTo(Element element) throws DocumentSerializationException { - - DocumentSerializableUtilities.addString(element, "peerID", peerID.toString()); - DocumentSerializableUtilities.addString(element, "endpointAddress", endpointAddress.toString()); - - if (initiatorState != null) { - DocumentSerializableUtilities.addString(element, "initiatorState", initiatorState); - } - if (initiatorTransitionTime != 0) { - DocumentSerializableUtilities.addLong(element, "initiatorTransitionTime", initiatorTransitionTime); - } - - if (acceptorState != null) { - DocumentSerializableUtilities.addString(element, "acceptorState", acceptorState); - } - if (acceptorTransitionTime != 0) { - DocumentSerializableUtilities.addLong(element, "acceptorTransitionTime", acceptorTransitionTime); - } - - if (acceptorBytesReceived != 0) { - DocumentSerializableUtilities.addInt(element, "acceptorBytesReceived", acceptorBytesReceived); - } - - if (acceptorBytesSent != 0) { - DocumentSerializableUtilities.addInt(element, "acceptorBytesSent", acceptorBytesSent); - } - - if (acceptorConnections != 0) { - DocumentSerializableUtilities.addInt(element, "acceptorConnections", acceptorConnections); - } - - if (acceptorConnectionsClosed != 0) { - DocumentSerializableUtilities.addInt(element, "acceptorConnectionsClosed", acceptorConnectionsClosed); - } - - if (acceptorConnectionsDropped != 0) { - DocumentSerializableUtilities.addInt(element, "acceptorConnectionsDropped", acceptorConnectionsDropped); - } - - if (acceptorConnectionsFailed != 0) { - DocumentSerializableUtilities.addInt(element, "acceptorConnectionsFailed", acceptorConnectionsFailed); - } - - if (acceptorMessagesReceived != 0) { - DocumentSerializableUtilities.addInt(element, "acceptorMessagesReceived", acceptorMessagesReceived); - } - - if (acceptorMessagesSent != 0) { - DocumentSerializableUtilities.addInt(element, "acceptorMessagesSent", acceptorMessagesSent); - } - - if (acceptorReceiveFailureProcessingTime != 0) { - DocumentSerializableUtilities.addLong(element, "acceptorReceiveFailureProcessingTime" - , - acceptorReceiveFailureProcessingTime); - } - - if (acceptorReceiveFailures != 0) { - DocumentSerializableUtilities.addInt(element, "acceptorReceiveFailures", acceptorReceiveFailures); - } - - if (acceptorReceiveProcessingTime != 0) { - DocumentSerializableUtilities.addLong(element, "acceptorReceiveProcessingTime", acceptorReceiveProcessingTime); - } - - if (acceptorSendFailureProcessingTime != 0) { - DocumentSerializableUtilities.addLong(element, "acceptorSendFailureProcessingTime", acceptorSendFailureProcessingTime); - } - - if (acceptorSendFailures != 0) { - DocumentSerializableUtilities.addInt(element, "acceptorSendFailures", acceptorSendFailures); - } - - if (acceptorSendProcessingTime != 0) { - DocumentSerializableUtilities.addLong(element, "acceptorSendProcessingTime", acceptorSendProcessingTime); - } - - if (acceptorTotalTimeConnected != 0) { - DocumentSerializableUtilities.addLong(element, "acceptorTotalTimeConnected", acceptorTotalTimeConnected); - } - - if (acceptorTimeToConnect != 0) { - DocumentSerializableUtilities.addLong(element, "acceptorTimeToConnect", acceptorTimeToConnect); - } - - if (acceptorTimeToFail != 0) { - DocumentSerializableUtilities.addLong(element, "acceptorTimeToFail", acceptorTimeToFail); - } - - if (initiatorBytesReceived != 0) { - DocumentSerializableUtilities.addInt(element, "initiatorBytesReceived", initiatorBytesReceived); - } - - if (initiatorBytesSent != 0) { - DocumentSerializableUtilities.addInt(element, "initiatorBytesSent", initiatorBytesSent); - } - - if (initiatorTotalTimeConnected != 0) { - DocumentSerializableUtilities.addLong(element, "initiatorTotalTimeConnected", initiatorTotalTimeConnected); - } - - if (initiatorConnections != 0) { - DocumentSerializableUtilities.addInt(element, "initiatorConnections", initiatorConnections); - } - - if (initiatorConnectionsClosed != 0) { - DocumentSerializableUtilities.addInt(element, "initiatorConnectionsClosed", initiatorConnectionsClosed); - } - - if (initiatorConnectionsDropped != 0) { - DocumentSerializableUtilities.addInt(element, "initiatorConnectionsDropped", initiatorConnectionsDropped); - } - - if (initiatorConnectionsFailed != 0) { - DocumentSerializableUtilities.addInt(element, "initiatorConnectionsFailed", initiatorConnectionsFailed); - } - - if (initiatorMessagesReceived != 0) { - DocumentSerializableUtilities.addInt(element, "initiatorMessagesReceived", initiatorMessagesReceived); - } - - if (initiatorMessagesSent != 0) { - DocumentSerializableUtilities.addInt(element, "initiatorMessagesSent", initiatorMessagesSent); - } - - if (initiatorReceiveFailureProcessingTime != 0) { - DocumentSerializableUtilities.addLong(element, "initiatorReceiveFailureProcessingTime" - , - initiatorReceiveFailureProcessingTime); - } - - if (initiatorReceiveFailures != 0) { - DocumentSerializableUtilities.addInt(element, "initiatorReceiveFailures", initiatorReceiveFailures); - } - - if (initiatorReceiveProcessingTime != 0) { - DocumentSerializableUtilities.addLong(element, "initiatorReceiveProcessingTime", initiatorReceiveProcessingTime); - } - - if (initiatorSendFailureProcessingTime != 0) { - DocumentSerializableUtilities.addLong(element, "initiatorSendFailureProcessingTime" - , - initiatorSendFailureProcessingTime); - } - - if (initiatorSendFailures != 0) { - DocumentSerializableUtilities.addInt(element, "initiatorSendFailures", initiatorSendFailures); - } - - if (initiatorSendProcessingTime != 0) { - DocumentSerializableUtilities.addLong(element, "initiatorSendProcessingTime", initiatorSendProcessingTime); - } - - if (initiatorTimeToConnect != 0) { - DocumentSerializableUtilities.addLong(element, "initiatorTimeToConnect", initiatorTimeToConnect); - } - - if (initiatorTimeToFail != 0) { - DocumentSerializableUtilities.addLong(element, "initiatorTimeToFail", initiatorTimeToFail); - } - - if (numPings != 0) { - DocumentSerializableUtilities.addInt(element, "numPings", numPings); - } - - if (numFailedPings != 0) { - DocumentSerializableUtilities.addInt(element, "numFailedPings", numFailedPings); - } - - if (pingTime != 0) { - DocumentSerializableUtilities.addLong(element, "pingTime", pingTime); - } - - if (pingFailedTime != 0) { - DocumentSerializableUtilities.addLong(element, "pingFailedTime", pingFailedTime); - } - - if (initiatorTimeToFail != 0) { - DocumentSerializableUtilities.addInt(element, "numPingsReceived", numPingsReceived); - } - - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("peerID")) { - String peerIdString = DocumentSerializableUtilities.getString(childElement); - - peerID = MetricUtilities.getPeerIdFromString(peerIdString); - } - if (tagName.equals("endpointAddress")) { - String endpointAddressString = DocumentSerializableUtilities.getString(childElement); - - endpointAddress = new EndpointAddress(endpointAddressString); - } else if (tagName.equals("acceptorBytesReceived")) { - acceptorBytesReceived = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("acceptorBytesSent")) { - acceptorBytesSent = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("acceptorConnections")) { - acceptorConnections = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("acceptorConnectionsClosed")) { - acceptorConnectionsClosed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("acceptorConnectionsDropped")) { - acceptorConnectionsDropped = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("acceptorConnectionsFailed")) { - acceptorConnectionsFailed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("acceptorMessagesReceived")) { - acceptorMessagesReceived = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("acceptorMessagesSent")) { - acceptorMessagesSent = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("acceptorReceiveFailureProcessingTime")) { - acceptorReceiveFailureProcessingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("acceptorReceiveFailures")) { - acceptorReceiveFailures = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("acceptorReceiveProcessingTime")) { - acceptorReceiveProcessingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("acceptorSendFailureProcessingTime")) { - acceptorSendFailureProcessingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("acceptorSendFailures")) { - acceptorSendFailures = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("acceptorSendProcessingTime")) { - acceptorSendProcessingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("acceptorTotalTimeConnected")) { - acceptorTotalTimeConnected = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("acceptorTimeToConnect")) { - acceptorTimeToConnect = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("acceptorTimeToFail")) { - acceptorTimeToFail = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("initiatorBytesReceived")) { - initiatorBytesReceived = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("initiatorBytesSent")) { - initiatorBytesSent = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("initiatorTotalTimeConnected")) { - initiatorTotalTimeConnected = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("initiatorConnections")) { - initiatorConnections = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("initiatorConnectionsClosed")) { - initiatorConnectionsClosed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("initiatorConnectionsDropped")) { - initiatorConnectionsDropped = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("initiatorConnectionsFailed")) { - initiatorConnectionsFailed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("initiatorMessagesReceived")) { - initiatorMessagesReceived = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("initiatorMessagesSent")) { - initiatorMessagesSent = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("initiatorReceiveFailureProcessingTime")) { - initiatorReceiveFailureProcessingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("initiatorReceiveFailures")) { - initiatorReceiveFailures = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("initiatorReceiveProcessingTime")) { - initiatorReceiveProcessingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("initiatorSendFailureProcessingTime")) { - initiatorSendFailureProcessingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("initiatorSendFailures")) { - initiatorSendFailures = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("initiatorSendProcessingTime")) { - initiatorSendProcessingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("initiatorTimeToConnect")) { - initiatorTimeToConnect = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("initiatorTimeToFail")) { - initiatorTimeToFail = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numPingsReceived")) { - numPingsReceived = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPings")) { - numPings = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numFailedPings")) { - numFailedPings = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("pingTime")) { - pingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("pingFailedTime")) { - pingFailedTime = DocumentSerializableUtilities.getLong(childElement); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportMeter.java deleted file mode 100644 index ca544b60..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportMeter.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.transportMeter; - - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.impl.meter.MetricUtilities; -import net.jxta.peer.PeerID; - -import java.util.Enumeration; -import java.util.Hashtable; - - -/** - * Transport Meter for a specific registered Transport - */ -public class TransportMeter { - public static final EndpointAddress UNKNOWN_ADDRESS = new EndpointAddress("", "", null, null); - public static final String UNKNOWN_PEER = MetricUtilities.UNKNOWN_PEERID.toString(); - private String protocol; - private EndpointAddress endpointAddress; - - private Hashtable transportBindingMeters = new Hashtable(); - private TransportMetric cumulativeMetrics; - - public TransportMeter(String protocol, EndpointAddress endpointAddress) { - this.endpointAddress = endpointAddress; - this.protocol = protocol; - cumulativeMetrics = new TransportMetric(this); - } - - public TransportMetric getCumulativeMetrics() { - return cumulativeMetrics; - } - - public TransportMetric collectMetrics() { - TransportMetric transportMetric = new TransportMetric(this); - boolean anyData = false; - - for (Enumeration e = transportBindingMeters.elements(); e.hasMoreElements();) { - TransportBindingMeter transportBindingMeter = e.nextElement(); - TransportBindingMetric transportBindingMetric = transportBindingMeter.collectMetrics(); - - if (transportBindingMetric != null) { - transportMetric.addTransportBindingMetric(transportBindingMetric); - anyData = true; - } - } - - if (anyData) { - return transportMetric; - } else { - return null; - } - } - - /** - * Get a specific Binding Meter corresponding to a connection for this transport - * - * @param peerIdString PeerID of destination - * @param destinationAddress Destination Address of connected peer transport - * @return The Binding Meter for tracking this connection - */ - public synchronized TransportBindingMeter getTransportBindingMeter(String peerIdString, EndpointAddress destinationAddress) { - PeerID peerID = MetricUtilities.getPeerIdFromString(peerIdString); - - return getTransportBindingMeter(peerID, destinationAddress); - } - - /** - * Get a specific Binding Meter corresponding to a connection for this transport - * - * @param peerID destination PeerID - * @param destinationAddress Destination Address of connected peer transport - * @return The Binding Meter for tracking this connection - */ - public synchronized TransportBindingMeter getTransportBindingMeter(PeerID peerID, EndpointAddress destinationAddress) { - destinationAddress = new EndpointAddress(destinationAddress, null, null); - - TransportBindingMeter transportBindingMeter = transportBindingMeters.get(destinationAddress); - - if (transportBindingMeter == null) { - transportBindingMeter = new TransportBindingMeter(peerID, destinationAddress); - transportBindingMeters.put(destinationAddress, transportBindingMeter); - cumulativeMetrics.addTransportBindingMetric(transportBindingMeter.getCumulativeMetrics()); - } else { - transportBindingMeter.setPeerID(peerID); - } - - return transportBindingMeter; - } - - public Enumeration getTransportBindingMeters() { - return transportBindingMeters.elements(); - } - - public int getTransportBindingCount() { - return transportBindingMeters.size(); - } - - public String getProtocol() { - return protocol; - } - - public EndpointAddress getEndpointAddress() { - return endpointAddress; - } - - @Override - public String toString() { - return "TransportMeter(" + endpointAddress + ")"; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportMeterBuildSettings.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportMeterBuildSettings.java deleted file mode 100644 index 1d09ff67..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportMeterBuildSettings.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * The Sun Project JXTA(TM) Software License - * - * Copyright (c) 2001-2006 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: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at https://jxta.dev.java.net. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * https://jxta.dev.java.net/ - * - * This license is based on the BSD license adopted by the Apache Foundation. - * - */ - - -/* **** THIS IS A GENERATED FILE. DO NOT EDIT. **** */ - -package net.jxta.impl.endpoint.transportMeter; - -import net.jxta.impl.meter.*; - -public interface TransportMeterBuildSettings extends MeterBuildSettings { - public static final boolean TRANSPORT_METERING = ConditionalTransportMeterBuildSettings.isRuntimeMetering(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportMetric.java deleted file mode 100644 index 3e8b0275..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportMetric.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.transportMeter; - - -import net.jxta.endpoint.EndpointAddress; - -import net.jxta.util.documentSerializable.DocumentSerializable; -import net.jxta.util.documentSerializable.DocumentSerializableUtilities; -import net.jxta.util.documentSerializable.DocumentSerializationException; -import net.jxta.document.Element; -import net.jxta.document.TextElement; - -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; - - -/** - * The Metric for a single Transport - **/ -public class TransportMetric implements DocumentSerializable { - private String protocol; - private EndpointAddress endpointAddress; - private HashMap transportBindingMetrics = new HashMap(); - - public TransportMetric(TransportMeter transportMeter) { - this.endpointAddress = transportMeter.getEndpointAddress(); - this.protocol = transportMeter.getProtocol(); - } - - public TransportMetric() {} - - public TransportMetric(TransportMetric prototype) { - this.endpointAddress = prototype.endpointAddress; - this.protocol = prototype.protocol; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof TransportMetric) { - TransportMetric other = (TransportMetric) obj; - - return protocol.equals(other.protocol) && endpointAddress.equals(other.endpointAddress); - } else { - return false; - } - } - - @Override - public int hashCode() { - return endpointAddress.hashCode(); - } - - public EndpointAddress getEndpointAddress() { - return endpointAddress; - } - - public String getProtocol() { - return protocol; - } - - public synchronized void addTransportBindingMetric(TransportBindingMetric transportBindingMetric) { - transportBindingMetrics.put(transportBindingMetric.getEndpointAddress(), transportBindingMetric); - } - - public TransportBindingMetric getTransportBindingMetric(EndpointAddress endpointAddress) { - return transportBindingMetrics.get(endpointAddress); - } - - public TransportBindingMetric getTransportBindingMetric(TransportBindingMetric prototype) { - return getTransportBindingMetric(prototype.getEndpointAddress()); - } - - public Iterator getTransportBindingMetrics() { - return transportBindingMetrics.values().iterator(); - } - - public int getTransportBindingMetricsCount() { - return transportBindingMetrics.size(); - } - - public void serializeTo(Element element) throws DocumentSerializationException { - DocumentSerializableUtilities.addString(element, "endpointAddress", endpointAddress.toString()); - DocumentSerializableUtilities.addString(element, "protocol", protocol); - - for (Iterator i = getTransportBindingMetrics(); i.hasNext();) { - TransportBindingMetric transportBindingMetric = i.next(); - - DocumentSerializableUtilities.addDocumentSerializable(element, "binding", transportBindingMetric); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("endpointAddress")) { - String endpointAddressString = DocumentSerializableUtilities.getString(childElement); - - endpointAddress = new EndpointAddress(endpointAddressString); - } else if (tagName.equals("protocol")) { - protocol = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("binding")) { - TransportBindingMetric transportBindingMetric = (TransportBindingMetric) DocumentSerializableUtilities.getDocumentSerializable( - childElement, TransportBindingMetric.class); - - transportBindingMetrics.put(transportBindingMetric.getEndpointAddress(), transportBindingMetric); - } - } - } - - void mergeMetrics(TransportMetric otherTransportMetric) { - for (Iterator i = otherTransportMetric.getTransportBindingMetrics(); i.hasNext();) { - TransportBindingMetric otherTransportBindingMetric = i.next(); - TransportBindingMetric transportBindingMetric = getTransportBindingMetric( - otherTransportBindingMetric.getEndpointAddress()); - - if (transportBindingMetric == null) { - transportBindingMetric = new TransportBindingMetric(otherTransportBindingMetric); - addTransportBindingMetric(transportBindingMetric); - } - - transportBindingMetric.mergeMetrics(otherTransportBindingMetric); - } - - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportServiceMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportServiceMetric.java deleted file mode 100644 index 0cb94418..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportServiceMetric.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.transportMeter; - - -import net.jxta.document.Element; -import net.jxta.document.TextElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.id.IDFactory; -import net.jxta.meter.MonitorResources; -import net.jxta.meter.ServiceMetric; -import net.jxta.platform.ModuleClassID; -import net.jxta.util.documentSerializable.DocumentSerializableUtilities; -import net.jxta.util.documentSerializable.DocumentSerializationException; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedList; - - -/** - * The Service Monitor Metric for the Transport Services - */ -public class TransportServiceMetric implements ServiceMetric { - private LinkedList transportMetrics = new LinkedList(); - private ModuleClassID moduleClassID = MonitorResources.transportServiceMonitorClassID; - - public TransportServiceMetric() {} - - /** - * {@inheritDoc} - */ - public void init(ModuleClassID moduleClassID) { - this.moduleClassID = moduleClassID; - } - - /** - * {@inheritDoc} - */ - public ModuleClassID getModuleClassID() { - return moduleClassID; - } - - /** - * Append a Transport Metric - * @param transportMetric metric to add - */ - public void addTransportMetric(TransportMetric transportMetric) { - transportMetrics.add(transportMetric); - } - - /** - * Get all Transport Metrics - * @return iterator of all transport metrics - */ - public Iterator getTransportMetrics() { - return transportMetrics.iterator(); - } - - /** - * Get the Transport Metric for a specific Transport Type - * @param protocol protocol name - * @param endpointAddress address - * @return a Transport Metric for a specific Transport Type - */ - public TransportMetric getTransportMetric(String protocol, EndpointAddress endpointAddress) { - for (TransportMetric transportMetric : transportMetrics) { - if (protocol.equals(transportMetric.getProtocol()) && endpointAddress.equals(transportMetric.getEndpointAddress())) { - return transportMetric; - } - } - - return null; - } - - /** - * Get the Transport Metric for a specific Transport Type - * - * @param prototype a similar Transport metric object (ie same protocol/endpointAddress) - * @see #getTransportMetric(String, EndpointAddress) - * @return a Transport Metric for a specific Transport Type - */ - public TransportMetric getTransportMetric(TransportMetric prototype) { - return getTransportMetric(prototype.getProtocol(), prototype.getEndpointAddress()); - } - - /** - * {@inheritDoc} - */ - public void serializeTo(Element element) throws DocumentSerializationException { - for (TransportMetric transportMetric : transportMetrics) { - DocumentSerializableUtilities.addDocumentSerializable(element, "transportMetric", transportMetric); - } - if (moduleClassID != null) { - DocumentSerializableUtilities.addString(element, "moduleClassID", moduleClassID.toString()); - } - } - - /** - * {@inheritDoc} - */ - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("transportMetric")) { - TransportMetric transportMetric = (TransportMetric) DocumentSerializableUtilities.getDocumentSerializable( - childElement, TransportMetric.class); - - transportMetrics.add(transportMetric); - } - if (tagName.equals("moduleClassID")) { - try { - moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI(DocumentSerializableUtilities.getString(childElement))); - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Can't read moduleClassID", jex); - } - } - } - } - - /** - * Make a shallow copy of this metric only including the portions designated in the Filter - *

            Note: since this is a shallow copy it is dangerous to modify the submetrics - * - * @param transportServiceMonitorFilter Filter designates constituant parts to be included - * @return a copy of this metric with references to the designated parts - */ - public TransportServiceMetric shallowCopy(TransportServiceMonitorFilter transportServiceMonitorFilter) { - TransportServiceMetric serviceMetric = new TransportServiceMetric(); - - serviceMetric.moduleClassID = moduleClassID; - - for (Iterator i = getTransportMetrics(); i.hasNext();) { - TransportMetric transportMetric = i.next(); - String protocol = transportMetric.getProtocol(); - - if (transportServiceMonitorFilter.hasTransport(protocol)) { - serviceMetric.addTransportMetric(transportMetric); - } - } - - return serviceMetric; - } - - /** - * {@inheritDoc} - */ - public void mergeMetrics(ServiceMetric serviceMetric) { - mergeMetrics(serviceMetric, null); - } - - /** - * - * @param serviceMetric - * @param transportServiceMonitorFilter - */ - public void mergeMetrics(ServiceMetric serviceMetric, TransportServiceMonitorFilter transportServiceMonitorFilter) { - TransportServiceMetric otherTransportServiceMetric = (TransportServiceMetric) serviceMetric; - - for (Iterator i = otherTransportServiceMetric.getTransportMetrics(); i.hasNext();) { - TransportMetric otherTransportMetric = i.next(); - String protocol = otherTransportMetric.getProtocol(); - - if ((transportServiceMonitorFilter == null) || transportServiceMonitorFilter.hasTransport(protocol)) { - TransportMetric transportMetric = getTransportMetric(otherTransportMetric.getProtocol() - , - otherTransportMetric.getEndpointAddress()); - - if (transportMetric == null) { - transportMetric = new TransportMetric(otherTransportMetric); - addTransportMetric(transportMetric); - } - - transportMetric.mergeMetrics(otherTransportMetric); - } - } - } - - /** - * Make a deep copy of this metric only including the portions designated in the Filter - * The resulting metric is Safe to modify without danger to the underlying Monitor Metrics - * - * @param transportServiceMonitorFilter Filter designates constituant parts to be included - * @return a copy of this metric with references to the designated parts - */ - public TransportServiceMetric deepCopy(TransportServiceMonitorFilter transportServiceMonitorFilter) { - TransportServiceMetric serviceMetric = new TransportServiceMetric(); - - serviceMetric.moduleClassID = moduleClassID; - - serviceMetric.mergeMetrics(this, transportServiceMonitorFilter); - return serviceMetric; - } - - /** - * {@inheritDoc} - */ - public void diffMetrics(ServiceMetric otherOne) { - throw new RuntimeException("Not Supported"); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportServiceMonitor.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportServiceMonitor.java deleted file mode 100644 index 4c790c2a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportServiceMonitor.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.transportMeter; - - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.impl.meter.GenericServiceMonitor; -import net.jxta.meter.ServiceMetric; -import net.jxta.meter.ServiceMonitorFilter; - -import java.util.LinkedList; - - -/** - * The Service Monitor Metric for the Transport Services - *

            Each Transport will register with this to create their own TransportMeter - */ -public class TransportServiceMonitor extends GenericServiceMonitor { - private LinkedList transportMeters = new LinkedList(); - private TransportServiceMetric cumulativeTransportServiceMetric; - - public TransportServiceMonitor() {} - - /** - * {@inheritDoc} - */ - @Override - protected void init() { - cumulativeTransportServiceMetric = (TransportServiceMetric) getCumulativeServiceMetric(); - } - - /** - * Create a service TransportMeter for a registerd Transport Type - * - * @param protocol protocol identifier - * @param sourceAddressString source address string - * @return a TransportMeter - * @deprecated use #createTransportMeter(String, EndpointAddress) - */ - @Deprecated - public synchronized TransportMeter createTransportMeter(String protocol, String sourceAddressString) { - EndpointAddress endpointAddress = new EndpointAddress(sourceAddressString); - - return createTransportMeter(protocol, endpointAddress); - } - - /** - * Create a service TransportMeter for a registerd Transport Type - * - * @param protocol Descriptive name of protocol - * @param endpointAddress The common public address for this transport - * @return Transport Meter for this transport - */ - public synchronized TransportMeter createTransportMeter(String protocol, EndpointAddress endpointAddress) { - endpointAddress = new EndpointAddress(endpointAddress, null, null); - - for (TransportMeter transportMeter : transportMeters) { - if (transportMeter.getProtocol().equals(protocol) && transportMeter.getEndpointAddress().equals(endpointAddress)) { - return transportMeter; - } - } - - TransportMeter transportMeter = new TransportMeter(protocol, endpointAddress); - - transportMeters.add(transportMeter); - cumulativeTransportServiceMetric.addTransportMetric(transportMeter.getCumulativeMetrics()); - return transportMeter; - } - - /** - * {@inheritDoc} - */ - @Override - protected ServiceMetric collectServiceMetrics() { - TransportServiceMetric transportServiceMetric = (TransportServiceMetric) createServiceMetric(); - - boolean anyData = false; - - for (TransportMeter transportMeter : transportMeters) { - TransportMetric transportMetric = transportMeter.collectMetrics(); - - if (transportMetric != null) { - transportServiceMetric.addTransportMetric(transportMetric); - anyData = true; - } - } - - if (anyData) { - return transportServiceMetric; - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - @Override - public ServiceMetric getServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime, int pulseIndex, long reportRate) { - int deltaReportRateIndex = monitorManager.getReportRateIndex(reportRate); - TransportServiceMetric origServiceMetric = (TransportServiceMetric) deltaServiceMetrics[deltaReportRateIndex]; - - if (origServiceMetric == null) { - return null; - } - - TransportServiceMonitorFilter transportServiceMonitorFilter = (TransportServiceMonitorFilter) serviceMonitorFilter; - - return origServiceMetric.shallowCopy(transportServiceMonitorFilter); - } - - /** - * {@inheritDoc} - */ - @Override - public ServiceMetric getCumulativeServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime) { - TransportServiceMetric origServiceMetric = (TransportServiceMetric) cumulativeServiceMetric; - - TransportServiceMonitorFilter transportServiceMonitorFilter = (TransportServiceMonitorFilter) serviceMonitorFilter; - - return origServiceMetric.deepCopy(transportServiceMonitorFilter); - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportServiceMonitorFilter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportServiceMonitorFilter.java deleted file mode 100644 index ed5f0f4f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/endpoint/transportMeter/TransportServiceMonitorFilter.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.endpoint.transportMeter; - - -import net.jxta.document.Element; -import net.jxta.document.TextElement; -import net.jxta.id.IDFactory; -import net.jxta.meter.MonitorResources; -import net.jxta.meter.ServiceMonitorFilter; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.util.documentSerializable.DocumentSerializableUtilities; -import net.jxta.util.documentSerializable.DocumentSerializationException; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.LinkedList; - - -public class TransportServiceMonitorFilter implements ServiceMonitorFilter { - private ModuleClassID moduleClassID = MonitorResources.transportServiceMonitorClassID; - private LinkedList includedTransports = new LinkedList(); - private boolean includeAllTransports = true; - - public TransportServiceMonitorFilter() {} - - public void init(ModuleClassID moduleClassID) { - this.moduleClassID = moduleClassID; - } - - public ModuleClassID getModuleClassID() { - return moduleClassID; - } - - public void removeAllTransports() { - includedTransports.clear(); - includeAllTransports = false; - } - - public void includeAllTransports(boolean includeAllTransports) { - this.includeAllTransports = includeAllTransports; - } - - public void includeTransport(String protocol) { - includedTransports.add(protocol); - } - - public boolean hasTransport(String protocol) { - if (includeAllTransports) { - return true; - } - - for (String includedTransport : includedTransports) { - if (includedTransport.equals(protocol)) { - return true; - } - } - return false; - } - - public void includeTransport(ModuleSpecID transportModuleClassID, String subProtocol) {// todo: how is this used??? - } - - public void serializeTo(Element element) throws DocumentSerializationException { - DocumentSerializableUtilities.addString(element, "moduleClassID", moduleClassID.toString()); - - DocumentSerializableUtilities.addBoolean(element, "includeAllTransports", includeAllTransports); - - for (String includedTransport : includedTransports) { - DocumentSerializableUtilities.addString(element, "includedTransport", includedTransport); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("moduleClassID")) { - try { - moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI(DocumentSerializableUtilities.getString(childElement))); - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Can't read moduleClassID", jex); - } - } - if (tagName.equals("includedTransport")) { - String includedTransport = DocumentSerializableUtilities.getString(childElement); - - includedTransports.add(includedTransport); - } - if (tagName.equals("includeAllTransports")) { - includeAllTransports = DocumentSerializableUtilities.getBoolean(childElement); - } - } - } - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/CodatID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/CodatID.java deleted file mode 100644 index d1d0ceb5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/CodatID.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.CBID; - - -import net.jxta.impl.id.UUID.IDBytes; -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.id.UUID.UUIDFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.ProviderException; -import java.util.logging.Logger; - - -/** - * An implementation of the {@link net.jxta.codat.CodatID} ID Type. - */ -public class CodatID extends net.jxta.impl.id.UUID.CodatID { - - /** - * Log4J Logger - */ - private static final transient Logger LOG = Logger.getLogger(CodatID.class.getName()); - - /** - * Internal constructor - */ - protected CodatID() { - super(); - } - - /** - * Intializes contents from provided bytes. - * - * @param id the ID data - */ - protected CodatID(IDBytes id) { - super(id); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newCodatID(net.jxta.peergroup.PeerGroupID)}. - * - * @param groupID the GroupID - */ - public CodatID(PeerGroupID groupID) { - super(groupID.getUUID(), UUIDFactory.newUUID()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newCodatID(net.jxta.peergroup.PeerGroupID,byte[])}. - * - * @param groupID the GroupID - * @param seed the seed - */ - public CodatID(PeerGroupID groupID, byte[] seed) { - this(); - - UUID groupCBID = groupID.getUUID(); - - id.longIntoBytes(CodatID.groupIdOffset, groupCBID.getMostSignificantBits()); - id.longIntoBytes(CodatID.groupIdOffset + 8, groupCBID.getLeastSignificantBits()); - - MessageDigest digester = null; - - try { - digester = MessageDigest.getInstance("SHA-1"); - } catch (NoSuchAlgorithmException caught) { - digester = null; - } - - if (digester == null) { - throw new ProviderException("SHA1 digest algorithm not found"); - } - - byte[] digest = digester.digest(seed); - - // we keep only the 128 most significant bits - byte[] buf16 = new byte[16]; - - System.arraycopy(digest, 0, buf16, 0, 16); - - UUID peerCBID = UUIDFactory.newUUID(buf16); - - id.longIntoBytes(CodatID.idOffset, peerCBID.getMostSignificantBits()); - id.longIntoBytes(CodatID.idOffset + 8, peerCBID.getLeastSignificantBits()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newCodatID(net.jxta.peergroup.PeerGroupID,InputStream)}. - * - * @param groupID the GroupID - * @param in the input stream - * @throws IOException if an io error occurs - */ - public CodatID(PeerGroupID groupID, InputStream in) throws IOException { - super(groupID, in); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newCodatID(net.jxta.peergroup.PeerGroupID,InputStream)}. - * - * @param groupID the GroupID - * @param seed the seed - * @param in the input stream - * @throws IOException if an io error occurs - */ - public CodatID(PeerGroupID groupID, byte[] seed, InputStream in) throws IOException { - this(groupID, seed); - - setHash(in); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.id.ID getPeerGroupID() { - UUID groupCBID = new UUID(id.bytesIntoLong(CodatID.groupIdOffset), id.bytesIntoLong(CodatID.groupIdOffset + 8)); - - PeerGroupID groupID = new PeerGroupID(groupCBID); - - // convert to the generic world PGID as necessary - return IDFormat.translateToWellKnown(groupID); - } - - /** - * Returns the UUID associated with this CodatID. - * - * @return The UUID associated with this CodatID. - */ - public UUID getUUID() { - return new UUID(id.bytesIntoLong(CodatID.idOffset), id.bytesIntoLong(CodatID.idOffset + 8)); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/IDFormat.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/IDFormat.java deleted file mode 100644 index a87ef04d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/IDFormat.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.id.CBID; - - -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.id.UUID.UUID; - -import java.util.logging.Logger; - - -/** - * A general purpose JXTA ID Format implementing all of the six standard ID - * Types. It was originally created for the Java 2 SE reference implementation. - * The 'cbid' format uses values generated from secure hash functions as the - * mechanism for generating canonical values for the ids it provides. - * - * @see net.jxta.id.ID - * @see JXTA Protocols Specification : IDs - */ -public class IDFormat extends net.jxta.impl.id.UUID.IDFormat { - - /** - * Log4J Logger - */ - private static final transient Logger LOG = Logger.getLogger(IDFormat.class.getName()); - - /** - * Our local version of the world Peer Group ID. We need this for cases - * where we have to make ids which are in the world peer group. We only - * use this ID for those cases and never return this ID. - */ - static final PeerGroupID worldPeerGroupID = new PeerGroupID(new UUID(0x5961626164616261L, 0x4A78746150325033L)); // YabadabaJXTAP2P! - - /** - * Our local version of the net Peer Group ID. We need this for cases - * where we have to make ids which are in the net peer group. We only - * use this ID for those cases and never return this ID. - */ - static final PeerGroupID defaultNetPeerGroupID = new PeerGroupID(new UUID(0x5961626164616261L, 0x4E50472050325033L)); // YabadabaNPG P2P! - - /** - * This table maps our local private versions of the well known ids to the - * globally known version. - */ - private final static Object[][] wellKnownIDs = { - { net.jxta.peergroup.PeerGroupID.worldPeerGroupID, worldPeerGroupID} - , - { net.jxta.peergroup.PeerGroupID.defaultNetPeerGroupID, defaultNetPeerGroupID} - }; - - /** - * The instantiator for this ID Format which is used by the IDFactory. - */ - public static final IDFactory.URIInstantiator INSTANTIATOR = new Instantiator(); - - /** - * This class cannot be instantiated. - */ - protected IDFormat() {} - - /** - * Translate from well known ID to our locally encoded versions. - * - * @param input the id to be translated. - * @return the translated ID or the input ID if no translation was needed. - */ - static ID translateFromWellKnown(ID input) { - for (Object[] wellKnownID : wellKnownIDs) { - ID aWellKnown = (ID) wellKnownID[0]; - - if (aWellKnown.equals(input)) { - return (ID) wellKnownID[1]; - } - } - - return input; - } - - /** - * Translate from locally encoded versions to the well known versions. - * - * @param input the id to be translated. - * @return the translated ID or the input ID if no translation was needed. - */ - static ID translateToWellKnown(ID input) { - for (Object[] wellKnownID : wellKnownIDs) { - ID aLocalEncoding = (ID) wellKnownID[1]; - - if (aLocalEncoding.equals(input)) { - return (ID) wellKnownID[0]; - } - } - - return input; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/Instantiator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/Instantiator.java deleted file mode 100644 index a1603cc9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/Instantiator.java +++ /dev/null @@ -1,445 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.CBID; - - -import net.jxta.impl.id.UUID.IDBytes; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.UnknownServiceException; - - -/** - * The instantiator for the CBID ID Format. - *

            - *

            For "seed" variant constructors, the "seed" must be a certificate. - */ -public class Instantiator implements net.jxta.id.IDFactory.URIInstantiator { - - /** - * Our ID Format - */ - final static String CBIDEncoded = "cbid"; - - /** - * {@inheritDoc} - */ - public String getSupportedIDFormat() { - return CBIDEncoded; - } - - /** - * {@inheritDoc} - */ - public net.jxta.id.ID fromURL(URL source) throws MalformedURLException, UnknownServiceException { - - // check the protocol - if (!net.jxta.id.ID.URIEncodingName.equalsIgnoreCase(source.getProtocol())) { - throw new UnknownServiceException("URI protocol type was not as expected."); - } - - String encoded = source.getFile(); - - int colonAt = encoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new UnknownServiceException("URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(encoded.substring(0, colonAt))) { - throw new UnknownServiceException("URN namespace was not as expected."); - } - - // skip the namespace portion and the colon - encoded = encoded.substring(colonAt + 1); - - int dashAt = encoded.indexOf('-'); - - // there's a dash, right? - if (-1 == dashAt) { - throw new UnknownServiceException("URN Encodingtype was missing."); - } - - if (!encoded.substring(0, dashAt).equals(getSupportedIDFormat())) { - throw new UnknownServiceException("JXTA ID Format was not as expected."); - } - - // skip the dash - encoded = encoded.substring(dashAt + 1); - - // check that the length is even - if (0 != (encoded.length() % 2)) { - throw new MalformedURLException("URN contains an odd number of chars"); - } - - // check that the length is long enough - if (encoded.length() < 2) { - throw new MalformedURLException("URN does not contain enough chars"); - } - - // check that id is short enough - if (IDFormat.IdByteArraySize < (encoded.length() % 2)) { - throw new MalformedURLException("URN contains too many chars"); - } - - net.jxta.id.ID result = null; - IDBytes id = new IDBytes(); - - try { - // do the primary portion. - for (int eachByte = 0; eachByte < ((encoded.length() / 2) - IDFormat.flagsSize); eachByte++) { - int index = eachByte * 2; - String twoChars = encoded.substring(index, index + 2); - - id.bytes[eachByte] = (byte) Integer.parseInt(twoChars, 16); - } - - // do the flags - for (int eachByte = IDFormat.flagsOffset; eachByte < IDFormat.IdByteArraySize; eachByte++) { - int index = encoded.length() - (IDFormat.IdByteArraySize - eachByte) * 2; - String twoChars = encoded.substring(index, index + 2); - - id.bytes[eachByte] = (byte) Integer.parseInt(twoChars, 16); - } - } catch (NumberFormatException caught) { - throw new MalformedURLException("Invalid Character in JXTA URI"); - } - - switch (id.bytes[IDFormat.flagsOffset + IDFormat.flagsIdTypeOffset]) { - case IDFormat.flagCodatID: - result = new CodatID(id); - break; - - case IDFormat.flagPeerGroupID: - result = new PeerGroupID(id); - result = (PeerGroupID) IDFormat.translateToWellKnown(result); - break; - - case IDFormat.flagPeerID: - result = new PeerID(id); - break; - - case IDFormat.flagPipeID: - result = new PipeID(id); - break; - - case IDFormat.flagModuleClassID: - result = new ModuleClassID(id); - break; - - case IDFormat.flagModuleSpecID: - result = new ModuleSpecID(id); - break; - - default: - throw new MalformedURLException("JXTA ID Type not recognized"); - } - - return result; - } - - /** - * {@inheritDoc} - */ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new CodatID(peerGroupID); - } - - /** - * {@inheritDoc} - */ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new CodatID(peerGroupID, seed); - } - - /** - * {@inheritDoc} - */ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID, InputStream in) throws IOException { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new CodatID(peerGroupID, in); - } - - /** - * {@inheritDoc} - */ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed, InputStream in) throws IOException { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new CodatID(peerGroupID, seed, in); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID() { - return new PeerGroupID(); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(byte[] seed) { - return new PeerGroupID(seed); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(net.jxta.peergroup.PeerGroupID parent) { - return new PeerGroupID(); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(net.jxta.peergroup.PeerGroupID parent, byte[] seed) { - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(parent); - - return new PeerGroupID(parentGroupID, seed); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peer.PeerID newPeerID(net.jxta.peergroup.PeerGroupID groupID) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - throw new UnsupportedOperationException("Must provide a cert as seed to generate a peer id."); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peer.PeerID newPeerID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new PeerID(peerGroupID, seed); - } - - /** - * {@inheritDoc} - */ - public net.jxta.pipe.PipeID newPipeID(net.jxta.peergroup.PeerGroupID groupID) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new PipeID(peerGroupID); - } - - /** - * {@inheritDoc} - */ - public net.jxta.pipe.PipeID newPipeID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new PipeID(peerGroupID, seed); - } - - /** - * {@inheritDoc} - */ - public net.jxta.platform.ModuleClassID newModuleClassID() { - return new ModuleClassID(); - } - - /** - * {@inheritDoc} - */ - public net.jxta.platform.ModuleClassID newModuleClassID(net.jxta.platform.ModuleClassID classID) { - return new ModuleClassID((ModuleClassID) classID); - } - - /** - * {@inheritDoc} - */ - public net.jxta.platform.ModuleSpecID newModuleSpecID(net.jxta.platform.ModuleClassID classID) { - return new ModuleSpecID((ModuleClassID) classID); - } - - /** - * {@inheritDoc} - */ - public net.jxta.id.ID fromURI(URI source) throws URISyntaxException { - - // check the protocol - if (!net.jxta.id.ID.URIEncodingName.equalsIgnoreCase(source.getScheme())) { - throw new URISyntaxException(source.toString(), "URI scheme was not as expected."); - } - - String decoded = source.getSchemeSpecificPart(); - - int colonAt = decoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new URISyntaxException(source.toString(), "URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(decoded.substring(0, colonAt))) { - throw new URISyntaxException(source.toString() - , - "URN namespace was not as expected. (" + net.jxta.id.ID.URNNamespace + "!=" + decoded.substring(0, colonAt) - + ")"); - } - - // skip the namespace portion and the colon - decoded = decoded.substring(colonAt + 1); - - return fromURNNamespaceSpecificPart(decoded); - } - - /** - * {@inheritDoc} - */ - public net.jxta.id.ID fromURNNamespaceSpecificPart(String source) throws URISyntaxException { - int dashAt = source.indexOf('-'); - - // there's a dash, right? - if (-1 == dashAt) { - throw new URISyntaxException(source, "URN Encodingtype was missing."); - } - - if (!source.substring(0, dashAt).equals(getSupportedIDFormat())) { - throw new URISyntaxException(source, "JXTA ID Format was not as expected."); - } - - // skip the dash - source = source.substring(dashAt + 1); - - // check that the length is even - if (0 != (source.length() % 2)) { - throw new URISyntaxException(source, "URN contains an odd number of chars"); - } - - // check that the length is long enough - if (source.length() < 2) { - throw new URISyntaxException(source, "URN does not contain enough chars"); - } - - // check that id is short enough - if (IDFormat.IdByteArraySize < (source.length() % 2)) { - throw new URISyntaxException(source, "URN contains too many chars"); - } - - net.jxta.id.ID result = null; - IDBytes id = new IDBytes(); - - try { - // do the primary portion. - for (int eachByte = 0; eachByte < ((source.length() / 2) - IDFormat.flagsSize); eachByte++) { - int index = eachByte * 2; - String twoChars = source.substring(index, index + 2); - - id.bytes[eachByte] = (byte) Integer.parseInt(twoChars, 16); - } - - // do the flags - for (int eachByte = IDFormat.flagsOffset; eachByte < IDFormat.IdByteArraySize; eachByte++) { - int index = source.length() - (IDFormat.IdByteArraySize - eachByte) * 2; - String twoChars = source.substring(index, index + 2); - - id.bytes[eachByte] = (byte) Integer.parseInt(twoChars, 16); - } - } catch (NumberFormatException caught) { - throw new URISyntaxException(source, "Invalid Character in JXTA URI"); - } - - switch (id.bytes[IDFormat.flagsOffset + IDFormat.flagsIdTypeOffset]) { - case IDFormat.flagCodatID: - result = new CodatID(id); - break; - - case IDFormat.flagPeerGroupID: - result = new PeerGroupID(id); - result = (PeerGroupID) IDFormat.translateToWellKnown(result); - break; - - case IDFormat.flagPeerID: - result = new PeerID(id); - break; - - case IDFormat.flagPipeID: - result = new PipeID(id); - break; - - case IDFormat.flagModuleClassID: - result = new ModuleClassID(id); - break; - - case IDFormat.flagModuleSpecID: - result = new ModuleSpecID(id); - break; - - default: - throw new URISyntaxException(source, "JXTA ID Type not recognized"); - } - return result; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/ModuleClassID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/ModuleClassID.java deleted file mode 100644 index bd11b932..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/ModuleClassID.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.CBID; - - -import net.jxta.impl.id.UUID.IDBytes; -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.id.UUID.UUIDFactory; - -import java.util.logging.Logger; - - -/** - * An implementation of the {@link net.jxta.platform.ModuleClassID} ID Type. - */ -public final class ModuleClassID extends net.jxta.impl.id.UUID.ModuleClassID { - - /** - * Log4J categorgy - */ - private static final transient Logger LOG = Logger.getLogger(ModuleClassID.class.getName()); - - /** - * Constructor. - * Intializes contents from provided ID. - * - * @param id the ID data - */ - protected ModuleClassID(IDBytes id) { - super(id); - } - - /** - * Constructor. - * Creates a ModuleClassID in a given class, with a given class unique id. - * A UUID of a class and another UUID are provided. - * - * @param classUUID the class to which this will belong. - * @param roleUUID the unique id of this role in that class. - */ - protected ModuleClassID(UUID classUUID, UUID roleUUID) { - super(classUUID, roleUUID); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newModuleClassID()}. - *

            - * A new class UUID is created. The role ID is left null. This is the - * only way to create a new class without supplying a new UUID explicitly. - *

            - * Note that a null role is just as valid as any other, it just has a - * shorter string representation. So it is not mandatory to create a new - * role in a new class. - */ - public ModuleClassID() { - this(UUIDFactory.newUUID(), new UUID(0L, 0L)); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newModuleClassID(net.jxta.platform.ModuleClassID)}. - * @param classID the ModuleClassID - */ - public ModuleClassID(ModuleClassID classID) { - this(classID.getClassUUID(), UUIDFactory.newUUID()); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.platform.ModuleClassID getBaseClass() { - return new ModuleClassID(getClassUUID(), new UUID(0L, 0L)); - } - - /** - * get the class' unique id - * - * @return UUID module class' unique id - */ - @Override - protected UUID getClassUUID() { - return super.getClassUUID(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/ModuleSpecID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/ModuleSpecID.java deleted file mode 100644 index 480d2dc3..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/ModuleSpecID.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.CBID; - - -import net.jxta.impl.id.UUID.IDBytes; -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.id.UUID.UUIDFactory; - -import java.util.logging.Logger; - - -/** - * An implementation of the {@link net.jxta.platform.ModuleSpecID} ID Type. - */ -public final class ModuleSpecID extends net.jxta.impl.id.UUID.ModuleSpecID { - - /** - * Log4J categorgy - */ - private static final transient Logger LOG = Logger.getLogger(ModuleSpecID.class.getName()); - - /** - * Constructor. Used only internally. - */ - protected ModuleSpecID() { - super(); - } - - /** - * Intializes contents from provided ID. - * - * @param id the ID data - */ - protected ModuleSpecID(IDBytes id) { - super(id); - } - - /** - * Creates a ModuleSpecID in a given class, with a given class unique id. - * A UUID of a class and another UUID are provided. - * - * @param classUUID the class to which this will belong. - * @param specUUID the unique id of this spec in that class. - * @since JXTA 1.0 - */ - protected ModuleSpecID(UUID classUUID, UUID specUUID) { - super(classUUID, classUUID); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newModuleSpecID(net.jxta.platform.ModuleClassID)}. - * @param classID the ModuleClassID - */ - public ModuleSpecID(ModuleClassID classID) { - this(classID.getClassUUID(), UUIDFactory.newUUID()); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.platform.ModuleClassID getBaseClass() { - return new ModuleClassID(getClassUUID(), new UUID(0L, 0L)); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/PeerGroupID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/PeerGroupID.java deleted file mode 100644 index d655ee7e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/PeerGroupID.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.CBID; - - -import net.jxta.impl.id.UUID.IDBytes; -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.id.UUID.UUIDFactory; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.ProviderException; -import java.util.logging.Logger; - - -/** - * An implementation of the {@link net.jxta.peergroup.PeerGroupID} ID Type. - */ -public class PeerGroupID extends net.jxta.impl.id.UUID.PeerGroupID { - - /** - * Log4J categorgy - */ - private static final transient Logger LOG = Logger.getLogger(PeerGroupID.class.getName()); - - /** - * Intializes contents from provided ID. - * - * @param id the ID data - */ - protected PeerGroupID(IDBytes id) { - super(id); - } - - /** - * Creates a PeerGroupID. A PeerGroupID is provided - * - * @param groupUUID the PeerGroupID to use to construct the new PeerGroupID - */ - protected PeerGroupID(UUID groupUUID) { - super(groupUUID); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerGroupID()}. - */ - public PeerGroupID() { - this(UUIDFactory.newUUID()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerGroupID(byte[])}. - * @param seed the seed - */ - public PeerGroupID(byte[] seed) { - super(); - - MessageDigest digester = null; - - try { - digester = MessageDigest.getInstance("SHA-1"); - } catch (NoSuchAlgorithmException caught) { - digester = null; - } - - if (digester == null) { - throw new ProviderException("SHA1 digest algorithm not found"); - } - - byte[] digest = digester.digest(seed); - - // we keep only the 128 most significant bits - byte[] buf16 = new byte[16]; - - System.arraycopy(digest, 0, buf16, 0, 16); - - UUID groupUUID = UUIDFactory.newUUID(buf16); - - id.longIntoBytes(PeerGroupID.groupIdOffset, groupUUID.getMostSignificantBits()); - id.longIntoBytes(PeerGroupID.groupIdOffset + 8, groupUUID.getLeastSignificantBits()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerGroupID(net.jxta.peergroup.PeerGroupID,byte[])}. - * - * @param parent Parent PeerGroupID - * @param seed the seed - */ - public PeerGroupID(PeerGroupID parent, byte[] seed) { - this(seed); - - UUID parentUUID = parent.getUUID(); - - id.longIntoBytes(PeerGroupID.parentgroupIdOffset, parentUUID.getMostSignificantBits()); - id.longIntoBytes(PeerGroupID.parentgroupIdOffset + 8, parentUUID.getLeastSignificantBits()); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.peergroup.PeerGroupID getParentPeerGroupID() { - - UUID parentUUID = new UUID(id.bytesIntoLong(PeerGroupID.parentgroupIdOffset) - , - id.bytesIntoLong(PeerGroupID.parentgroupIdOffset + 8)); - - // if zero, then there is no parent. - if ((0 == parentUUID.getMostSignificantBits()) && (0 == parentUUID.getLeastSignificantBits())) { - return null; - } - - PeerGroupID groupID = new PeerGroupID(parentUUID); - - // convert to the generic world PGID as necessary - return (net.jxta.peergroup.PeerGroupID) IDFormat.translateToWellKnown(groupID); - } - - /** - * Returns the UUID associated with this PeerGroupID. - * - * @return The UUID associated with this PeerGroupID. - */ - @Override - public UUID getUUID() { - return super.getUUID(); - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/PeerID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/PeerID.java deleted file mode 100644 index 5fdeda5b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/PeerID.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.CBID; - - -import net.jxta.impl.id.UUID.IDBytes; -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.id.UUID.UUIDFactory; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.ProviderException; -import java.util.logging.Logger; - - -/** - * An implementation of the {@link net.jxta.peer.PeerID} ID Type. - */ -public class PeerID extends net.jxta.impl.id.UUID.PeerID { - - /** - * Log4J Logger - */ - private static final transient Logger LOG = Logger.getLogger(PeerID.class.getName()); - - /** - * Used only internally. - */ - protected PeerID() { - super(); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerID(net.jxta.peergroup.PeerGroupID)}. - * - * @param groupID the PeerGroupID - */ - public PeerID(PeerGroupID groupID) { - this(groupID.getUUID(), UUIDFactory.newUUID()); - } - - /** - * Intializes contents from provided ID. - * - * @param id the ID data - */ - protected PeerID(IDBytes id) { - super(id); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerID(net.jxta.peergroup.PeerGroupID,byte[])}. - * - * @param groupID the PeerGroupID - * @param seed the seed - */ - public PeerID(PeerGroupID groupID, byte[] seed) { - this(); - - UUID groupUUID = groupID.getUUID(); - - id.longIntoBytes(PeerID.groupIdOffset, groupUUID.getMostSignificantBits()); - id.longIntoBytes(PeerID.groupIdOffset + 8, groupUUID.getLeastSignificantBits()); - - MessageDigest digester = null; - - try { - digester = MessageDigest.getInstance("SHA-1"); - } catch (NoSuchAlgorithmException caught) { - digester = null; - } - - if (digester == null) { - throw new ProviderException("SHA1 digest algorithm not found"); - } - - byte[] digest = digester.digest(seed); - - // we keep only the 128 most significant bits - byte[] buf16 = new byte[16]; - - System.arraycopy(digest, 0, buf16, 0, 16); - - UUID peerCBID = new UUID(buf16); - - id.longIntoBytes(PeerID.idOffset, peerCBID.getMostSignificantBits()); - id.longIntoBytes(PeerID.idOffset + 8, peerCBID.getLeastSignificantBits()); - } - - /** - * Creates a PeerID. A PeerGroupID is provided - * - * @param groupUUID the group to which this will belong. - * @param peerUUID id of this peer - */ - protected PeerID(UUID groupUUID, UUID peerUUID) { - super(groupUUID, peerUUID); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.id.ID getPeerGroupID() { - UUID groupCBID = new UUID(id.bytesIntoLong(PeerID.groupIdOffset), id.bytesIntoLong(PeerID.groupIdOffset + 8)); - - PeerGroupID groupID = new PeerGroupID(groupCBID); - - // convert to the generic world PGID as necessary - return IDFormat.translateToWellKnown(groupID); - } - - /** - * Returns the UUID associated with this PeerID. - * - * @return The UUID associated with this PeerID. - */ - public UUID getUUID() { - return new UUID(id.bytesIntoLong(PeerID.idOffset), id.bytesIntoLong(PeerID.idOffset + 8)); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/PipeID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/PipeID.java deleted file mode 100644 index c61fca92..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/PipeID.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.id.CBID; - - -import net.jxta.impl.id.UUID.IDBytes; -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.id.UUID.UUIDFactory; - -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.ProviderException; -import java.util.logging.Logger; - - -/** - * An implementation of the {@link net.jxta.pipe.PipeID} ID Type. - */ -public class PipeID extends net.jxta.impl.id.UUID.PipeID { - - /** - * Log4J categorgy - */ - private static final transient Logger LOG = Logger.getLogger(PipeID.class.getName()); - - /** - * Used only internally - */ - protected PipeID() { - super(); - } - - /** - * Constructor. - * Intializes contents from provided ID. - * - * @param id the ID data - */ - protected PipeID(IDBytes id) { - super(id); - } - - /** - * Creates a PipeID. A PeerGroupID is provided - * - * @param groupUUID the UUID of the group to which this will belong. - * @param idUUID the UUID which will be used for this pipe. - */ - protected PipeID(UUID groupUUID, UUID idUUID) { - super(groupUUID, idUUID); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPipeID(net.jxta.peergroup.PeerGroupID)}. - * @param groupID the PeerGroupID - */ - public PipeID(PeerGroupID groupID) { - this(groupID.getUUID(), UUIDFactory.newUUID()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPipeID(net.jxta.peergroup.PeerGroupID,byte[])}. - * @param groupID the PeerGroupID - * @param seed the seed - */ - public PipeID(PeerGroupID groupID, byte[] seed) { - this(); - - UUID groupCBID = groupID.getUUID(); - - id.longIntoBytes(PipeID.groupIdOffset, groupCBID.getMostSignificantBits()); - id.longIntoBytes(PipeID.groupIdOffset + 8, groupCBID.getLeastSignificantBits()); - - MessageDigest digester = null; - - try { - digester = MessageDigest.getInstance("SHA-1"); - } catch (NoSuchAlgorithmException caught) { - digester = null; - } - - if (digester == null) { - throw new ProviderException("SHA1 digest algorithm not found"); - } - - byte[] digest = digester.digest(seed); - - // we keep only the 128 most significant bits - byte[] buf16 = new byte[16]; - - System.arraycopy(digest, 0, buf16, 0, 16); - - UUID pipeCBID = UUIDFactory.newUUID(buf16); - - id.longIntoBytes(PipeID.idOffset, pipeCBID.getMostSignificantBits()); - id.longIntoBytes(PipeID.idOffset + 8, pipeCBID.getLeastSignificantBits()); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.id.ID getPeerGroupID() { - UUID groupCBID = new UUID(id.bytesIntoLong(PipeID.groupIdOffset), id.bytesIntoLong(PipeID.groupIdOffset + 8)); - - PeerGroupID groupID = new PeerGroupID(groupCBID); - - // convert to the generic world PGID as necessary - return IDFormat.translateToWellKnown(groupID); - } - - /** - * Returns the UUID associated with this PipeID. - * - * @return The UUID associated with this PipeID. - */ - public UUID getUUID() { - return new UUID(id.bytesIntoLong(PipeID.idOffset), id.bytesIntoLong(PipeID.idOffset + 8)); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/package.html deleted file mode 100644 index ca7cc2c2..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/CBID/package.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - The 'cbid' format is a general purpose JXTA ID Format. It implements all of - the six standard ID types. It was originally created for the Jave 2 SE - reference implementation. The 'cbid' format uses values generated from - secure hash functions as the mechanism for generating canonical values for - the ids it provides. - - @see JXTA Protocols Specification -: IDs - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/CodatID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/CodatID.java deleted file mode 100644 index c51c8bf9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/CodatID.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -import java.io.InputStream; -import java.security.MessageDigest; - -import java.io.IOException; -import java.security.ProviderException; -import java.security.NoSuchAlgorithmException; - - -/** - * An implementation of the {@link net.jxta.codat.CodatID} ID Type. - */ -public class CodatID extends net.jxta.codat.CodatID { - - /** - * size of a SHA1 hash. I would use MessageDigest.getDigestLength, but - * possible exceptions make it difficult to do. - */ - protected final static int hashSize = 20; - - /** - * Location of the group id in the byte array. - */ - protected final static int groupIdOffset = 0; - - /** - * Location of the randomly chosen portion of the id within the byte array. - */ - protected final static int idOffset = CodatID.groupIdOffset + IDFormat.uuidSize; - - /** - * Location of the hash value portion of the id within the byte array. - */ - protected final static int codatHashOffset = CodatID.idOffset + IDFormat.uuidSize; - - /** - * Location of the beginning of pad (unused space) within the byte array. - */ - protected final static int padOffset = CodatID.codatHashOffset + CodatID.hashSize; - - /** - * Size of the pad. - */ - protected final static int padSize = IDFormat.flagsOffset - CodatID.padOffset; - - /** - * The id data - */ - protected IDBytes id; - - /** - * Internal constructor - */ - protected CodatID() { - super(); - id = new IDBytes(IDFormat.flagCodatID); - } - - /** - * Initializes contents from provided bytes. - * - * @param id the ID data - */ - protected CodatID(IDBytes id) { - super(); - this.id = id; - } - - protected CodatID(UUID groupUUID, UUID idUUID) { - this(); - - id.longIntoBytes(CodatID.groupIdOffset, groupUUID.getMostSignificantBits()); - id.longIntoBytes(CodatID.groupIdOffset + 8, groupUUID.getLeastSignificantBits()); - - id.longIntoBytes(CodatID.idOffset, idUUID.getMostSignificantBits()); - id.longIntoBytes(CodatID.idOffset + 8, idUUID.getLeastSignificantBits()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newCodatID(net.jxta.peergroup.PeerGroupID)}. - */ - public CodatID(PeerGroupID groupID) { - this(groupID.getUUID(), UUIDFactory.newUUID()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newCodatID(net.jxta.peergroup.PeerGroupID,byte[])}. - */ - public CodatID(PeerGroupID groupID, byte[] seed) { - this(); - - UUID groupUUID = groupID.getUUID(); - - id.longIntoBytes(CodatID.groupIdOffset, groupUUID.getMostSignificantBits()); - id.longIntoBytes(CodatID.groupIdOffset + 8, groupUUID.getLeastSignificantBits()); - - System.arraycopy(seed, 0, id.bytes, CodatID.idOffset, Math.min(IDFormat.uuidSize, seed.length)); - - // make it a valid UUID - id.bytes[CodatID.idOffset + 6] &= 0x0f; - id.bytes[CodatID.idOffset + 6] |= 0x40; /* version 4 */ - id.bytes[CodatID.idOffset + 8] &= 0x3f; - id.bytes[CodatID.idOffset + 8] |= 0x80; /* IETF variant */ - id.bytes[CodatID.idOffset + 10] &= 0x3f; - id.bytes[CodatID.idOffset + 10] |= 0x80; /* multicast bit */ - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newCodatID(net.jxta.peergroup.PeerGroupID,InputStream)}. - */ - public CodatID(PeerGroupID groupID, InputStream in) throws IOException { - this(groupID); - - setHash(in); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newCodatID(net.jxta.peergroup.PeerGroupID,InputStream)}. - */ - public CodatID(PeerGroupID groupID, byte[] seed, InputStream in) throws IOException { - this(groupID, seed); - - setHash(in); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof CodatID) { - CodatID codatTarget = (CodatID) target; - - return id.equals(codatTarget.id); - } else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return id.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + (String) id.getUniqueValue(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.id.ID getPeerGroupID() { - UUID groupUUID = new UUID(id.bytesIntoLong(CodatID.groupIdOffset), id.bytesIntoLong(CodatID.groupIdOffset + 8)); - - PeerGroupID groupID = new PeerGroupID(groupUUID); - - // convert to the generic world PGID as necessary - return IDFormat.translateToWellKnown(groupID); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isStatic() { - for (int eachHashByte = CodatID.codatHashOffset; eachHashByte < (CodatID.padOffset); eachHashByte++) { - if (0 != id.bytes[eachHashByte]) { - return true; - } - } - - return false; - } - - /** - * Calculates the SHA-1 hash of a stream. - * - * @param in The InputStream. - */ - protected void setHash(InputStream in) throws IOException { - MessageDigest dig = null; - - try { - dig = MessageDigest.getInstance("SHA-1"); - } catch (NoSuchAlgorithmException caught) { - dig = null; - } - - if (dig == null) { - throw new ProviderException("SHA-1 digest algorithm not found"); - } - - dig.reset(); - - byte[] chunk = new byte[1024]; - - try { - do { - int read = in.read(chunk); - - if (read == -1) { - break; - } - - dig.update(chunk, 0, read); - } while (true); - } finally { - in.close(); - } - - byte[] result = dig.digest(); - - System.arraycopy(result, 0, id.bytes, CodatID.codatHashOffset, CodatID.hashSize); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/IDBytes.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/IDBytes.java deleted file mode 100644 index 0a9a647c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/IDBytes.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -import java.io.Serializable; -import java.util.Arrays; -import java.util.zip.Checksum; -import java.util.zip.CRC32; - - -/** - * Maintains the internal representation of a 'uuid' JXTA ID. - * - * @see net.jxta.id.IDFactory - * @see net.jxta.impl.id.UUID.IDFormat - * @see JXTA Protocols Specification : UUID ID Format - */ -public final class IDBytes implements Serializable { - - /** - * The bytes. - */ - public final byte[] bytes; - - /** - * The cached hash value for this object - */ - protected transient int cachedHash = 0; - - /** - * Constructs a new byte representation. This constructor initializes only - * the flag fields of the ID. - * - */ - public IDBytes() { - this.bytes = new byte[ IDFormat.IdByteArraySize ]; - } - - /** - * Constructs a new byte representation. This constructor initializes only - * the flag fields of the ID. - */ - public IDBytes(byte type) { - this(); - this.bytes[IDFormat.flagsOffset + IDFormat.flagsIdTypeOffset] = type; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof IDBytes) { - IDBytes asIDBytes = (IDBytes) target; - - return Arrays.equals(bytes, asIDBytes.bytes); - } else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = cachedHash; - - if (0 == result) { - // There is a very small chance that this - Checksum crc = new CRC32(); - - crc.update(bytes, 0, bytes.length); - - cachedHash = (int) crc.getValue(); - cachedHash = (0 == cachedHash) ? 1 : cachedHash; - - result = cachedHash; - } - - return result; - } - - /** - * Returns a string representation of the ID bytes. The bytes are encoded - * in hex ASCII format with two characters per byte. The pad bytes between - * the primary id portion and the flags field are omitted. - * - * @return String containing the unique value of this ID. - */ - @Override - public String toString() { - return getUniqueValue().toString(); - } - - /** - * Private replacement for toHexString since we need the leading 0 digits. - * Returns a char array containing byte value encoded as 2 hex chars. - * - * @param theByte a byte containing the value to be encoded. - * @return char[] containing byte value encoded as 2 hex characters. - */ - private static char[] toHexDigits(byte theByte) { - final char[] HEXDIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - char result[] = new char[2]; - - result[0] = HEXDIGITS[(theByte >>> 4) & 15]; - result[1] = HEXDIGITS[theByte & 15]; - - return result; - } - - /** - * Return an object containing the unique value of the ID. This object must - * provide implementations of toString() and hashCode() that are canonical - * and consistent from run-to-run given the same input values. Beyond - * this nothing should be assumed about the nature of this object. For some - * implementations the object returned may be the same as provided. - * - * @return Object which can provide canonical representations of the ID. - */ - public Object getUniqueValue() { - StringBuilder encoded = new StringBuilder(144); - int lastIndex; - - // find the last non-zero index. - for (lastIndex = IDFormat.flagsOffset - 1; lastIndex > 0; lastIndex--) { - if (0 != bytes[lastIndex]) { - break; - } - } - - // build the string. - for (int eachByte = 0; eachByte <= lastIndex; eachByte++) { - char[] asHex = toHexDigits(bytes[eachByte]); - - encoded.append(asHex); - } - - // append the flags field - for (int eachFlagByte = IDFormat.flagsOffset; eachFlagByte < IDFormat.IdByteArraySize; eachFlagByte++) { - char asHex[] = toHexDigits(bytes[eachFlagByte]); - - encoded.append(asHex); - } - - return encoded.toString(); - } - - /** - * Insert a long value into the byte array. The long is stored in - * big-endian order into the byte array beginning at the specified index. - * - * @param offset location within the byte array to insert. - * @param value value to be inserted. - */ - public void longIntoBytes(int offset, long value) { - if ((offset < 0) || ((offset + 8) > IDFormat.IdByteArraySize)) { - throw new IndexOutOfBoundsException("Bad offset"); - } - - for (int eachByte = 0; eachByte < 8; eachByte++) { - bytes[eachByte + offset] = (byte) (value >> ((7 - eachByte) * 8L)); - } - - cachedHash = 0; - } - - /** - * Return the long value of a portion of the byte array. The long is - * retrieved in big-endian order from the byte array at the specified - * offset. - * - * @param offset location within the byte array to extract. - * @return long value extracted from the byte array. - */ - public long bytesIntoLong(int offset) { - if ((offset < 0) || ((offset + 8) > IDFormat.IdByteArraySize)) { - throw new IndexOutOfBoundsException("Bad offset"); - } - - long result = 0L; - - for (int eachByte = 0; eachByte < 8; eachByte++) { - result |= ((long) (bytes[eachByte + offset] & 0xff)) << ((7 - eachByte) * 8L); - } - - return result; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/IDFormat.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/IDFormat.java deleted file mode 100644 index ad3b4219..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/IDFormat.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.id.ID; -import net.jxta.id.IDFactory; - - -/** - * A general purpose JXTA ID Format implementing all of the six standard ID - * Types. It was originally created for the Java 2 SE reference implementation. - * The 'uuid' format uses (IETF version 4) randomly generated UUIDs as the - * mechanism for generating canonical values for the ids it provides. - * - *

            For IDs constructed using "seed" variant constructors, the first 16 - * bytes of the seed are used literally as the UUID value. The value is masked - * to make it a valid version 4 IETF variant UUID. - * - * @see net.jxta.id.ID - * @see JXTA Protocols Specification : IDs - * @see JXTA Protocols Specification : UUID ID Format - */ -public class IDFormat { - - /** - * Log4J Logger - */ - private static final transient Logger LOG = Logger.getLogger(IDFormat.class.getName()); - - /** - * number of bytes in the byte array - */ - public final static int IdByteArraySize = 64; - - /** - * The size of a UUID in bytes - */ - public final static int uuidSize = 16; - - /** - * The size of the flags field - */ - public final static int flagsSize = 1; - - /** - * Location of the type field within the flags field - */ - public final static int flagsIdTypeOffset = IDFormat.flagsSize - 1; - - /** - * Type value for Codat - */ - public final static byte flagCodatID = 0x01; - - /** - * Type value for PeerGroup - */ - public final static byte flagPeerGroupID = 0x02; - - /** - * Type value for Peer - */ - public final static byte flagPeerID = 0x03; - - /** - * Type value for Pipe - */ - public final static byte flagPipeID = 0x04; - - /** - * Type value for ModuleClass - */ - public final static byte flagModuleClassID = 0x05; - - /** - * Type value for ModuleSpec - */ - public final static byte flagModuleSpecID = 0x06; - - /** - * Type value for CodatID - */ - public final static byte flagCodatID7 = 0x07; - - /** - * Location of ID flags within byte array. - */ - public final static int flagsOffset = IDFormat.IdByteArraySize - IDFormat.flagsSize; - - /** - * Our local version of the world Peer Group ID. We need this for cases - * where we have to make ids which are in the world peer group. We only - * use this ID for those cases and never return this ID. - */ - public static final PeerGroupID worldPeerGroupID = new PeerGroupID(new UUID(0x5961626164616261L, 0x4A78746150325033L)); // YabadabaJXTAP2P! - - /** - * Our local version of the net Peer Group ID. We need this for cases - * where we have to make ids which are in the net peer group. We only - * use this ID for those cases and never return this ID. - */ - public static final PeerGroupID defaultNetPeerGroupID = new PeerGroupID(new UUID(0x5961626164616261L, 0x4E50472050325033L)); // YabadabaNPG P2P! - - /** - * This table maps our local private versions of the well known ids to the - * globally known version. - */ - private final static Object[][] wellKnownIDs = { - { net.jxta.peergroup.PeerGroupID.worldPeerGroupID, worldPeerGroupID } - , - { net.jxta.peergroup.PeerGroupID.defaultNetPeerGroupID, defaultNetPeerGroupID } - }; - - /** - * The instantiator for this ID Format which is used by the IDFactory. - */ - public static final IDFactory.Instantiator INSTANTIATOR = new Instantiator(); - - /** - * This class cannot be instantiated. - */ - protected IDFormat() {} - - /** - * Translate from well known ID to our locally encoded versions. - * - * @param input the id to be translated. - * @return the translated ID or the input ID if no translation was needed. - */ - static ID translateFromWellKnown(ID input) { - for (int eachWellKnown = 0; eachWellKnown < wellKnownIDs.length; eachWellKnown++) { - ID aWellKnown = (ID) wellKnownIDs[eachWellKnown][0]; - - if (aWellKnown.equals(input)) { - return (ID) wellKnownIDs[eachWellKnown][1]; - } - } - - return input; - } - - /** - * Translate from locally encoded versions to the well known versions. - * - * @param input the id to be translated. - * @return the translated ID or the input ID if no translation was needed. - */ - static ID translateToWellKnown(ID input) { - for (int eachWellKnown = 0; eachWellKnown < wellKnownIDs.length; eachWellKnown++) { - ID aLocalEncoding = (ID) wellKnownIDs[eachWellKnown][1]; - - if (aLocalEncoding.equals(input)) { - return (ID) wellKnownIDs[eachWellKnown][0]; - } - } - - return input; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/Instantiator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/Instantiator.java deleted file mode 100644 index 57d2bdf3..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/Instantiator.java +++ /dev/null @@ -1,451 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -import java.io.InputStream; -import java.net.URI; -import java.net.URL; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.UnknownServiceException; -import java.net.URISyntaxException; - -import net.jxta.id.IDFactory; - - -/** - * The instantiator for the UUID ID Format. - * - *

            For "seed" variant constructors, the first 16 bytes of the seed are used - * literally as the UUID value. The value is masked to make it a valid version 4 - * IETF varient UUID. - */ -public class Instantiator implements IDFactory.URIInstantiator { - - /** - * Our ID Format - */ - final static String UUIDEncoded = "uuid"; - - /** - * {@inheritDoc} - */ - public String getSupportedIDFormat() { - return UUIDEncoded; - } - - /** - * {@inheritDoc} - */ - public net.jxta.id.ID fromURL(URL source) throws MalformedURLException, UnknownServiceException { - - // check the protocol - if (!net.jxta.id.ID.URIEncodingName.equalsIgnoreCase(source.getProtocol())) { - throw new UnknownServiceException("URI protocol type was not as expected."); - } - - String encoded = source.getFile(); - - int colonAt = encoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new UnknownServiceException("URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(encoded.substring(0, colonAt))) { - throw new UnknownServiceException("URN namespace was not as expected."); - } - - // skip the namespace portion and the colon - encoded = encoded.substring(colonAt + 1); - - int dashAt = encoded.indexOf('-'); - - // there's a dash, right? - if (-1 == dashAt) { - throw new UnknownServiceException("URN Encodingtype was missing."); - } - - if (!encoded.substring(0, dashAt).equals(getSupportedIDFormat())) { - throw new UnknownServiceException("JXTA ID Format was not as expected."); - } - - // skip the dash - encoded = encoded.substring(dashAt + 1); - - // check that the length is even - if (0 != (encoded.length() % 2)) { - throw new MalformedURLException("URN contains an odd number of chars"); - } - - // check that the length is long enough - if (encoded.length() < 2) { - throw new MalformedURLException("URN does not contain enough chars"); - } - - // check that id is short enough - if (IDFormat.IdByteArraySize < (encoded.length() % 2)) { - throw new MalformedURLException("URN contains too many chars"); - } - - net.jxta.id.ID result = null; - IDBytes id = new IDBytes(); - - try { - // do the primary portion. - for (int eachByte = 0; eachByte < ((encoded.length() / 2) - IDFormat.flagsSize); eachByte++) { - int index = eachByte * 2; - String twoChars = encoded.substring(index, index + 2); - - id.bytes[eachByte] = (byte) Integer.parseInt(twoChars, 16); - } - - // do the flags - for (int eachByte = IDFormat.flagsOffset; eachByte < IDFormat.IdByteArraySize; eachByte++) { - int index = encoded.length() - (IDFormat.IdByteArraySize - eachByte) * 2; - String twoChars = encoded.substring(index, index + 2); - - id.bytes[eachByte] = (byte) Integer.parseInt(twoChars, 16); - } - } catch (NumberFormatException caught) { - throw new MalformedURLException("Invalid Character in JXTA URI"); - } - - switch (id.bytes[IDFormat.flagsOffset + IDFormat.flagsIdTypeOffset]) { - case IDFormat.flagCodatID: - result = new CodatID(id); - break; - - case IDFormat.flagPeerGroupID: - result = new PeerGroupID(id); - result = (PeerGroupID) IDFormat.translateToWellKnown(result); - break; - - case IDFormat.flagPeerID: - result = new PeerID(id); - break; - - case IDFormat.flagPipeID: - result = new PipeID(id); - break; - - case IDFormat.flagModuleClassID: - result = new ModuleClassID(id); - break; - - case IDFormat.flagModuleSpecID: - result = new ModuleSpecID(id); - break; - - default: - throw new MalformedURLException("JXTA ID Type not recognized"); - } - - return result; - } - - /** - * {@inheritDoc} - */ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new CodatID(peerGroupID); - } - - /** - * {@inheritDoc} - */ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new CodatID(peerGroupID, seed); - } - - /** - * {@inheritDoc} - */ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID, InputStream in) throws IOException { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new CodatID(peerGroupID, in); - } - - /** - * {@inheritDoc} - */ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed, InputStream in) throws IOException { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new CodatID(peerGroupID, seed, in); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID() { - return new PeerGroupID(); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(byte[] seed) { - return new PeerGroupID(seed); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(net.jxta.peergroup.PeerGroupID parent) { - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(parent); - - return new PeerGroupID(parentGroupID); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(net.jxta.peergroup.PeerGroupID parent, byte[] seed) { - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(parent); - - return new PeerGroupID(parentGroupID, seed); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peer.PeerID newPeerID(net.jxta.peergroup.PeerGroupID groupID) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new PeerID(peerGroupID); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peer.PeerID newPeerID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new PeerID(peerGroupID, seed); - } - - /** - * {@inheritDoc} - */ - public net.jxta.pipe.PipeID newPipeID(net.jxta.peergroup.PeerGroupID groupID) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new PipeID(peerGroupID); - } - - /** - * {@inheritDoc} - */ - public net.jxta.pipe.PipeID newPipeID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new PipeID(peerGroupID, seed); - } - - /** - * {@inheritDoc} - */ - public net.jxta.platform.ModuleClassID newModuleClassID() { - return new ModuleClassID(); - } - - /** - * {@inheritDoc} - */ - public net.jxta.platform.ModuleClassID newModuleClassID(net.jxta.platform.ModuleClassID classID) { - return new ModuleClassID((ModuleClassID) classID); - } - - /** - * {@inheritDoc} - */ - public net.jxta.platform.ModuleSpecID newModuleSpecID(net.jxta.platform.ModuleClassID classID) { - return new ModuleSpecID((ModuleClassID) classID); - } - - /** - * {@inheritDoc} - */ - public net.jxta.id.ID fromURI(URI source) throws URISyntaxException { - - // check the protocol - if (!net.jxta.id.ID.URIEncodingName.equalsIgnoreCase(source.getScheme())) { - throw new URISyntaxException(source.toString(), "URI scheme was not as expected."); - } - - String decoded = source.getSchemeSpecificPart(); - - int colonAt = decoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new URISyntaxException(source.toString(), "URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(decoded.substring(0, colonAt))) { - throw new URISyntaxException(source.toString() - , - "URN namespace was not as expected. (" + net.jxta.id.ID.URNNamespace + "!=" + decoded.substring(0, colonAt) - + ")"); - } - - // skip the namespace portion and the colon - decoded = decoded.substring(colonAt + 1); - - return fromURNNamespaceSpecificPart(decoded); - } - - /** - * {@inheritDoc} - */ - public net.jxta.id.ID fromURNNamespaceSpecificPart(String source) throws URISyntaxException { - int dashAt = source.indexOf('-'); - - // there's a dash, right? - if (-1 == dashAt) { - throw new URISyntaxException(source, "URN Encodingtype was missing."); - } - - if (!source.substring(0, dashAt).equals(getSupportedIDFormat())) { - throw new URISyntaxException(source, "JXTA ID Format was not as expected."); - } - - // skip the dash - source = source.substring(dashAt + 1); - - // check that the length is even - if (0 != (source.length() % 2)) { - throw new URISyntaxException(source, "URN contains an odd number of chars"); - } - - // check that the length is long enough - if (source.length() < 2) { - throw new URISyntaxException(source, "URN does not contain enough chars"); - } - - // check that id is short enough - if (IDFormat.IdByteArraySize < (source.length() / 2)) { - throw new URISyntaxException(source, "URN contains too many chars"); - } - - net.jxta.id.ID result = null; - IDBytes id = new IDBytes(); - - try { - // do the primary portion. - for (int eachByte = 0; eachByte < ((source.length() / 2) - IDFormat.flagsSize); eachByte++) { - int index = eachByte * 2; - String twoChars = source.substring(index, index + 2); - - id.bytes[eachByte] = (byte) Integer.parseInt(twoChars, 16); - } - - // do the flags - for (int eachByte = IDFormat.flagsOffset; eachByte < IDFormat.IdByteArraySize; eachByte++) { - int index = source.length() - (IDFormat.IdByteArraySize - eachByte) * 2; - String twoChars = source.substring(index, index + 2); - - id.bytes[eachByte] = (byte) Integer.parseInt(twoChars, 16); - } - } catch (NumberFormatException caught) { - throw new URISyntaxException(source, "Invalid Character in JXTA URI"); - } - - switch (id.bytes[IDFormat.flagsOffset + IDFormat.flagsIdTypeOffset]) { - case IDFormat.flagCodatID: - result = new CodatID(id); - break; - - case IDFormat.flagPeerGroupID: - result = new PeerGroupID(id); - result = IDFormat.translateToWellKnown(result); - break; - - case IDFormat.flagPeerID: - result = new PeerID(id); - break; - - case IDFormat.flagPipeID: - result = new PipeID(id); - break; - - case IDFormat.flagModuleClassID: - result = new ModuleClassID(id); - break; - - case IDFormat.flagModuleSpecID: - result = new ModuleSpecID(id); - break; - - default: - throw new URISyntaxException(source, "JXTA ID Type not recognized"); - } - - return result; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/ModuleClassID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/ModuleClassID.java deleted file mode 100644 index 2f56ff62..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/ModuleClassID.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - - -/** - * An implementation of the {@link net.jxta.platform.ModuleClassID} ID Type. - */ -public class ModuleClassID extends net.jxta.platform.ModuleClassID { - - /** - * Location of the class id - */ - private final static int moduleClassIdOffset = 0; - - /** - * Location of the role id - */ - private final static int moduleRoleIdOffset = moduleClassIdOffset + IDFormat.uuidSize; - - /** - * location of the start of the pad space - */ - private final static int padOffset = ModuleClassID.moduleRoleIdOffset + IDFormat.uuidSize; - - /** - * size of the unused space - */ - private final static int padSize = IDFormat.flagsOffset - ModuleClassID.padOffset; - - /** - * The id data - */ - protected IDBytes id; - - /** - * Constructor. - * Initializes contents from provided ID. - * - * @param id the ID data - */ - protected ModuleClassID(IDBytes id) { - super(); - this.id = id; - } - - /** - * Constructor. - * Creates a ModuleClassID in a given class, with a given class unique id. - * A UUID of a class and another UUID are provided. - * - * @param classUUID the class to which this will belong. - * @param roleUUID the unique id of this role in that class. - */ - protected ModuleClassID(UUID classUUID, UUID roleUUID) { - super(); - id = new IDBytes(IDFormat.flagModuleClassID); - - id.longIntoBytes(ModuleClassID.moduleClassIdOffset, classUUID.getMostSignificantBits()); - id.longIntoBytes(ModuleClassID.moduleClassIdOffset + 8, classUUID.getLeastSignificantBits()); - - id.longIntoBytes(ModuleClassID.moduleRoleIdOffset, roleUUID.getMostSignificantBits()); - id.longIntoBytes(ModuleClassID.moduleRoleIdOffset + 8, roleUUID.getLeastSignificantBits()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newModuleClassID()}. - * - *

            A new class UUID is created. The role ID is left null. This is the - * only way to create a new class without supplying a new UUID explicitly. - * - *

            Note that a null role is just as valid as any other, it just has a - * shorter string representation. So it is not mandatory to create a new - * role in a new class. - */ - public ModuleClassID() { - this(UUIDFactory.newUUID(), new UUID(0L, 0L)); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newModuleClassID(net.jxta.platform.ModuleClassID)}. - */ - public ModuleClassID(ModuleClassID classID) { - this(classID.getClassUUID(), UUIDFactory.newUUID()); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof ModuleClassID) { - ModuleClassID mcidTarget = (ModuleClassID) target; - - return id.equals(mcidTarget.id); - } else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return id.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + (String) id.getUniqueValue(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.platform.ModuleClassID getBaseClass() { - return new ModuleClassID(getClassUUID(), new UUID(0L, 0L)); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isOfSameBaseClass(net.jxta.platform.ModuleClassID classId) { - return getClassUUID().equals(((ModuleClassID) classId).getClassUUID()); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isOfSameBaseClass(net.jxta.platform.ModuleSpecID specId) { - return getClassUUID().equals(((ModuleSpecID) specId).getClassUUID()); - } - - /** - * get the class' unique id - * - * @return UUID module class' unique id - */ - protected UUID getClassUUID() { - UUID result = new UUID(id.bytesIntoLong(ModuleClassID.moduleClassIdOffset) - , - id.bytesIntoLong(ModuleClassID.moduleClassIdOffset + 8)); - - return result; - } - - /** - * get the role unique id - * - * @return UUID module role unique id - */ - protected UUID getRoleUUID() { - UUID result = new UUID(id.bytesIntoLong(ModuleClassID.moduleRoleIdOffset) - , - id.bytesIntoLong(ModuleClassID.moduleRoleIdOffset + 8)); - - return result; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/ModuleSpecID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/ModuleSpecID.java deleted file mode 100644 index eed81a10..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/ModuleSpecID.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - - -/** - * An implementation of the {@link net.jxta.platform.ModuleSpecID} ID Type. - */ -public class ModuleSpecID extends net.jxta.platform.ModuleSpecID { - private final static int moduleClassIdOffset = 0; - private final static int moduleSpecIdOffset = IDFormat.uuidSize; - private final static int padOffset = ModuleSpecID.moduleSpecIdOffset + IDFormat.uuidSize; - private final static int padSize = IDFormat.flagsOffset - ModuleSpecID.padOffset; - - /** - * The id data - */ - protected IDBytes id; - - /** - * Constructor. Used only internally. - */ - protected ModuleSpecID() { - super(); - id = new IDBytes(IDFormat.flagModuleSpecID); - } - - /** - * Initializes contents from provided ID. - * - * @param id the ID data - */ - protected ModuleSpecID(IDBytes id) { - super(); - this.id = id; - } - - /** - * Creates a ModuleSpecID in a given class, with a given class unique id. - * A UUID of a class and another UUID are provided. - * - * @param classUUID the class to which this will belong. - * @param specUUID the unique id of this spec in that class. - */ - protected ModuleSpecID(UUID classUUID, UUID specUUID) { - - this(); - id.longIntoBytes(ModuleSpecID.moduleClassIdOffset, classUUID.getMostSignificantBits()); - id.longIntoBytes(ModuleSpecID.moduleClassIdOffset + 8, classUUID.getLeastSignificantBits()); - - id.longIntoBytes(ModuleSpecID.moduleSpecIdOffset, specUUID.getMostSignificantBits()); - id.longIntoBytes(ModuleSpecID.moduleSpecIdOffset + 8, specUUID.getLeastSignificantBits()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newModuleSpecID(net.jxta.platform.ModuleClassID)}. - */ - public ModuleSpecID(ModuleClassID classID) { - this(classID.getClassUUID(), UUIDFactory.newUUID()); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof ModuleSpecID) { - ModuleSpecID msidTarget = (ModuleSpecID) target; - - return id.equals(msidTarget.id); - } else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return id.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + (String) id.getUniqueValue(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.platform.ModuleClassID getBaseClass() { - return new ModuleClassID(getClassUUID(), new UUID(0L, 0L)); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isOfSameBaseClass(net.jxta.platform.ModuleClassID classId) { - return getClassUUID().equals(((ModuleClassID) classId).getClassUUID()); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isOfSameBaseClass(net.jxta.platform.ModuleSpecID specId) { - return getClassUUID().equals(((ModuleSpecID) specId).getClassUUID()); - } - - /** - * get the class' unique id - * - * @since JXTA 1.0 - * - * @return UUID module class' unique id - */ - protected UUID getClassUUID() { - UUID result = new UUID(id.bytesIntoLong(ModuleSpecID.moduleClassIdOffset) - , - id.bytesIntoLong(ModuleSpecID.moduleClassIdOffset + 8)); - - return result; - } - - /** - * get the spec unique id - * - * @since JXTA 1.0 - * - * @return UUID module spec unique id - */ - protected UUID getSpecUUID() { - UUID result = new UUID(id.bytesIntoLong(ModuleSpecID.moduleSpecIdOffset) - , - id.bytesIntoLong(ModuleSpecID.moduleSpecIdOffset + 8)); - - return result; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/PeerGroupID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/PeerGroupID.java deleted file mode 100644 index 616345c9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/PeerGroupID.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - - -/** - * An implementation of the {@link net.jxta.peergroup.PeerGroupID} ID Type. - */ -public class PeerGroupID extends net.jxta.peergroup.PeerGroupID { - - /** - * Location of the group id UUID within the id bytes. - */ - protected final static int groupIdOffset = 0; - - /** - * Location of the parent group id UUID within the id bytes. - */ - protected final static int parentgroupIdOffset = PeerGroupID.groupIdOffset + IDFormat.uuidSize; - - /** - * Location of the begining of the pad space. - */ - protected final static int padOffset = PeerGroupID.parentgroupIdOffset + IDFormat.uuidSize; - - /** - * size of the pad space. - */ - protected final static int padSize = IDFormat.flagsOffset - PeerGroupID.padOffset; - - /** - * The id data - */ - protected IDBytes id; - - /** - * Initializes contents from provided ID. - * - * @param id the ID data - */ - protected PeerGroupID(IDBytes id) { - super(); - this.id = id; - } - - /** - * Creates a PeerGroupID. A PeerGroupID is provided - * - * @param groupUUID the PeerGroupID to use to construct the new PeerGroupID - */ - protected PeerGroupID(UUID groupUUID) { - super(); - id = new IDBytes(IDFormat.flagPeerGroupID); - - id.longIntoBytes(PeerGroupID.groupIdOffset, groupUUID.getMostSignificantBits()); - id.longIntoBytes(PeerGroupID.groupIdOffset + 8, groupUUID.getLeastSignificantBits()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerGroupID()}. - */ - public PeerGroupID() { - this(UUIDFactory.newUUID()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerGroupID(net.jxta.peergroup.PeerGroupID)}. - */ - public PeerGroupID(PeerGroupID parent) { - this(UUIDFactory.newUUID()); - - System.arraycopy(parent.id.bytes, 0, id.bytes, 16, IDFormat.uuidSize); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerGroupID(byte[])}. - */ - public PeerGroupID(byte[] seed) { - super(); - id = new IDBytes(IDFormat.flagPeerGroupID); - - for (int copySeed = Math.min(IDFormat.uuidSize, seed.length) - 1; copySeed >= 0; copySeed--) { - id.bytes[copySeed + PeerGroupID.groupIdOffset] = seed[copySeed]; - } - - // make it a valid UUID - id.bytes[PeerGroupID.groupIdOffset + 6] &= 0x0f; - id.bytes[PeerGroupID.groupIdOffset + 6] |= 0x40; /* version 4 */ - id.bytes[PeerGroupID.groupIdOffset + 8] &= 0x3f; - id.bytes[PeerGroupID.groupIdOffset + 8] |= 0x80; /* IETF variant */ - id.bytes[PeerGroupID.groupIdOffset + 10] &= 0x3f; - id.bytes[PeerGroupID.groupIdOffset + 10] |= 0x80; /* multicast bit */ - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerGroupID(net.jxta.peergroup.PeerGroupID,byte[])}. - */ - public PeerGroupID(PeerGroupID parent, byte[] seed) { - this(seed); - - System.arraycopy(parent.id.bytes, 0, id.bytes, 16, IDFormat.uuidSize); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof PeerGroupID) { - PeerGroupID peergroupTarget = (PeerGroupID) target; - - return id.equals(peergroupTarget.id); - } else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return id.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + (String) id.getUniqueValue(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.peergroup.PeerGroupID getParentPeerGroupID() { - boolean zero = true; - - for (int eachByte = 0; eachByte < IDFormat.uuidSize; eachByte++) { - if (id.bytes[eachByte + PeerGroupID.parentgroupIdOffset] != 0) { - zero = false; - break; - } - } - - // if zero, then there is no parent. - if (zero) { - return null; - } - - UUID groupUUID = new UUID(id.bytesIntoLong(PeerGroupID.parentgroupIdOffset) - , - id.bytesIntoLong(PeerGroupID.parentgroupIdOffset + 8)); - - PeerGroupID groupID = new PeerGroupID(groupUUID); - - // convert to the generic world PGID as necessary - return (net.jxta.peergroup.PeerGroupID) IDFormat.translateToWellKnown(groupID); - } - - /** - * Returns the UUID associated with this PeerGroupID. - * - * @return The UUID associated with this PeerGroupID. - */ - protected UUID getUUID() { - return new UUID(id.bytesIntoLong(PeerGroupID.groupIdOffset), id.bytesIntoLong(PeerGroupID.groupIdOffset + 8)); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/PeerID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/PeerID.java deleted file mode 100644 index 4ba50ed3..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/PeerID.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -/** - * An implementation of the {@link net.jxta.peer.PeerID} ID Type. - */ -public class PeerID extends net.jxta.peer.PeerID { - - protected final static int groupIdOffset = 0; - protected final static int idOffset = PeerID.groupIdOffset + IDFormat.uuidSize; - protected final static int padOffset = PeerID.idOffset + IDFormat.uuidSize; - - protected final static int padSize = IDFormat.flagsOffset - PeerID.padOffset; - - /** - * The id data - */ - protected IDBytes id; - - /** - * Used only internally. - */ - protected PeerID() { - super(); - id = new IDBytes(IDFormat.flagPeerID); - } - - /** - * Initializes contents from provided ID. - * - * @param id the ID data - */ - protected PeerID(IDBytes id) { - super(); - this.id = id; - } - - /** - * Creates a PeerID. A PeerGroupID is provided - * - * @param groupUUID the UUID of the group to which this will belong. - * @param idUUID the UUID which will be used for this pipe. - */ - protected PeerID(UUID groupUUID, UUID idUUID) { - this(); - - id.longIntoBytes(PipeID.groupIdOffset, groupUUID.getMostSignificantBits()); - id.longIntoBytes(PipeID.groupIdOffset + 8, groupUUID.getLeastSignificantBits()); - - id.longIntoBytes(PipeID.idOffset, idUUID.getMostSignificantBits()); - id.longIntoBytes(PipeID.idOffset + 8, idUUID.getLeastSignificantBits()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerID(net.jxta.peergroup.PeerGroupID)}. - */ - public PeerID(PeerGroupID groupID) { - this(groupID.getUUID(), UUIDFactory.newUUID()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPeerID(net.jxta.peergroup.PeerGroupID,byte[])}. - */ - public PeerID(PeerGroupID groupID, byte[] seed) { - this(); - - UUID groupUUID = new UUID(groupID.id.bytesIntoLong(PeerGroupID.groupIdOffset) - , - groupID.id.bytesIntoLong(PeerGroupID.groupIdOffset + 8)); - - byte[] idUUIDbytes = new byte[IDFormat.uuidSize]; - - System.arraycopy(seed, 0, idUUIDbytes, 0, Math.min(IDFormat.uuidSize, seed.length)); - - UUID idUUID = UUIDFactory.newUUID(idUUIDbytes); - - id.longIntoBytes(PipeID.groupIdOffset, groupUUID.getMostSignificantBits()); - id.longIntoBytes(PipeID.groupIdOffset + 8, groupUUID.getLeastSignificantBits()); - - id.longIntoBytes(PipeID.idOffset, idUUID.getMostSignificantBits()); - id.longIntoBytes(PipeID.idOffset + 8, idUUID.getLeastSignificantBits()); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof PeerID) { - PeerID peerTarget = (PeerID) target; - - return id.equals(peerTarget.id); - } else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return id.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + (String) id.getUniqueValue(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.id.ID getPeerGroupID() { - UUID groupUUID = new UUID(id.bytesIntoLong(PeerID.groupIdOffset), id.bytesIntoLong(PeerID.groupIdOffset + 8)); - - PeerGroupID groupID = new PeerGroupID(groupUUID); - - // convert to the generic world PGID as necessary - return IDFormat.translateToWellKnown(groupID); - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/PipeID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/PipeID.java deleted file mode 100644 index 92d25b20..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/PipeID.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - - -/** - * An implementation of the {@link net.jxta.pipe.PipeID} ID Type. - */ -public class PipeID extends net.jxta.pipe.PipeID { - protected final static int groupIdOffset = 0; - protected final static int idOffset = PipeID.groupIdOffset + IDFormat.uuidSize; - protected final static int padOffset = PipeID.idOffset + IDFormat.uuidSize; - protected final static int padSize = IDFormat.flagsOffset - PipeID.padOffset; - - /** - * The id data - */ - protected IDBytes id; - - /** - * Used only internally - * - */ - protected PipeID() { - super(); - id = new IDBytes(IDFormat.flagPipeID); - } - - /** - * Constructor. - * Initializes contents from provided ID. - * - * - * @param id the ID data - */ - protected PipeID(IDBytes id) { - super(); - this.id = id; - } - - /** - * Creates a PipeID. A PeerGroupID is provided - * - * @param groupUUID the UUID of the group to which this will belong. - * @param idUUID the UUID which will be used for this pipe. - */ - protected PipeID(UUID groupUUID, UUID idUUID) { - this(); - - id.longIntoBytes(PipeID.groupIdOffset, groupUUID.getMostSignificantBits()); - id.longIntoBytes(PipeID.groupIdOffset + 8, groupUUID.getLeastSignificantBits()); - - id.longIntoBytes(PipeID.idOffset, idUUID.getMostSignificantBits()); - id.longIntoBytes(PipeID.idOffset + 8, idUUID.getLeastSignificantBits()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPipeID(net.jxta.peergroup.PeerGroupID)}. - */ - public PipeID(PeerGroupID groupID) { - this(groupID.getUUID(), UUIDFactory.newUUID()); - } - - /** - * See {@link net.jxta.id.IDFactory.Instantiator#newPipeID(net.jxta.peergroup.PeerGroupID,byte[])}. - */ - public PipeID(PeerGroupID groupID, byte[] seed) { - this(); - - UUID groupUUID = groupID.getUUID(); - - id.longIntoBytes(PipeID.groupIdOffset, groupUUID.getMostSignificantBits()); - id.longIntoBytes(PipeID.groupIdOffset + 8, groupUUID.getLeastSignificantBits()); - - for (int copySeed = Math.min(IDFormat.uuidSize, seed.length) - 1; copySeed >= 0; copySeed--) { - id.bytes[copySeed + PipeID.idOffset] = seed[copySeed]; - } - - // make it a valid UUID - id.bytes[PipeID.idOffset + 6] &= 0x0f; - id.bytes[PipeID.idOffset + 6] |= 0x40; /* version 4 */ - id.bytes[PipeID.idOffset + 8] &= 0x3f; - id.bytes[PipeID.idOffset + 8] |= 0x80; /* IETF variant */ - id.bytes[PipeID.idOffset + 10] &= 0x3f; - id.bytes[PipeID.idOffset + 10] |= 0x80; /* multicast bit */ - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof PipeID) { - PipeID pipeTarget = (PipeID) target; - - return id.equals(pipeTarget.id); - } else { - return false; - } - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return id.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + (String) id.getUniqueValue(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.id.ID getPeerGroupID() { - UUID groupUUID = new UUID(id.bytesIntoLong(PipeID.groupIdOffset), id.bytesIntoLong(PipeID.groupIdOffset + 8)); - - PeerGroupID groupID = new PeerGroupID(groupUUID); - - // convert to the generic world PGID as necessary - return IDFormat.translateToWellKnown(groupID); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/UUID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/UUID.java deleted file mode 100644 index f7ea4da1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/UUID.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -import java.io.Serializable; - - -/** - * A UUID is a 128-bit universally unique identifier. - * The most significant long can be decomposed into the following - * unsigned fields: - *

            - * 0xFFFFFFFF00000000 time_low
            - * 0x00000000FFFF0000 time_mid
            - * 0x000000000000F000 version
            - * 0x0000000000000FFF time_hi
            - * 
            - *

            The least significant long can be decomposed into the following - * unsigned fields: - *

            - * 0xC000000000000000 variant
            - * 0x3FFF000000000000 clock_seq
            - * 0x0000FFFFFFFFFFFF node
            - * 
            - *

            The variant field must be 0x2. The version field must be either 0x1 or 0x4. - * - *

            If the version field is 0x4, then the most significant bit of the node - * field must be set to 1, and the remaining fields are set to values - * produced by a cryptographically strong pseudo-random number generator. - * - *

            If the version field is 0x1, then the node field is set to an IEEE 802 - * address (MAC), the clock_seq field is set to a 14-bit random number, and the - * time_low, time_mid, and time_hi fields are set to the least, middle and - * most significant bits (respectively) of a 60-bit timestamp measured in - * 100-nanosecond units since midnight, October 15, 1582 UTC. - * - * @see net.jxta.impl.id.UUID.IDFormat - * @see net.jxta.impl.id.UUID.UUIDFactory - * @see "Information Technology - Open Systems Interconnection - Remote Procedure Call (RPC), ISO 11578:1996" - * @see The Open Group - DCE 1.1 Remote Procedure Call (RPC) : Appendix A - Universal Unique Identifier - * - */ -public final class UUID implements Serializable { - - /** - * The null UUID. Useful for comparisons. - */ - public static final UUID nullUUID = new UUID(0L, 0L); - - /** - * The most significant 64 bits. - */ - private long mostSig; - - /** - * The least significant 64 bits. - */ - private long leastSig; - - /** - * Simple constructor. This constructor does not check to ensure that the - * values provided produce a valid UUID. - * - * @param mostSig the most significant 64 bits - * @param leastSig the least significant 64 bits - */ - public UUID(long mostSig, long leastSig) { - this.mostSig = mostSig; - this.leastSig = leastSig; - } - - /** - * Simple constructor. This constructor does not check to ensure that the - * values provided produce a valid UUID. - * - * @param bytes the 128 bits of - */ - public UUID(byte[] bytes) { - if (bytes.length != 16) { - throw new IllegalArgumentException("bytes must be 16 bytes in length"); - } - - long mostSig = 0; - - for (int i = 0; i < 8; i++) { - mostSig = (mostSig << 8) | (bytes[i] & 0xff); - } - - long leastSig = 0; - - for (int i = 8; i < 16; i++) { - leastSig = (leastSig << 8) | (bytes[i] & 0xff); - } - - this.mostSig = mostSig; - this.leastSig = leastSig; - } - - public UUID(String uuid) { - if (36 != uuid.length()) { - throw new IllegalArgumentException("uuid must be 36 characters in length"); - } - - byte bytes[] = new byte[16]; - - boolean hi = true; - - for (int eachChar = 0, offset = 0; eachChar < 36; eachChar++) { - char aChar = uuid.charAt(eachChar); - - switch (eachChar) { - case 8: - case 13: - case 18: - case 23: - if ('-' != uuid.charAt(eachChar)) { - throw new IllegalArgumentException("uuid has an illegal character at position " + eachChar); - } - break; - - default: - aChar = Character.toLowerCase(aChar); - - int aNibble; - - if (('0' <= aChar) && ('9' >= aChar)) { - aNibble = aChar - '0'; - } else if (('a' <= aChar) && ('f' >= aChar)) { - aNibble = aChar - 'a' + 10; - } else { - throw new IllegalArgumentException("uuid has an illegal character at position " + eachChar); - } - - if (hi) { - aNibble <<= 4; - } - - bytes[offset] |= aNibble; - - if (!hi) { - offset++; - } - - hi = !hi; - } - } - - mostSig = 0; - for (int i = 0; i < 8; i++) { - mostSig = (mostSig << 8) | (bytes[i] & 0xff); - } - - leastSig = 0; - for (int i = 8; i < 16; i++) { - leastSig = (leastSig << 8) | (bytes[i] & 0xff); - } - } - - /** - * Returns the most significant 64 bits of the UUID. - * - * @return long return most significant bits - */ - public long getMostSignificantBits() { - return mostSig; - } - - /** - * Returns the least significant 64 bits of the UUID. - * - * @return long least significant bits - */ - public long getLeastSignificantBits() { - return leastSig; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return (int) ((mostSig >> 32) ^ mostSig ^ (leastSig >> 32) ^ leastSig); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof UUID) { - return equals((UUID) target); - } else { - return false; - } - } - - /** - * UUIDs are equal if they represent the same 128-bit value. - * - * @param sid UUID seed - * @return boolean true if equals - */ - public boolean equals(UUID sid) { - if (null == sid) { - return false; - } - - return (mostSig == sid.mostSig && leastSig == sid.leastSig); - } - - /** - * Returns a 36-character string of six fields separated by hyphens, - * with each field represented in lowercase hexadecimal with the same - * number of digits as in the field. The order of fields is: time_low, - * time_mid, version and time_hi treated as a single field, variant and - * clock_seq treated as a single field, and node. - * - * ie. XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - * - * @return String return value - */ - @Override - public String toString() { - return (digits(mostSig >> 32, 8) + "-" + digits(mostSig >> 16, 4) + "-" + digits(mostSig, 4) + "-" - + digits(leastSig >> 48, 4) + "-" + digits(leastSig, 12)); - } - - /** - * Returns val represented by the specified number of hex digits - * - * @param val value - * @param digits - * @return String return value - */ - private static String digits(long val, int digits) { - long hi = 1L << (digits * 4); - - return Long.toHexString(hi | (val & (hi - 1))).substring(1); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/UUIDFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/UUIDFactory.java deleted file mode 100644 index 689dedee..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/UUIDFactory.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.UUID; - - -import java.security.SecureRandom; -import java.util.GregorianCalendar; -import java.util.Random; -import java.util.Calendar; -import java.util.TimeZone; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - - -/** - * A Factory for generating random UUIDs. - * - * @see net.jxta.impl.id.UUID.UUID - */ -public final class UUIDFactory { - - /** - * Log4J Logger - */ - private static final transient Logger LOG = Logger.getLogger(UUIDFactory.class.getName()); - - /** - * The point at which the Gregorian calendar rules are used, measured in - * milliseconds from the standard epoch. Default is October 15, 1582 - * (Gregorian) 00:00:00 UTC or -12219292800000L. - */ - static final long GREGORIAN_MILLIS_OFFSET = 12219292800000L; - - /** - * offset of this computer relative to utc - */ - private long utc_offset = 0L; - - /** - * Time at which we last generated a version 1 UUID in relative - * milliseconds from 00:00:00.00, 15 October 1582 UTC. - */ - private long lastTimeSequence = 0L; - - /** - * Count of how many version 1 UUIDs we have generated at this time - * sequence value. - */ - private long inSequenceCounter = 0L; - - /** - * pseudo random value to prevent clock collisions on the same computer. - */ - private long clock_seq = 0L; - - /** - * pseudo random value. If available, this should be seeded with the MAC - * address of a local network interface. - */ - private long node = 0L; - - /** - * Random number generator for UUID generation. - */ - private Random randNum = null; - - /** - * We have to catch exceptions from construct of JRandom so we - * have to init it inline. - */ - private static UUIDFactory factory = new UUIDFactory(); - - /** - * Generate a new random UUID value. The UUID returned is a version 4 IETF - * variant random UUID. - * - *

            This member must be synchronized because it makes use of shared - * internal state. - * - * @return UUID returns a version 4 IETF variant random UUID. - */ - public synchronized static UUID newUUID() { - - return newUUID(factory.randNum.nextLong(), factory.randNum.nextLong()); - } - - /** - * Returns a formatted time sequence field containing the elapsed time in - * 100 nano units since 00:00:00.00, 15 October 1582. Since the normal - * clock resolution is coarser than 100 nano than this value, the lower - * bits are generated in sequence for each call within the same milli. - * - * @return time sequence value - */ - private synchronized long getTimeSequence() { - long now = (System.currentTimeMillis() - GREGORIAN_MILLIS_OFFSET + utc_offset) * 10000L; // convert to 100 nano units; - - if (now > lastTimeSequence) { - lastTimeSequence = now; - // XXX bondolo@jxta.org It might be better to set this to a random - // value and just watch for rollover. The reason is that there may - // be more than one instance running on the same computer which is - // generating UUIDs, but is not excluded by our synchronization. - // A random value would reduce collisions. - inSequenceCounter = 0; - } else { - inSequenceCounter++; - if (inSequenceCounter >= 10000L) { - // we allow the clock to skew forward rather than wait. It's - // really unlikely that anyone will be continuously generating - // more than 10k UUIDs per milli for very long. - lastTimeSequence += 10000L; - inSequenceCounter = 0; - } - } - - return (lastTimeSequence + inSequenceCounter); - } - - /** - * Generate a new UUID value. The UUID returned is a version 1 IETF - * variant UUID. - * - *

            The node value used is currently a random value rather than the - * normal ethernet MAC address because the MAC address is not directly - * accessible in to java. - * - * @return UUID returns a version 1 IETF variant UUID. - */ - public static UUID newSeqUUID() { - long mostSig = 0L, leastSig = 0L; - - long timeSeq = factory.getTimeSequence(); - - mostSig |= (timeSeq & 0x0FFFFFFFFL) << 32; - mostSig |= ((timeSeq >> 32) & 0x0FFFFL) << 16; - mostSig |= (0x01L) << 12; // version 1; - mostSig |= ((timeSeq >> 48) & 0x00FFFL); - - leastSig |= (0x02L) << 62; // ietf variant - leastSig |= ((factory.clock_seq >> 8) & 0x03FL) << 56; - leastSig |= (factory.clock_seq & 0x0FFL) << 48; - leastSig |= factory.node & 0x0FFFFFFFFFFFFL; - - return new UUID(mostSig, leastSig); - } - - /** - * Generate a new UUID value. The values provided are masked to produce a - * version 4 IETF variant random UUID. - * - * @param bytes the 128 bits of the UUID - * @return UUID returns a version 4 IETF variant random UUID. - */ - public static UUID newUUID(byte[] bytes) { - if (bytes.length != 16) { - throw new IllegalArgumentException("bytes must be 16 bytes in length"); - } - - long mostSig = 0; - - for (int i = 0; i < 8; i++) { - mostSig = (mostSig << 8) | (bytes[i] & 0xff); - } - - long leastSig = 0; - - for (int i = 8; i < 16; i++) { - leastSig = (leastSig << 8) | (bytes[i] & 0xff); - } - - return newUUID(mostSig, leastSig); - } - - /** - * Generate a new UUID value. The values provided are masked to produce a - * version 3 IETF variant UUID. - * - * @param mostSig High-long of UUID value. - * @param leastSig Low-long of UUID value. - * @return UUID returns a version 3 IETF variant random UUID. - */ - public static UUID newHashUUID(long mostSig, long leastSig) { - - mostSig &= 0xFFFFFFFFFFFF0FFFL; - mostSig |= 0x0000000000003000L; // version 3 - leastSig &= 0x3FFFFFFFFFFFFFFFL; - leastSig |= 0x8000000000000000L; // IETF variant - - return new UUID(mostSig, leastSig); - } - - /** - * Generate a new UUID value. The values provided are masked to produce a - * version 4 IETF variant random UUID. - * - * @param mostSig High-long of UUID value. - * @param leastSig Low-long of UUID value. - * @return UUID returns a version 4 IETF variant random UUID. - */ - public static UUID newUUID(long mostSig, long leastSig) { - - mostSig &= 0xFFFFFFFFFFFF0FFFL; - mostSig |= 0x0000000000004000L; // version 4 - leastSig &= 0x3FFFFFFFFFFFFFFFL; - leastSig |= 0x8000000000000000L; // IETF variant - - leastSig &= 0xFFFF7FFFFFFFFFFFL; - leastSig |= 0x0000800000000000L; // multicast bit - - return new UUID(mostSig, leastSig); - } - - /** - * Singleton class - */ - private UUIDFactory() { - - randNum = new SecureRandom(); - - String[] tz_ids = TimeZone.getAvailableIDs(0); - Calendar gregorianCalendar = new GregorianCalendar(); - - // FIXME 20031024 bondolo@jxta.org In theory we should be doing this - // EVERY time we generate a UUID. In practice because of we use a random - // clock_seq we don't have to. - utc_offset = gregorianCalendar.get(Calendar.ZONE_OFFSET) + gregorianCalendar.get(Calendar.DST_OFFSET); - - // Generate a random clock seq - clock_seq = randNum.nextInt() & 0x03FFL; - - // Generate a random node ID since we can't get the MAC Address - node = (randNum.nextLong() & 0x0000FFFFFFFFFFFFL); - node |= 0x0000800000000000L; // mask in the multicast bit since we don't know if its unique. - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/package.html deleted file mode 100644 index dc0f6b23..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/UUID/package.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - The 'uuid' format is a general purpose JXTA ID Format. It implements all of - the six standard ID types. It was originally created for the Jave 2 SE - reference implementation. The 'uuid' format uses randomly generated UUIDs - as the mechanism for generating canonical values for the ids it provides. - - @see JXTA Protocols Specification : IDs - @see JXTA Protocols Specification -: UUID ID Format - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/BinaryID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/BinaryID.java deleted file mode 100644 index fd45a2f1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/BinaryID.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.binaryID; - - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.Serializable; - - -/** - * A BinaryID is a 256-byte, identifier. - * This class should be immutable so that it is thread safe. - * - * @author Daniel Brookshier turbogeek@cluck.com - * @see net.jxta.id.ID - * @see net.jxta.id.IDFactory - */ - -public class BinaryID implements Serializable { - - private final static transient Logger LOG = Logger.getLogger(BinaryID.class.getName()); - public static String UUIDEncoded = "uuid"; - public final static int flagsSize = 1; - - public final static byte flagPeerGroupID = 'a'; - public final static byte flagPeerID = 'b'; - public final static byte flagPipeID = 'c'; - - public final static byte flagModuleClassID = 'd'; - public final static byte flagModuleClassRoleID = 'e'; - - public final static byte flagModuleSpecID = 'f'; - public final static byte flagCodatID = 'g'; - public final static byte flagGenericID = 'z'; - - /** - * location of the byte designating its type. - */ - public final static int flagsOffset = 0; - - /** - * location of the byte where the data starts. - */ - public final static int dataOffset = 1; - - /** - * Null id contents. - */ - private static final byte[] nullID = { 0}; - public static final BinaryID nullBinaryID = new BinaryID(flagGenericID, nullID, true); - - /** - * Array that holds the length and the value of the id in base64 format. This is the default format - * rather than binary byte because it saves time converting. Odds of returning the actual binary are - * low so it is done on demand only. Callers of the toByteArray() method should consider the cost of - * decoding if it is to be called often. - */ - protected String encodedValue = null; - - /** - * Creates a null value ID. - */ - public BinaryID() { - this.encodedValue = nullBinaryID.encodedValue; // (flagGenericID, nullID, true); - } - - /** - * Creates zero content ID of a specific type. - */ - public BinaryID(byte id) { - this(id, nullID, true); - } - - /** - * Creates a ID from a string. Note that the ID is not currently validated. - * - * @param encodedValue Value to convert ID. - */ - protected BinaryID(String encodedValue) { - this.encodedValue = encodedValue; - } - - /** - * Simple constructor that takes a binary array to signify the contents of the array. - * - * @param type The Type of ID. Valid values: flagPeerGroupID,flagPeerID,flagPipeID,flagGenericID - * @param data the array of up to 256 bytes. Max is 256 if lengthIncluded is true or 255 if the first byte is the length-1. - * @param lengthIncluded Boolean that signifies if the first byte is the length of the bytes to follow. - * @throws RuntimeException Runtime exception trhown if array is not correct or if included, the array length does not match actual size. - */ - - public BinaryID(byte type, byte data[], boolean lengthIncluded) { - if (lengthIncluded && data.length < 256 && data.length > 1) { - if (data[0] == data.length - 1) { - try { - java.io.StringWriter base64 = new java.io.StringWriter(); - net.jxta.impl.util.BASE64OutputStream encoder = new net.jxta.impl.util.BASE64OutputStream(base64); - - encoder.write(data); - encoder.close(); - - encodedValue = ((char) type) + base64.toString(); - } catch (Exception e) { - LOG.log(Level.SEVERE, "Unable to encode binary value.", e); - throw new RuntimeException("Unable to encode binary value."); - } - } else { - throw new RuntimeException( - "Length of data section is " + (data.length - 1) + " but byte zero says length is:" + data[0] + "."); - } - } else if (!lengthIncluded && data.length > 0) { - byte temp[] = new byte[data.length + 1]; - - temp[0] = (byte) data.length; - System.arraycopy(data, 0, temp, 1, data.length); - try { - java.io.StringWriter base64 = new java.io.StringWriter(); - net.jxta.impl.util.BASE64OutputStream encoder = new net.jxta.impl.util.BASE64OutputStream(base64); - - encoder.write(temp); - encoder.close(); - - encodedValue = ((char) type) + base64.toString(); - } catch (Exception e) { - LOG.log(Level.SEVERE, "Unable to encode binary value.", e); - throw new RuntimeException("Unable to encode binary value."); - } - } else if (lengthIncluded && (data.length > 256 || data.length == 0)) { - throw new RuntimeException("Length of 'data' is " + data.length + " must be >0 and less or equal to 256."); - } else if (!lengthIncluded && data.length > 255) { - throw new RuntimeException("Length of 'data' is " + data.length + " must be less than 256. "); - } - } - - /** - * Returns the value of the ID as a binary array. This is always decoded from the base64 - * string rather than caching of the binary array. Callers of the toByteArray() method - * should consider the cost of decoding if the method is called often. - * - * @return returns the data part of the array. - */ - public byte[] toByteArray() { - try { - java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); - net.jxta.impl.util.BASE64InputStream decoder = new net.jxta.impl.util.BASE64InputStream( - new java.io.StringReader(encodedValue.substring(1))); - - while (true) { - int c = decoder.read(); - - if (-1 == c) { - break; - } - - bos.write(c); - } - - return bos.toByteArray(); - } catch (Exception e) { - LOG.log(Level.SEVERE, "Unable to decode binary value.", e); - throw new RuntimeException("Unable to encode binary value."); - } - - } - - /** - * Returns the value of the ID as a binary array without the size in byte zero. This is always decoded from the base64 - * string rather than caching of the binary array. Callers of the toByteArray() method - * should consider the cost of decoding if the method is called often.

            - *

            - * Note that we assume the array size-1 equals the contents of byte zero. - * - * @return returns the array with the first byte as the length of the remaining bytes. - */ - public byte[] toSizeIncludedByteArray() { - byte[] data = toByteArray(); - - byte temp[] = new byte[data.length - 1]; - - System.arraycopy(data, 1, temp, 0, temp.length); - - return temp; - } - - /** - * @return The ID which consists of a character designating type, followed by the base64 encoded value of the size and array of bytes. - */ - public String encodedValue() { - return encodedValue; - } - - /** - * Returns the hash code of the BinaryID

            - *

            - * WARNING: Do not use this hash as a network ID. Use a stronger digest hash like SHA-1 to get the hash of the contents. - * - * @return int hashcode - */ - - @Override - public int hashCode() { - return encodedValue.hashCode(); - } - - /** - * Compares two BinaryIDs for equality.

            - * true: taget == this

            - * false: target == null

            - * true: taget.encodedValue == this.encodedValue

            - * true: target instance of ID && ID==ID.nullID && nullBinaryID.encodedValue().equals( encodedValue())

            - * false: all other posibilities

            - * - * @param target the BidaryID to be compared against. - * @return boolean true if IDs are equal, false otherwise. - */ - @Override - public boolean equals(Object target) { - boolean result = false; - - if (target == this) { - result = true; - } else if (target == null) { - result = false; - } else if (target instanceof BinaryID) { - result = encodedValue().equals(((BinaryID) target).encodedValue()); - LOG.fine("((BinaryID)target).encodedValue():" + ((BinaryID) target).encodedValue()); - } else if (target instanceof net.jxta.id.ID && ((net.jxta.id.ID) target) == net.jxta.id.ID.nullID - && nullBinaryID.encodedValue().equals(encodedValue())) { - result = true; - } - // LOG.error("this:"+encodedValue()+" type:"+target.getClass().getName()+" target:"+target+" equals:"+result,new RuntimeException("test exception")); - return result; - } - - /** - * Return the type of ID. - * - * @return byte value designating type. - */ - - public byte type() { - return (byte) encodedValue.charAt(0); - } - - /** - * Returns base 64 encoded value. - * - * @return String return value - */ - - @Override - public String toString() { - return encodedValue; - } - - /** - * returns the raw encoded value. Not cloned because it is a string. - */ - public String getID() { - return encodedValue; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/BinaryIDFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/BinaryIDFactory.java deleted file mode 100644 index f1266d38..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/BinaryIDFactory.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.binaryID; - - -/** - * A BinaryIDFactory generates a BinaryID id. BinaryIDs are used to uniquely - * identify objects such as peers, peer groups and pipes. - * - * @author Daniel Brookshier turbogeek@cluck.com - * @see net.jxta.id.ID - */ - -public class BinaryIDFactory { - - /** - * Returns a new BinaryID value. - * - * @return BinaryID returns a BinaryID. - */ - - public static BinaryID newBinaryID(byte type, byte data[], boolean lengthIncluded) { - return new BinaryID(type, data, lengthIncluded); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/CodatBinaryID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/CodatBinaryID.java deleted file mode 100644 index a0600672..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/CodatBinaryID.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.id.binaryID; - - -import net.jxta.peergroup.PeerGroupID; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.InputStream; -import java.net.URI; -import net.jxta.id.ID; - - -/** - * This class implements a Pipe ID. Each pipe is assigned a unique id. - * - * @author Daniel Brookshier turbogeek@cluck.com - * @see net.jxta.id.ID - * @see net.jxta.id.IDFactory - * @see net.jxta.peergroup.PeerGroupID - */ -public final class CodatBinaryID extends net.jxta.codat.CodatID { - - /** - * LOG object for this class. - */ - private final static transient Logger LOG = Logger.getLogger(CodatBinaryID.class.getName()); - - /** - * The id data - */ - protected String id; - - /** - * Used only internally - */ - protected CodatBinaryID() { - super(); - } - - /** - * Creates a ID from a string. Note that the ID is not currently validated. - * - * @param id Value of ID. - */ - - public CodatBinaryID(String id) { - super(); - this.id = id; - - } - - /** - * Constructor. Intializes contents from provided ID. - * - * @param id the ID data - */ - public CodatBinaryID(BinaryID id) { - super(); - this.id = id.getID(); - } - - /** - * Constructor. Creates a PipeID. A PeerGroupID is provided. Note that only - * the peer group's primary node is used to build this node. We don't want - * to be appending great grand parents. - * - * @param parent the group to which this will belong. - * @param data DOCUMENT ME! - * @param lengthIncluded DOCUMENT ME! - */ - public CodatBinaryID(net.jxta.peergroup.PeerGroupID parent, byte[] data, boolean lengthIncluded) { - this(); - - String parentStr = IDFormat.childGroup(parent); - - id = BinaryIDFactory.newBinaryID(BinaryID.flagPipeID, data, lengthIncluded).getID() + "." + parentStr.replace('-', '.'); - } - - public CodatBinaryID(PeerGroupID groupID, InputStream in) { - // this( groupID ); - net.jxta.id.IDFactory.newCodatID(groupID); - // setHash( in ); - } - - public CodatBinaryID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed, InputStream in) { - this(groupID, seed, false); - - // setHash( in ); - } - - /* - private void setHash( InputStream in ) throws IOException { - MessageDigest dig = null; - try { - dig = MessageDigest.getInstance( "SHA" ); - } catch( NoSuchAlgorithmException caught ) { - dig = null; - } - - if (dig == null) { - throw new ProviderException("SHA1 digest algorithm found"); - } - - dig.reset(); - - do { - int nextByte = in.read(); - if( nextByte == -1 ) - break; - - dig.update( (byte) nextByte); - } - while( true ); - - in.close(); - - try { - byte [] result = dig.digest( ); - for( int eachByte = 0; eachByte < CodatID.hashSize; eachByte++ ) - id.bytes[eachByte + CodatID.codatHashOffset] = result[eachByte]; - } catch( Throwable e ) { - // we convert this to an IO Exception to keep the number of - // down. - throw new IOException( "Digest algorithm could not complete : " + e.getMessage() ); - } - } - */ - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - return target instanceof CodatBinaryID && getUniqueValue().equals(((CodatBinaryID) target).getUniqueValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return getUniqueValue().hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - if (null == id) { - return ID.nullID.getUniqueValue(); - } - - return getIDFormat() + "-" + id; - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.id.ID getPeerGroupID() { - try { - if (id == null) { - return net.jxta.id.ID.nullID; - } - String idd = id; - int parentStart = idd.indexOf('.'); - - if (parentStart != -1) { - idd = idd.substring(parentStart + 1); - } else { - return null; - } - - URI url = new URI("urn:jxta:" + idd.replace('.', '-')); - net.jxta.peergroup.PeerGroupID peerGroupID = (net.jxta.peergroup.PeerGroupID) net.jxta.id.IDFactory.fromURI(url); - - return peerGroupID; - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("cannot convert sub group. ID value = " + id); - } - return null; - - } - } - - /** - * returns the coded ID without the binaryid tag. - * - * @return Returns the raw string used to create the urn! - */ - protected String getID() { - return id; - } - - /** - * {@inheritDoc} - * Binary ID only supports static - */ - @Override - public boolean isStatic() { - return true; - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/DigestTool.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/DigestTool.java deleted file mode 100644 index 101def96..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/DigestTool.java +++ /dev/null @@ -1,417 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.binaryID; - - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.security.MessageDigest; - - -/** - * This is a utility class used to create pipe advertisement named and BinaryID for the pipeID to create - * a private address space that can be hosted in the public discovery system or sent over unencrypted - * channeds without revealing their intent or purpose.

            - *

            - * We use a one-way hashing algorythum to create an ID from private information like - * a user's social security number or a user's email address. - * We search for the pipe by with this private information securly by creating the - * matching hash using the same methods.

            - *

            - * The purpose of this system is to create a way to search - * for a pipe (or other BinaryID based system) without exposing the - * pipe owner's clearTextID while allowing for people that - * know what they are looking for to find the right pipe. The - * system also has the ability to create pipes that have a specific purpose. - * For example, the email address is appended with a function name. Say you - * have a pipe for messages and one for administrative purposes. You would - * supply the email and a string for the function. The same combination can be - * created by another peer to search for either of these pipes.

            - *

            - * This implementation uses the "SHA-1" algorythum. This was selected for relitive - * speed. It is used as a one-way conversion that cannot be reversed engineered to - * create the original string. This allows you to publish the hash without the - * possibility of the contents being decoded. This allows for public indexing of - * data that is only known by the parties involved.

            - *

            - * Note that this can also be used to generate safe password verification hash codes. - * Sample useage: - * - * String clearTextID = "turbogeek@cluck.com"; - * String function = "eventPipe"; - * System.out.println("clear text ID: "+clearTextID); - * System.out.println("function text: "+function); - * String digest1 = DigestID.generateHashString(clearTextID, function); - * String digest2 = DigestID.generateHashString(clearTextID); - * System.out.println("Digest1: '"+digest1+"'"); - * System.out.println("Digest2: '"+digest2+"'"); - * System.out.println("test1: "+DigestID.test(clearTextID, function,digest1)); - * System.out.println("test2: "+DigestID.test(clearTextID, digest2)); - * System.out.println("Digest1 != Digest2: "+DigestID.test(clearTextID, function,digest2)); - *

            - *

            - * To use an algorythum other than SHA-1, you will need stronger encyption. - * The BouncyCastle that comes with JXTA is just a minimum implimentation so - * a good choice is the normal bouncy castle (it is much larger, nearing a meg, - * which is why it is not a part of the normal JXTA distribution. The full version - * of bouncy includes SHA-128, SHA-256, SHA-384, and SHA-512.

            - *

            - * Here is how you create a provider from the full version of Bouncy. Once you do this, you can access the extended - * Digest ecryption levels. - * - * provider = new org.bouncycastle.jce.provider.BouncyCastleProvider(); - * System.out.println("provider:"+provider.getName()); - * Security.addProvider(provider); - *

            - * Security Note

            - *

            - * This class should have all of its fields and properties marked as 'final' to prevent overriding the default behavior. - * Failure to do so could allow a less scrupulous person to cause the BinaryID or hash codes to contain the original information. - * Note that the class itself is not final to allow for additional convienience methods to be added. There - * a no methods for creating ModuleClassBinaryID, ModuleSpecBinaryID, or CodatID because this is meant for general' - * use, not for extending platform (you can write your own using similar code).

            - * - * @author Daniel Brookshier turbogeek@cluck.com - * @version $Revision$ - */ -public class DigestTool { - private final static transient Logger LOG = Logger.getLogger(DigestTool.class.getName()); - - /** - * varaible used for conditional compile of debug printing. - */ - public static final boolean debug = true; - - /** - * Defualt SHA-1 digest algorithm type. This is a 20 byte hash function (note: that MD5 is only 16 so we don't use it). - */ - public static final String SHAOne = "SHA-1"; - - /** - * SHA-128 digest algorithm type. This is a 128 bit hash function (note: must have another provider registered to use). - */ - public static final String SHA128 = "SHA-128"; - - /** - * SHA-256 digest algorithm type. This is a 256 bit hash function (note: must have another provider registered to use). - */ - public static final String SHA256 = "SHA-256"; - - /** - * SHA-384 digest algorithm type. This is a 384 bit hash function (note: must have another provider registered to use). - */ - public static final String SHA384 = "SHA-384"; - - /** - * SHA-512 digest algorithm type. This is a 512 bit hash function (note: must have another provider registered to use). - */ - public static final String SHA512 = "SHA-512"; - - /** - * Tilde character used to seperate candidate strings from a function. - */ - public final String functionSeperator = "~"; - String algorithmType; - - public DigestTool() { - algorithmType = SHAOne; - } - - public DigestTool(String algorithmType) { - this.algorithmType = algorithmType; - } - - /** - * Create a PipeID based on the BinaryID type with a digest of the clearTextID and function. - * - * @param peerGroupID Parent peer group ID. - * @param clearTextID String used as the significant part of the address - * @param function String used to diferentiate different clearTextID addresses (can be null). - * @return PipeBinaryID with the digest hash of the string: clearTextID+"~"+function. - */ - public final PipeBinaryID createPipeID(net.jxta.peergroup.PeerGroupID peerGroupID, String clearTextID, String function) { - byte[] digest = generateHash(clearTextID, function); - PipeBinaryID pipe = new PipeBinaryID(peerGroupID, digest, false); - - return pipe; - } - - /** - * Create a PeerGroupID based on the BinaryID type with a digest of the clearTextID and function. - * - * @param parentPeerGroupID Parent peer group ID. - * @param clearTextID String used as the significant part of the address - * @param function String used to diferentiate different clearTextID addresses (can be null). - * @return PeerGroupBinaryID with the digest hash of the string: clearTextID+"~"+function. - */ - public final PeerGroupBinaryID createPeerGroupID(net.jxta.peergroup.PeerGroupID parentPeerGroupID, String clearTextID, String function) { - byte[] digest = generateHash(clearTextID, function); - PeerGroupBinaryID peerGroupID = new PeerGroupBinaryID(parentPeerGroupID, digest, false); - - return peerGroupID; - } - - /** - * Create a PeerID based on the BinaryID type with a digest of the clearTextID and function. - * - * @param peerGroupID Parent peer group ID. - * @param clearTextID String used as the significant part of the address - * @param function String used to diferentiate different clearTextID addresses (can be null). - * @return PeerBinaryID with the digest hash of the string: clearTextID+"~"+function. - */ - public final PeerBinaryID createPeerID(net.jxta.peergroup.PeerGroupID peerGroupID, String clearTextID, String function) { - byte[] digest = generateHash(clearTextID, function); - PeerBinaryID peerID = new PeerBinaryID(peerGroupID, digest, false); - - return peerID; - } - - /** - * Creates a new instance of DigestPipe. Because this is a utility, - * this is private to prevent construction. - */ - - /** - * Generates a Base64 encoded string of an SHA-1 digest hash of the string: clearTextID.

            - * - * @param clearTextID A string that is to be hashed. This can be any string used for hashing or hiding data. - * @return Base64 encoded string containing the hash of the string: clearTextID. - */ - public final String generateHashString(String clearTextID) { - try { - java.io.StringWriter base64 = new java.io.StringWriter(); - net.jxta.impl.util.BASE64OutputStream encode = new net.jxta.impl.util.BASE64OutputStream(base64); - - encode.write(generateHash(clearTextID)); - encode.close(); - - return base64.toString(); - } catch (Exception failed) { - LOG.log(Level.SEVERE, "Unable to encode hash value.", failed); - throw new RuntimeException("Unable to encode hash value."); - } - } - - /** - * Generates a Base64 encoded string of an SHA-1 digest hash of the string: clearTextID+"-"+function or: clearTextID if function was blank.

            - * - * @param clearTextID A string that is to be hashed. This can be any string used for hashing or hiding data. - * @param function A function related to the clearTextID string. This is used to create a hash associated with clearTextID so that it is a uique code. - * @return Base64 encoded string containing the hash of the string: clearTextID+"-"+function or clearTextID if function was blank. - */ - public final String generateHashString(String clearTextID, String function) { - try { - java.io.StringWriter base64 = new java.io.StringWriter(); - net.jxta.impl.util.BASE64OutputStream encode = new net.jxta.impl.util.BASE64OutputStream(base64); - - encode.write(generateHash(clearTextID, function)); - encode.close(); - - return base64.toString(); - } catch (Exception failed) { - LOG.log(Level.SEVERE, "Unable to encode hash value.", failed); - throw new RuntimeException("Unable to encode hash value."); - } - } - - /** - * Generates a SHA-1 digest hash of the string: clearTextID.

            - * - * @param clearTextID A string that is to be hashed. This can be any string used for hashing or hiding data. - * @return String containing the hash of the string: clearTextID. - */ - public final byte[] generateHash(String clearTextID) { - return generateHash(clearTextID, null); - } - - /** - * Generates an SHA-1 digest hash of the string: clearTextID+"-"+function or: clearTextID if function was blank.

            - *

            - * Note that the SHA-1 used only creates a 20 byte hash.

            - * - * @param clearTextID A string that is to be hashed. This can be any string used for hashing or hiding data. - * @param function A function related to the clearTextID string. This is used to create a hash associated with clearTextID so that it is a uique code. - * @return array of bytes containing the hash of the string: clearTextID+"-"+function or clearTextID if function was blank. Can return null if SHA-1 does not exist on platform. - */ - public final byte[] generateHash(String clearTextID, String function) { - String id; - - if (function == null) { - id = clearTextID; - } else { - id = clearTextID + functionSeperator + function; - } - byte[] buffer = id.getBytes(); - - MessageDigest algorithm; - - try { - algorithm = MessageDigest.getInstance(algorithmType); - } catch (Exception e) { - LOG.log(Level.SEVERE, "Cannot load selected Digest Hash implementation", e); - return null; - } - - // Generate the digest. - algorithm.reset(); - algorithm.update(buffer); - - try { - byte[] digest1 = algorithm.digest(); - - return digest1; - } catch (Exception de) { - LOG.log(Level.SEVERE, "Failed to creat a digest.", de); - return null; - } - } - - /** - * Generates an SHA-1 digest hash of the string: clearTextID.

            - * - * @param function the function - * @param testHash test hash - * @param clearTextID A string that is to be hashed. This can be any string used for hashing or hiding data. - * @return String containing the hash of the string: clearTextID. - */ - public final boolean test(String clearTextID, String function, String testHash) { - String id = clearTextID + functionSeperator + function; - - return test(id, testHash); - - } - - /** - * Compares a clear text code or ID with a candidate hash code. - * This is used to confirm that the clearTextID can be successfully converted to the hash. - * - * @param clearTextID A string that is to be hashed. This can be any string used for hashing or hiding data. - * @param testHash A string of hashed string. - * @return true if the hash created from clearTextID is equal to the testHash string.Can return false if SHA-1 does not exist on platform. - */ - public final boolean test(String clearTextID, String testHash) { - - byte[] digest1 = generateHash(clearTextID); - byte[] digest2; - - try { - java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); - net.jxta.impl.util.BASE64InputStream decoder = new net.jxta.impl.util.BASE64InputStream( - new java.io.StringReader(testHash)); - - while (true) { - int c = decoder.read(); - - if (-1 == c) { - break; - } - - bos.write(c); - } - - digest2 = bos.toByteArray(); - } catch (Exception e) { - LOG.log(Level.SEVERE, "Failed to create a digest.", e); - return false; - } - - if (digest1.length != digest2.length) { - // Not a match! because of length. - return false; - } - - for (int i = 0; i < digest1.length; i++) { - if (digest1[i] != digest2[i]) { - // Not a match because of byte:"+i+" did not match - return false; - } - } - - // Match was ok - return true; - } - - /** - * Compares a clear text code or ID with a candidate hash code. - * This is used to confirm that the clearTextID can be successfully converted to the hash. - * - * @param clearTextID A string that is to be hashed. This can be any string used for hashing or hiding data. - * @param testHash A string of hashed string. - * @return true if the hash created from clearTextID is equal to the testHash string.Can return false if SHA-1 does not exist on platform. - */ - public final boolean test(String clearTextID, byte[] testHash) { - - byte[] digest1 = generateHash(clearTextID); - - if (digest1.length != testHash.length) { - // Not a match! because of length. - return false; - } - - for (int i = 0; i < testHash.length; i++) { - if (digest1[i] != testHash[i]) { - // Not a match because of byte:"+i+" did not match - return false; - } - } - - // Match was ok - return true; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/IDFormat.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/IDFormat.java deleted file mode 100644 index 480115da..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/IDFormat.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.binaryID; - - -import java.util.logging.Logger; - - -/** - * The 'BinaryID' format is a general purpose JXTA ID Format. It implements all of - * the six standard ID types. It was originally created for the Java 2 SE - * reference implementation. The 'BinaryID' format uses randomly generated BinaryIDs - * as the mechanism for generating canonical values for the ids it provides. - * - * @author Daniel Brookshier turbogeek@cluck.com - */ -public class IDFormat { - - /** - * LOG4J Logger - */ - private final static transient Logger LOG = Logger.getLogger(IDFormat.class.getName()); - - /** - * This table maps our local private versions of the well known ids to the - * globally known version. - */ - - final static Object[][] wellKnownIDs = { - { net.jxta.peergroup.PeerGroupID.worldPeerGroupID, net.jxta.impl.id.UUID.IDFormat.worldPeerGroupID} - , - { net.jxta.peergroup.PeerGroupID.defaultNetPeerGroupID, net.jxta.impl.id.UUID.IDFormat.defaultNetPeerGroupID} - }; - - /** - * The instantiator for this ID Format which is used by the IDFactory. - */ - public static final net.jxta.impl.id.binaryID.Instantiator INSTANTIATOR = new net.jxta.impl.id.binaryID.Instantiator(); - - /** - * Private Constructor. This class cannot be instantiated. - */ - private IDFormat() {} - - /** - * Translate from well known ID to our locally encoded versions. - * - * @param input the id to be translated. - * @return the translated ID or the input ID if no translation was needed. - */ - - static net.jxta.id.ID translateFromWellKnown(net.jxta.id.ID input) { - for (int eachWellKnown = 0; eachWellKnown < wellKnownIDs.length; eachWellKnown++) { - net.jxta.id.ID aWellKnown = (net.jxta.id.ID) wellKnownIDs[eachWellKnown][0]; - - if (aWellKnown.equals(input)) { - return (net.jxta.id.ID) wellKnownIDs[eachWellKnown][1]; - } - } - - return input; - } - - /** - * Translate from locally encoded versions to the well known versions. - * - * @param input the id to be translated. - * @return the translated ID or the input ID if no translation was needed. - */ - - static net.jxta.id.ID translateToWellKnown(net.jxta.id.ID input) { - for (int eachWellKnown = 0; eachWellKnown < wellKnownIDs.length; eachWellKnown++) { - net.jxta.id.ID aLocalEncoding = (net.jxta.id.ID) wellKnownIDs[eachWellKnown][1]; - - if (aLocalEncoding.equals(input)) { - return (net.jxta.id.ID) wellKnownIDs[eachWellKnown][0]; - } - } - - return input; - } - - /** - * Utility method used to strip only the most significant peer group ID. - * This prevents us from continiously appending grandparents to each child. - *

            - *

            - * This method is used in PipeID and PeerID. - *

            - * - * @param peerGroupID Peer group ID to pull the child from. - * @return Child of the peer group. - */ - public static String childGroup(net.jxta.peergroup.PeerGroupID peerGroupID) { - String parentStr = (String) peerGroupID.getUniqueValue(); - // Child is the first ID - int first = parentStr.indexOf('.'); - String child = null; - - if (first != -1) { - child = parentStr.substring(0, first); - - } else { - child = parentStr; - } - return child; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/Instantiator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/Instantiator.java deleted file mode 100644 index f4934674..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/Instantiator.java +++ /dev/null @@ -1,395 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.binaryID; - - -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.security.SecureRandom; -import java.util.Random; -import java.util.logging.Level; -import java.util.logging.Logger; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.UnknownServiceException; - -import net.jxta.peergroup.PeerGroupID; - - -/** - * ID Factory for the binary ID type. All identifiers in this type are prefixed by "binaryid". - * - * @author Daniel Brookshier turbogeek@cluck.com - */ - -public final class Instantiator implements net.jxta.id.IDFactory.URIInstantiator { - - /** - * LOG object for this class. - */ - private final static transient Logger LOG = Logger.getLogger(Instantiator.class.getName()); - - /** - * Our ID Format - */ - final static String BinaryIDEncoded = "binaryid"; - - /** - * Random generator used for ID creation where a seed (idValue) is not provided. - */ - private static final Random randNumGenerator = new SecureRandom(); - - /** - * {@inheritDoc} - */ - public String getSupportedIDFormat() { - return BinaryIDEncoded; - } - - /** - * {@inheritDoc} - */ - public net.jxta.id.ID fromURL(URL source) throws MalformedURLException, UnknownServiceException { - - // check the protocol - if (!net.jxta.id.ID.URIEncodingName.equalsIgnoreCase(source.getProtocol())) { - throw new UnknownServiceException("URI protocol type was not as expected."); - } - - String encoded = source.getFile(); - - int colonAt = encoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new UnknownServiceException("URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(encoded.substring(0, colonAt))) { - throw new UnknownServiceException("URN namespace was not as expected."); - } - - // skip the namespace portion and the colon - encoded = encoded.substring(colonAt + 1); - - try { - return fromURNNamespaceSpecificPart(encoded); - } catch (URISyntaxException failed) { - MalformedURLException failure = new MalformedURLException("Failure parsing URL"); - - failure.initCause(failed); - - throw failure; - } - } - - /** - * {@inheritDoc} - */ - public net.jxta.id.ID fromURI(URI source) throws URISyntaxException { - - // check the protocol - if (!net.jxta.id.ID.URIEncodingName.equalsIgnoreCase(source.getScheme())) { - throw new URISyntaxException(source.toString(), "URI scheme was not as expected."); - } - - String decoded = source.getSchemeSpecificPart(); - - int colonAt = decoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new URISyntaxException(source.toString(), "URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(decoded.substring(0, colonAt))) { - throw new URISyntaxException(source.toString() - , - "URN namespace was not as expected. (" + net.jxta.id.ID.URNNamespace + "!=" + decoded.substring(0, colonAt) - + ")"); - } - - // skip the namespace portion and the colon - decoded = decoded.substring(colonAt + 1); - - return fromURNNamespaceSpecificPart(decoded); - } - - /** - * {@inheritDoc} - */ - public net.jxta.id.ID fromURNNamespaceSpecificPart(String encoded) throws URISyntaxException { - int dashAt = encoded.indexOf('-'); - - // there's a dash, right? - if (-1 == dashAt) { - throw new URISyntaxException(encoded, "URN Encodingtype was missing."); - } - - if (!encoded.substring(0, dashAt).equals(BinaryIDEncoded)) { - throw new URISyntaxException(encoded - , - "JXTA id format was not as expected. Should have been BinaryIDEncoded found:" + encoded.substring(0, dashAt)); - } - - // skip the dash - encoded = encoded.substring(dashAt + 1); - // check that the length is long enough - if (encoded.length() < 1) { - throw new URISyntaxException(encoded, "URN does not contain enough chars. Must have at least one byte"); - } - BinaryID id = new BinaryID(encoded); - net.jxta.id.ID result = null; - - switch (id.type()) { - - case BinaryID.flagCodatID: - result = new CodatBinaryID(encoded); - break; - - case BinaryID.flagPeerGroupID: - result = new PeerGroupBinaryID(encoded); - if (PeerGroupID.worldPeerGroupID.equals(result)) { - result = net.jxta.peergroup.PeerGroupID.worldPeerGroupID; - } - break; - - case BinaryID.flagPeerID: - result = new PeerBinaryID(encoded); - break; - - case BinaryID.flagPipeID: - result = new PipeBinaryID(encoded); - break; - - case BinaryID.flagModuleClassID: - result = new ModuleClassBinaryID(encoded); - break; - - case BinaryID.flagModuleSpecID: - result = new ModuleSpecBinaryID(encoded); - break; - - default: - throw new URISyntaxException(encoded, "jxta ID type not recognized"); - } - - return result; - } - - /** - * Utility to create a random array of bits to be used when a random value is required. - */ - private byte[] randomID() { - byte[] randBuf16 = new byte[16]; - - randNumGenerator.nextBytes(randBuf16); - - return randBuf16; - } - - /** - * {@inheritDoc} - * - * @throws UnsupportedOperationException This form is not supported. Use CODAT from UUID package instead. - */ - public net.jxta.codat.CodatID newCodatID(final net.jxta.peergroup.PeerGroupID groupID) { - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new net.jxta.impl.id.binaryID.CodatBinaryID(parentGroupID, randomID(), false); - // throw new UnsupportedOperationException("This form is not supported. Use CODAT from UUID package instead."); - } - - /** - * {@inheritDoc} - * - * @throws UnsupportedOperationException This form is not supported. Use CODAT from UUID package instead. - */ - public net.jxta.codat.CodatID newCodatID(final net.jxta.peergroup.PeerGroupID groupID, byte[] seed) { - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new net.jxta.impl.id.binaryID.CodatBinaryID(parentGroupID, seed, false); - } - - /** - * {@inheritDoc} - * - * @throws UnsupportedOperationException This form is not supported. Use CODAT from UUID package instead. - */ - public net.jxta.codat.CodatID newCodatID(final net.jxta.peergroup.PeerGroupID groupID, InputStream in) throws IOException { - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new net.jxta.impl.id.binaryID.CodatBinaryID(parentGroupID, randomID(), false); - } - - /** - * {@inheritDoc} - * - * @throws UnsupportedOperationException This form is not supported. Use CODAT from UUID package instead. - */ - public net.jxta.codat.CodatID newCodatID(final net.jxta.peergroup.PeerGroupID groupID, byte[] idValue, InputStream in) throws IOException { - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new net.jxta.impl.id.binaryID.CodatBinaryID(parentGroupID, idValue, false); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peer.PeerID newPeerID(final net.jxta.peergroup.PeerGroupID groupID) { - LOG.log(Level.SEVERE, "random peer created", new RuntimeException()); - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new net.jxta.impl.id.binaryID.PeerBinaryID(parentGroupID, randomID(), false); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peer.PeerID newPeerID(final net.jxta.peergroup.PeerGroupID groupID, byte[] idValue) { - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new net.jxta.impl.id.binaryID.PeerBinaryID(parentGroupID, idValue, false); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID() { - return net.jxta.id.IDFactory.newPeerGroupID(randomID()); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(byte[] idValue) { - return new PeerGroupBinaryID(idValue, false); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(net.jxta.peergroup.PeerGroupID parent) { - LOG.log(Level.SEVERE, "random peergroup created", new RuntimeException()); - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(parent); - - return net.jxta.id.IDFactory.newPeerGroupID(parentGroupID, randomID()); - } - - /** - * {@inheritDoc} - */ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(net.jxta.peergroup.PeerGroupID parent, byte[] idValue) { - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(parent); - - return new PeerGroupBinaryID(parentGroupID, idValue, false); - } - - /** - * {@inheritDoc} - */ - public net.jxta.pipe.PipeID newPipeID(final net.jxta.peergroup.PeerGroupID groupID) { - PeerGroupID parentGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return net.jxta.id.IDFactory.newPipeID(parentGroupID, randomID()); - } - - /** - * {@inheritDoc} - */ - public net.jxta.pipe.PipeID newPipeID(final net.jxta.peergroup.PeerGroupID groupID, byte[] idValue) { - PeerGroupID peerGroupID = (PeerGroupID) IDFormat.translateFromWellKnown(groupID); - - return new PipeBinaryID(peerGroupID, idValue, false); - } - - /** - * {@inheritDoc} - * - * @throws UnsupportedOperationException This form is not supported because a binary ID is meant to be created with a random ID. - */ - public net.jxta.platform.ModuleClassID newModuleClassID() { - throw new UnsupportedOperationException( - "This form is not supported because a binary ID is meant to be created with a random ID. Use UUID package instead."); - } - - /** - * {@inheritDoc} - * - * @throws UnsupportedOperationException This form is not supported because a binary ID is meant to be created with a random ID. - */ - public net.jxta.platform.ModuleClassID newModuleClassID(final net.jxta.platform.ModuleClassID classID) { - throw new UnsupportedOperationException( - "This form is not supported because a binary ID is meant to be created with a random ID. Use UUID package instead."); - } - - /** - * {@inheritDoc} - * - * @throws UnsupportedOperationException This form is not supported because a binary ID is meant to be created with a random ID. Use UUID instead. - */ - public net.jxta.platform.ModuleSpecID newModuleSpecID(final net.jxta.platform.ModuleClassID classID) { - throw new UnsupportedOperationException( - "This form is not supported because a binary ID is meant to be created with a random ID. Use UUID package instead."); - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/ModuleClassBinaryID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/ModuleClassBinaryID.java deleted file mode 100644 index 596e83d2..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/ModuleClassBinaryID.java +++ /dev/null @@ -1,326 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.binaryID; - - -import net.jxta.peergroup.PeerGroupID; -import java.util.logging.Logger; -import net.jxta.id.ID; - - -/** - * This interface defines a Module Class Identifier. - * A ModuleClassID uniquely identifies a particular local behaviour, that is, - * a specific API for each execution environment for which an implementation - * exists. - *

            - *

            - * A ModuleClassID has two components: A base class identifier, and a role identifier. - * The role identifier may be zero. By convention the API uses the ModuleClassID with - * a zero role identifier to designate the base class in contexts where only the base class - * is significant. Nonetheless, a ModuleClassID with a zero role identifier is a valid - * ModulesClassID wherever a full ModuleClassID is expected. In many cases, only one role - * in a given class is ever used. Using role zero in such cases is an optimization because - * it may make the string representation of the ModuleClassID shorter. - *

            - *

            - * Each service of a group, that is, the role it plays in the group, is uniquely identified - * per the group definition. - * This identifier may be used by other modules in the group to designate this one, or by the service - * itself to identify its parameters in a PeerAdvertisement. In addition, by combining its - * PeerGroupID with its own ModuleClassID, a service may create a predictible identifier unique - * on their peer, suitable for registering listeners with the EndpointService or other services - * with similar listener interfaces. - *

            - *

            - * The standard PeerGroup implementation of the java reference implementation - * assigns to each service its ModuleClassID as its unique service identifier. Most of the - * times this ModuleClassID is a base classID, but groups that use the same Module Class - * for more than one service (same behaviour but playing a different role in the group, such - * as, for example, a data base engine with a different data base), may define multiple roles - * identified by the same base class identifier but different role identifiers. The standard - * PeerGroup implementation of the java reference implementation has the notion of main - * application: a default application which may be started automatically upon instantiating - * the group. This application implements Module and, therefore, is assigned a ModuleClassID. - * However applications are not expected to play any specific role in the group. As a result, they - * are assigned a role identifier allocated at run-time as need to garantee local unicity. As - * a result main applications cannot expect a predictible ClassID. - *

            - *

            - * A ModuleClassID is optionaly described by a published ModuleClassAdvertisement. - *

            - *

            - * There may be any number of embodiements of a module class. These are module - * specifications. A module specification represent the network behaviour of a - * module while its class represents its local behaviour. Different groups - * may use a common subset of classes, for example, the basic set defined by the platform - * should always be part of it. Each group may use different and network-incompatible - * specifications for common classes, optimized for various purposes. The local API of a - * given class on a given JXTA implementation will be invariant per the spec being used. - * Therefore, the difference will be transparent to applications which do not depend - * on the possibly different quality of service. - *

            - *

            - * A ModuleSpecID embeds a base class identifier, which permits to verify that - * a given Module specification is suitable for its intended use. - * - * @author Daniel Brookshier turbogeek@cluck.com - * @see net.jxta.peergroup.PeerGroup - * @see net.jxta.platform.Module - * @see net.jxta.platform.ModuleClassID - * @see net.jxta.protocol.PeerAdvertisement - * @see net.jxta.protocol.ModuleSpecAdvertisement - * @see net.jxta.protocol.ModuleClassAdvertisement - * @see net.jxta.endpoint.EndpointService - * @see net.jxta.id.ID - */ - -public final class ModuleClassBinaryID extends net.jxta.platform.ModuleClassID { - - /** - * Log4J categorgy - */ - private final static transient Logger LOG = Logger.getLogger(ModuleClassBinaryID.class.getName()); - - /** - * The id data - */ - protected BinaryID classID; - protected BinaryID parentClassID; - protected BinaryID roleID; - protected PeerGroupID peerGroupID; - - /** - * Constructor. - * Intializes contents from provided ID. - * - * @param id the ID data - * @since JXTA 1.0 - */ - protected ModuleClassBinaryID(String id) { - super(); - int start = id.indexOf('-'); - int parent = id.indexOf(start + 1, '-'); - int role = id.indexOf(id.indexOf(parent + 1, '-') + 1, '-'); - int group = id.indexOf(id.indexOf(role + 1, '-') + 1, '-'); - - classID = new BinaryID(id.substring(group + 1, parent)); - parentClassID = new BinaryID(id.substring(parent + 1, role)); - roleID = new BinaryID(id.substring(role + 1, group)); - peerGroupID = new PeerGroupBinaryID(new BinaryID(id.substring(group + 1))); - } - - /** - * Constructor. - * Creates a ModuleClassID in a given class, with a given class unique id. - * A BinaryID of a class and another BinaryID are provided. - * - * @param parentClassID the class to which this will belong. - * @param roleID the unique id of this role in that class. - * @param peerGroupID the peer group ID - * @param classID the class ID - */ - protected ModuleClassBinaryID(BinaryID classID, BinaryID parentClassID, BinaryID roleID, PeerGroupID peerGroupID) { - super(); - this.classID = classID; - this.parentClassID = parentClassID; - this.roleID = roleID; - this.peerGroupID = peerGroupID; - } - - protected ModuleClassBinaryID(BinaryID classID, BinaryID parentClassID, BinaryID roleID, BinaryID peerGroupID) { - super(); - this.classID = classID; - this.parentClassID = parentClassID; - this.roleID = roleID; - this.peerGroupID = new PeerGroupBinaryID(peerGroupID); - } - - /** - * Constructor for creating a new ModuleClassID. A new class BinaryID is - * created. The role ID is left null. This is the only way to create - * a new class without supplying a new BinaryID explicitly. - * To create a new role in an existing class, one must use one of - * the other constructors. - * Note that a null role is just as valid as any other, it just has a - * shorter string representation. So it is not mandatory to create a new - * role in a new class. - * - * @since JXTA 1.0 - */ - public ModuleClassBinaryID() { - this(new BinaryID(BinaryID.flagModuleClassID), new BinaryID(BinaryID.flagModuleClassID) - , - new BinaryID(BinaryID.flagModuleClassRoleID), new BinaryID(BinaryID.flagPeerGroupID)); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (!(target instanceof ModuleClassBinaryID)) { - return false; - } - - ModuleClassBinaryID targetObj = (ModuleClassBinaryID) target; - - return this.classID.equals(targetObj.getClassID()) && this.parentClassID.equals(targetObj.getBaseClass()) - && this.roleID.equals(targetObj.getRoleID()) && this.peerGroupID.equals(targetObj.getPeerGroupID()); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return getUniqueValue().hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + classID.getID() + "-" + parentClassID.getID() + "-" + roleID.getID() + "-" - + peerGroupID.getUniqueValue(); - } - - /** - * Returns the peer group ID - * - * @return the peer group ID - */ - public net.jxta.id.ID getPeerGroupID() { - return peerGroupID; - } - - /** - * returns the coded ID without the binaryid tag. - * - * @return string of the contents - */ - protected String getID() { - return classID.getID() + "*" + parentClassID.getID() + "*" + roleID.getID() + "*" + peerGroupID.getUniqueValue(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.platform.ModuleClassID getBaseClass() { - return new ModuleClassBinaryID(parentClassID, new BinaryID(), new BinaryID(), new BinaryID()); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isOfSameBaseClass(net.jxta.platform.ModuleClassID classId) { - return getClass().equals(((ModuleClassBinaryID) classId).getClass()); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isOfSameBaseClass(net.jxta.platform.ModuleSpecID specId) { - return getBaseClassID().equals(((ModuleSpecBinaryID) specId).getBaseClassID()); - } - - /** - * get the class' unique id - * - * @return BinaryID module class' unique id - * @since JXTA 1.0 - */ - public BinaryID getClassID() { - return classID; - } - - /** - * get the role unique id - * - * @return Module role unique id. - * @since JXTA 1.0 - */ - public BinaryID getRoleID() { - return roleID; - } - - /** - * Getter for property parentClassID. - * - * @return Value of property parentClassID. - */ - public BinaryID getBaseClassID() { - return parentClassID; - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/ModuleSpecBinaryID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/ModuleSpecBinaryID.java deleted file mode 100644 index ca1f2108..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/ModuleSpecBinaryID.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.binaryID; - - -import java.util.logging.Logger; - - -/** - * A ModuleSpecID uniquely identifies a particular network behaviour - * (wire protocol and choregraphy) that may be embodied by a Jxta Module. - * There may be any number of implementations of a given SpecID. All - * such implementations are assumed to be network compatible. - *

            - *

            - * The Specification that corresponds to a given ModuleSpecID may be published - * in a ModuleSpecAdvertisement. This advertisement is uniquely identified by - * the ModuleSpecID that it describes. - *

            - *

            - * The various implementations of a given SpecID may be published in - * ModuleImplAdvertisements. These advertisements are identified by the - * ModuleSpecID that they implement and a compatibility statement. - * ModuleImplAdvertisements baring the same SpecID and compatibility statement - * are theorethicaly interchangeable. However they may be subsequently discriminated - * by a Description element. - *

            - *

            - * A ModuleSpecID embeds a ModuleClassID which uniquely identifies a base Module - * class. A base module class defines a local behaviour and one API per compatible - * JXTA implementation. - *

            - *

            - * A ModuleSpecID therefore uniquely identifies an abstract module, of which an - * implementation compatible with the local JXTA implementation may be located and - * instantiated. - *

            - *

            - * In the standard PeerGroup implementation of the java reference implementation - * the various services are specified as a list of ModuleSpecID, for each of which - * the group locates and loads an implementation as part of the group's - * initialization. - * - * @author Daniel Brookshier turbogeek@cluck.com - * @see net.jxta.peergroup.PeerGroup - * @see net.jxta.platform.Module - * @see net.jxta.platform.ModuleClassID - * @see net.jxta.protocol.ModuleSpecAdvertisement - * @see net.jxta.protocol.ModuleImplAdvertisement - * @see net.jxta.id.ID - * @see net.jxta.document.Advertisement - */ - -public final class ModuleSpecBinaryID extends net.jxta.platform.ModuleSpecID { - - /** - * Log4J categorgy - */ - private final static transient Logger LOG = Logger.getLogger(ModuleSpecBinaryID.class.getName()); - - protected BinaryID classID; - protected BinaryID baseClassID; - protected BinaryID specID; - - /** - * Constructor. Used only internally. - * - * @since JXTA 1.0 - */ - protected ModuleSpecBinaryID() { - super(); - specID = new BinaryID(BinaryID.flagModuleSpecID); - classID = new BinaryID(BinaryID.flagModuleClassID); - baseClassID = new BinaryID(BinaryID.flagModuleClassID); - } - - ; - - /** - * Constructor. - * Intializes contents from provided ID. - * - * @param id the ID data - * @since JXTA 1.0 - */ - protected ModuleSpecBinaryID(String id) { - super(); - int start = id.indexOf('-'); - int parent = id.indexOf(start + 1, '-'); - int spec = id.indexOf(id.indexOf(parent + 1, '-') + 1, '-'); - - classID = new BinaryID(id.substring(start + 1, parent)); - baseClassID = new BinaryID(id.substring(parent + 1, spec)); - specID = new BinaryID(id.substring(parent + 1)); - } - - /** - * Constructor. - * Creates a ModuleSpecID in a given class, with a given class unique id. - * A BinaryID of a class and another BinaryID are provided. - * - * @param classID the class to which this will belong. - * @param baseClassID the unique id of this spec in that class. - * @param specID the spec ID - */ - protected ModuleSpecBinaryID(BinaryID classID, BinaryID baseClassID, BinaryID specID) { - this.classID = classID; - this.baseClassID = baseClassID; - this.specID = specID; - } - - /* - * Official constructors. No mention of BinaryID. - */ - - /** - * Creates a new ModuleSpecID in a given class. A ModuleClassID is - * provided. A new SpecID in that class is created. - * - * @since JXTA 1.0 - * - * @param classID the class to which this will belong. - */ - - /* - public ModuleSpecID( net.jxta.platform.ModuleClassID moduleClassID ) { - this.classID = moduleClassID.getClassID(); - this.baseClassID = getBaseClassID(); - this.specID = getSpecID(); - } - */ - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (!(target instanceof ModuleSpecBinaryID)) { - return false; - } - - ModuleSpecBinaryID targetObj = (ModuleSpecBinaryID) target; - - return classID.equals(targetObj.getClassID()) && baseClassID.equals(targetObj.getBaseClassID()) - && specID.equals(targetObj.getSpecID()); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return getUniqueValue().hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - return getIDFormat() + "-" + classID + "-" + baseClassID + "_" + specID; - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.platform.ModuleClassID getBaseClass() { - return new ModuleClassBinaryID(baseClassID, new BinaryID(BinaryID.flagModuleClassID) - , - new BinaryID(BinaryID.flagModuleSpecID), new BinaryID(BinaryID.flagModuleSpecID)); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isOfSameBaseClass(net.jxta.platform.ModuleClassID classId) { - return baseClassID.equals(classId.getBaseClass()); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isOfSameBaseClass(net.jxta.platform.ModuleSpecID specId) { - return getClassID().equals(((ModuleSpecBinaryID) specId).getClassID()); - } - - /** - * Getter for property classID. - * - * @return Value of property classID. - */ - public net.jxta.impl.id.binaryID.BinaryID getClassID() { - return classID; - } - - /** - * Getter for property baseClassID. - * - * @return Value of property baseClassID. - */ - public net.jxta.impl.id.binaryID.BinaryID getBaseClassID() { - return baseClassID; - } - - /** - * Getter for property specID. - * - * @return Value of property specID. - */ - public net.jxta.impl.id.binaryID.BinaryID getSpecID() { - return specID; - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/PeerBinaryID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/PeerBinaryID.java deleted file mode 100644 index 39dcc8c7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/PeerBinaryID.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.id.binaryID; - - -import java.net.URI; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; -import net.jxta.id.ID; - - -/** - * This class implements a PeerID. Each peer is assigned a unique peer id.UUID - * id are used to implement peer id. - * - * @see net.jxta.impl.id.UUID.UUID - * @see net.jxta.impl.id.UUID.UUIDFactory - */ -public final class PeerBinaryID extends net.jxta.peer.PeerID { - - /** - * LOG object form this class - */ - private final static transient Logger LOG = Logger.getLogger(PeerBinaryID.class.getName()); - - /** - * This is the id string used in the XML of the id. The format is TX0..Xn where T is the type and X0 through Xn are the base64 encoded id. - */ - private String id; - - /** - * Constructor. Used only internally. - */ - private PeerBinaryID() { - super(); - } - - /** - * Creates a ID from a string. Note that the ID is not currently validated. - * - * @param id Value of ID. - */ - - protected PeerBinaryID(String id) { - super(); - this.id = id; - - } - - /** - * Creates a new PeerID object. - * - * @param binaryID binary id to build the peerID from. - */ - public PeerBinaryID(BinaryID binaryID) { - id = binaryID.getID(); - } - - /** - * Constructor. Creates a PeerID. A PeerGroupID and BinaryID is provided. If - * the binary ID is not a pipe ID, the construcion will throw a runtime - * exception.

            - *

            - * Note that only the ID for the parent is obtained and not the - * parent and the grandparent. - * - * @param parent the group to which this will belong. - * @param data data byte array to be used as the id. - * @param lengthIncluded If true, the first byte in the data array is the length of the remaining bytes. - */ - public PeerBinaryID(net.jxta.peergroup.PeerGroupID parent, byte[] data, boolean lengthIncluded) { - this(); - - String parentStr = IDFormat.childGroup(parent); - - id = BinaryIDFactory.newBinaryID(BinaryID.flagPeerID, data, lengthIncluded).getID() + "." + parentStr.replace('-', '.'); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - return target instanceof PeerBinaryID && getUniqueValue().equals(((PeerBinaryID) target).getUniqueValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return getUniqueValue().hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - if (null == id) { - return ID.nullID.getUniqueValue(); - } - - return new StringBuilder().append(getIDFormat()).append("-").append(id).toString(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.id.ID getPeerGroupID() { - try { - if (id == null) { - return net.jxta.id.ID.nullID; - } - String idd = id; - int parentStart = idd.indexOf('.'); - - if (parentStart != -1) { - idd = idd.substring(parentStart + 1); - } else { - return null; - } - - URI url = new URI("urn:jxta:" + idd.replace('.', '-')); - net.jxta.peergroup.PeerGroupID peerGroupID = (net.jxta.peergroup.PeerGroupID) net.jxta.id.IDFactory.fromURI(url); - - return peerGroupID; - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("cannot convert sub group. ID value = " + id); - } - return null; - - } - } - - /** - * returns the coded ID without the binaryid tag. - * - * @return The raw ID. - */ - protected String getID() { - return id; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/PeerGroupBinaryID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/PeerGroupBinaryID.java deleted file mode 100644 index 59477bd5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/PeerGroupBinaryID.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.id.binaryID; - - -import java.net.URI; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; -import net.jxta.id.ID; - - -/** - * This class implements a PeerGroup ID. Each peer group is assigned a unique - * peer id.BinaryID id are used to implement peer group id. Because this id is - * built with BinaryID, pulling the parent group requires a little work. The - * parent group is the first id, with the second following, separated by a - * dash '-' character.

            - * - * @author Daniel Brookshier turbogeek@cluck.com - * @see net.jxta.id.ID - * @see net.jxta.id.IDFactory - * @see net.jxta.peergroup.PeerGroupID - */ -public final class PeerGroupBinaryID extends net.jxta.peergroup.PeerGroupID { - - /** - * LOG object for this class. - */ - private final static transient Logger LOG = Logger.getLogger(PeerGroupBinaryID.class.getName()); - - /** - * This is the id string used in the XML of the id. The format is TX0..Xn where T is the type and X0 through Xn are the base64 encoded id. - */ - protected String id; - - /** - * Constructor for creating a new PeerGroupID with a unique ID and a parent.

            - *

            - * Note that only the ID for the parent is obtained and not the - * parent and the grandparent. - * - * @param parent Parent peer group. - * @param data data byte array to be used as the id. - * @param lengthIncluded If true, the first byte in the data array is the length of the remaining bytes. - */ - public PeerGroupBinaryID(net.jxta.peergroup.PeerGroupID parent, byte[] data, boolean lengthIncluded) { - this(); - - String parentStr = IDFormat.childGroup(parent); - - if (parentStr != null) { - id = BinaryIDFactory.newBinaryID(BinaryID.flagPeerGroupID, data, lengthIncluded).getID() + "." - + parentStr.replace('-', '.'); - } else { - id = BinaryIDFactory.newBinaryID(BinaryID.flagPeerGroupID, data, lengthIncluded).getID(); - } - } - - /** - * Creates a ID from a string. Note that the ID is not currently validated. - * - * @param id Value of ID. - */ - - protected PeerGroupBinaryID(String id) { - super(); - this.id = id; - } - - /** - * Constructor for creating a new PeerGroupID with a unique ID and a parent. - * - * @param data DOCUMENT ME! - * @param lengthIncluded DOCUMENT ME! - */ - public PeerGroupBinaryID(byte[] data, boolean lengthIncluded) { - this(); - id = BinaryIDFactory.newBinaryID(BinaryID.flagPeerGroupID, data, lengthIncluded).getID(); - } - - /** - * Constructor for creating a new PeerGroupID. Note that this creates an - * invalid ID but is required for serialization. - */ - public PeerGroupBinaryID() { - super(); - } - - /** - * Constructor. Intializes contents from provided ID. This PeerGroupID has - * no parent. - * - * @param id the ID data - */ - public PeerGroupBinaryID(BinaryID id) { - super(); - this.id = id.getID(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - return target instanceof PeerGroupBinaryID && getUniqueValue().equals(((PeerGroupBinaryID) target).getUniqueValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return getUniqueValue().hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - if (null == id) { - return ID.nullID.getUniqueValue(); - } - - return getIDFormat() + "-" + id; - } - - /** - * {@inheritDoc} - */ - public net.jxta.id.ID getPeerGroupID() { - // convert to the generic world PGID as necessary - return IDFormat.translateToWellKnown(this); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.peergroup.PeerGroupID getParentPeerGroupID() { - net.jxta.peergroup.PeerGroupID result = null; - - try { - if (id == null) { - result = (net.jxta.peergroup.PeerGroupID) net.jxta.id.ID.nullID; - } - String idd = id; - int parentStart = idd.indexOf('.'); - - if (parentStart != -1) { - idd = idd.substring(parentStart + 1); - } else { - result = null; - } - URI url = new URI("urn:jxta:" + idd.replace('.', '-')); - net.jxta.peergroup.PeerGroupID peerGroupID = (net.jxta.peergroup.PeerGroupID) net.jxta.id.IDFactory.fromURI(url); - - result = (net.jxta.peergroup.PeerGroupID) IDFormat.translateToWellKnown(peerGroupID); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("cannot convert sub group. ID value = " + id); - } - result = null; - - } - // LOG.error("getParentPeerGroupID():"+result); - return result; - } - - /** - * returns the coded ID without the binaryid tag. - * - * @return The coded ID without the binaryid tag. - */ - protected String getID() { - return id; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/PipeBinaryID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/PipeBinaryID.java deleted file mode 100644 index 0ffe37ef..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/PipeBinaryID.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.id.binaryID; - - -import java.net.URI; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; -import net.jxta.id.ID; - - -/** - * This class implements a Pipe ID. Each pipe is assigned a unique id. - * - * @author Daniel Brookshier turbogeek@cluck.com - * @see net.jxta.id.ID - * @see net.jxta.id.IDFactory - * @see net.jxta.peergroup.PeerGroupID - */ -public final class PipeBinaryID extends net.jxta.pipe.PipeID { - - /** - * LOG object for this class. - */ - private final static transient Logger LOG = Logger.getLogger(PipeBinaryID.class.getName()); - - /** - * The id data - */ - protected String id; - - /** - * Used only internally - */ - protected PipeBinaryID() { - super(); - } - - /** - * Creates a ID from a string. Note that the ID is not currently validated. - * - * @param id Value of ID. - */ - - protected PipeBinaryID(String id) { - super(); - this.id = id; - - } - - /** - * Constructor. Intializes contents from provided ID. - * - * @param id the ID data - */ - PipeBinaryID(BinaryID id) { - super(); - this.id = id.getID(); - } - - /** - * Constructor. Creates a PipeID. A PeerGroupID is provided. Note that only - * the peer group's primary node is used to build this node. We don't want - * to be appending great grand parents. - * - * @param parent the group to which this will belong. - * @param data DOCUMENT ME! - * @param lengthIncluded DOCUMENT ME! - */ - public PipeBinaryID(net.jxta.peergroup.PeerGroupID parent, byte[] data, boolean lengthIncluded) { - this(); - - String parentStr = IDFormat.childGroup(parent); - - id = BinaryIDFactory.newBinaryID(BinaryID.flagPipeID, data, lengthIncluded).getID() + "." + parentStr.replace('-', '.'); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - return target instanceof PipeBinaryID && getUniqueValue().equals(((PipeBinaryID) target).getUniqueValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return getUniqueValue().hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getIDFormat() { - return IDFormat.INSTANTIATOR.getSupportedIDFormat(); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getUniqueValue() { - if (null == id) { - return ID.nullID.getUniqueValue(); - } - - return new StringBuilder().append(getIDFormat()).append("-").append(id).toString(); - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.id.ID getPeerGroupID() { - try { - if (id == null) { - return net.jxta.id.ID.nullID; - } - String idd = id; - int parentStart = idd.indexOf('.'); - - if (parentStart != -1) { - idd = idd.substring(parentStart + 1); - } else { - return null; - } - - URI url = new URI("urn:jxta:" + idd.replace('.', '-')); - net.jxta.peergroup.PeerGroupID peerGroupID = (net.jxta.peergroup.PeerGroupID) net.jxta.id.IDFactory.fromURI(url); - - return peerGroupID; - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "cannot convert sub group. ID value = " + id, e); - } - return null; - } - } - - /** - * returns the coded ID without the binaryid tag. - * - * @return Returns the raw string used to create the urn! - */ - protected String getID() { - return id; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/package.html deleted file mode 100644 index 7556f18c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/binaryID/package.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - -The 'binary' format is a general purpose JXTA ID Format. It implements Peer, -group, and pipe ID types. The remaining types are supported, but not -guarenteed (CODAT not supported at all yet).

            - - The DigestTool class is probably the main entry point for most developers. - The class creates various BinaryID types with an SHA digest hashing. The - intent is to make secure but non-random possible for ID pipes, peers, - and peer groups. When using the utility, it is recomended tha you use - a hash size apropriate to your address space. - - @see net.jxta.impl.id.binaryID.DigestTool - - This package supports the creation of an identifier given a binary value - that is 0 to 255 bytes long that is encoded as Base64. The value needs to - be a unique value so that it can be used for addressing peers, pipes, and - groups. - -

            - - The implementation also includes the creation of a digest hash given an - arbirary length string. This allows you to encode any type of data into - a secure digest. The digest hash is recomended unless you are sure that - your binary id is truely unique. Using a digest hash is also preferrable - for situatins when you have an id that could be comprimized if known (like - a socal security number). The digest tools also have convenience methods - for mixing an id with a function name and a way to create a time - limited ID. - -

            - - Note that this ID currently only allows parent peer group ID to be of - type UUID. - -

            - - @author Daniel Brookshier turbogeek@cluck.com - - - @see JXTA - Protocols Specification : IDs - - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/ID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/ID.java deleted file mode 100644 index 66295ebd..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/ID.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.unknown; - - -import net.jxta.id.IDFactory; -import java.net.URI; -import java.net.URL; - -import java.net.MalformedURLException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - - -/** - * IDs are used to uniquely identify peers, peer groups, pipes and other - * types of objects manipulated by the JXTA APIs. - * - * @see net.jxta.id.IDFactory - * @see net.jxta.codat.CodatID - * @see net.jxta.peer.PeerID - * @see net.jxta.peergroup.PeerGroupID - * @see net.jxta.pipe.PipeID - * @see net.jxta.platform.ModuleClassID - * @see net.jxta.platform.ModuleSpecID - * - **/ -public final class ID extends net.jxta.id.ID { - - /** - * Log4J Logger - **/ - private static final transient Logger LOG = Logger.getLogger(ID.class.getName()); - - String unqiueValue; - - /** - * Constructor for IDs. - **/ - ID(String value) { - unqiueValue = value; - } - - /** - * {@inheritDoc} - **/ - @Override - public boolean equals(Object target) { - if (this == target) { - return true; - } - - if (target instanceof ID) { - return getUniqueValue().toString().equals(((ID) target).getUniqueValue().toString()); - } else { - return false; - } - } - ; - - /** - * {@inheritDoc} - **/ - @Override - public int hashCode() { - return getUniqueValue().hashCode(); - } - ; - - /** - * {@inheritDoc} - **/ - @Override - public String getIDFormat() { - return unqiueValue.substring(0, unqiueValue.indexOf('-')); - } - - /** - * {@inheritDoc} - **/ - @Override - public Object getUniqueValue() { - return unqiueValue; - } - - /** - * {@inheritDoc} - **/ - @Override - public URL getURL() { - return getURL((String) getUniqueValue()); - } - - /** - * Public member which returns a URI (URL in Java nomenclature) of the ID. - * - * @param uniqueValue the unique portion of the ID - * @return URL Object containing the URI - **/ - static URL getURL(String uniqueValue) { - URL result = null; - - // Encode the unique value so that the resulting URN is valid. - String encoded = sun.net.www.protocol.urn.Handler.encodeURN(uniqueValue); - - try { - result = IDFactory.jxtaURL(ID.URIEncodingName, "", ID.URNNamespace + ":" + encoded); - } catch (MalformedURLException failed) { - LOG.log(Level.SEVERE, "Failed to construct URL", failed); - } - - return result; - } - - /** - * {@inheritDoc} - **/ - @Override - public URI toURI() { - return URI.create(ID.URIEncodingName + ":" + ID.URNNamespace + ":" + getUniqueValue()); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/IDFormat.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/IDFormat.java deleted file mode 100644 index a2f13306..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/IDFormat.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.unknown; - - -import net.jxta.id.IDFactory; - - -/** - * The 'unknown' format is not a regular JXTA ID format. It is a special ID - * format used by the J2SE implementation to manage ids of formats which are - * not recognized. No ids of format 'unknown' are ever emitted nor can any new - * ids be created. - **/ -public final class IDFormat { - - /** - * The instantiator for this ID Format which is used by the IDFactory. - * - **/ - public static final IDFactory.URIInstantiator INSTANTIATOR = new Instantiator(); - - /** - * Private Constructor. This class cannot be instantiated. - **/ - private IDFormat() {} -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/Instantiator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/Instantiator.java deleted file mode 100644 index f06ea65e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/Instantiator.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.id.unknown; - - -import java.io.InputStream; -import java.net.URI; -import java.net.URL; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.UnknownServiceException; -import java.net.URISyntaxException; -import java.security.ProviderException; - -import net.jxta.id.IDFactory; - - -final class Instantiator implements IDFactory.URIInstantiator { - - /** - * Our ID Format - **/ - final static String unknownFormat = "unknown"; - - /** - * {@inheritDoc} - **/ - public String getSupportedIDFormat() { - return unknownFormat; - } - - /** - * {@inheritDoc} - **/ - public net.jxta.id.ID fromURL(URL source) throws MalformedURLException, UnknownServiceException { - - net.jxta.id.ID result = null; - - // check the protocol - if (!net.jxta.id.ID.URIEncodingName.equalsIgnoreCase(source.getProtocol())) { - throw new UnknownServiceException("URI protocol type was not as expected."); - } - - String encoded = source.getFile(); - - // Decode the URN to convert any % encodings and convert it from UTF8. - String decoded = sun.net.www.protocol.urn.Handler.decodeURN(encoded); - - int colonAt = decoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new UnknownServiceException("URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(decoded.substring(0, colonAt))) { - throw new UnknownServiceException("URN namespace was not as expected."); - } - - // skip the namespace portion and the colon - decoded = decoded.substring(colonAt + 1); - - result = new ID(decoded); - - return result; - } - ; - - /** - * {@inheritDoc} - **/ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID, InputStream in) throws IOException { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.codat.CodatID newCodatID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed, InputStream in) throws IOException { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.peer.PeerID newPeerID(net.jxta.peergroup.PeerGroupID groupID) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.peer.PeerID newPeerID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.peergroup.PeerGroupID newPeerGroupID() { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(byte[] seed) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(net.jxta.peergroup.PeerGroupID parent) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.peergroup.PeerGroupID newPeerGroupID(net.jxta.peergroup.PeerGroupID parent, byte[] seed) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.pipe.PipeID newPipeID(net.jxta.peergroup.PeerGroupID groupID) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.pipe.PipeID newPipeID(net.jxta.peergroup.PeerGroupID groupID, byte[] seed) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.platform.ModuleClassID newModuleClassID() { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.platform.ModuleClassID newModuleClassID(final net.jxta.platform.ModuleClassID classID) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.platform.ModuleSpecID newModuleSpecID(final net.jxta.platform.ModuleClassID classID) { - throw new ProviderException("unsupported id type"); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.id.ID fromURI(URI source) throws URISyntaxException { - - // check the protocol - if (!net.jxta.id.ID.URIEncodingName.equalsIgnoreCase(source.getScheme())) { - throw new URISyntaxException(source.toString(), "URI scheme was not as expected."); - } - - String decoded = source.getSchemeSpecificPart(); - - int colonAt = decoded.indexOf(':'); - - // There's a colon right? - if (-1 == colonAt) { - throw new URISyntaxException(source.toString(), "URN namespace was missing."); - } - - // check the namespace - if (!net.jxta.id.ID.URNNamespace.equalsIgnoreCase(decoded.substring(0, colonAt))) { - throw new URISyntaxException(source.toString() - , - "URN namespace was not as expected. (" + net.jxta.id.ID.URNNamespace + "!=" + decoded.substring(0, colonAt) - + ")"); - } - - // skip the namespace portion and the colon - decoded = decoded.substring(colonAt + 1); - - return fromURNNamespaceSpecificPart(decoded); - } - - /** - * {@inheritDoc} - **/ - public net.jxta.id.ID fromURNNamespaceSpecificPart(String source) throws URISyntaxException { - ID result = new ID(source); - - return result; - - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/package.html deleted file mode 100644 index 9163b710..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/id/unknown/package.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - The 'unknown' format is a special JXTA ID format used by the J2SE - implementation to manage ids of formats which are not recognized. No ids of - format 'unknown' are ever emitted nor can any new ids be created. - - @see JXTA Protocols Specification : IDs - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/loader/RefJxtaLoader.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/loader/RefJxtaLoader.java deleted file mode 100644 index 46834998..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/loader/RefJxtaLoader.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.loader; - -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.impl.peergroup.CompatibilityEquater; -import net.jxta.platform.JxtaLoader; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleImplAdvertisement; - -import java.io.IOException; -import java.io.StringReader; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.jxta.logging.Logging; -import net.jxta.platform.Module; - - -/** - * This class is the reference implementation of the JxtaLoader. - */ -public class RefJxtaLoader extends JxtaLoader { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(RefJxtaLoader.class.getName()); - - /** - * The equator we will use to determine if compatibility statements are - * compatible with this JXTA implementation. - */ - private final CompatibilityEquater equator; - - /** - *

              - *
            • Keys are {@link net.jxta.platform.ModuleSpecID}.
            • - *
            • Values are {@link java.util.Map}. - *
                - *
              • Keys are {@link java.lang.String} Compatibility Statements serialized as XML UTF-8
              • - *
              • Values are {@link java.lang.Class}.
              • - *
              - *
            • - *
            - */ - private final Map>> classes = new HashMap>>(); - - /** - * Classes and ImplAdvs we have known. Weak Map so that classes can be GCed. - */ - private final Map, ModuleImplAdvertisement> implAdvs = new WeakHashMap, ModuleImplAdvertisement>(); - - /** - * Construct a new loader for the specified URLS with the default parent - * loader and specified compatibility equator. - * - * @param urls The URLs from which to load classes and resources. - * @param equator The equator to use in comparing compatibility statements. - */ - public RefJxtaLoader(URL[] urls, CompatibilityEquater equator) { - this(urls, RefJxtaLoader.class.getClassLoader(), equator); - } - - /** - * Construct a new loader for the specified URLS with the specified parent - * loader and specified compatibility equator. - * - * @param urls The URLs from which to load classes and resources. - * @param parent The parent class loader for delegation. - * @param equator The equator to use in comparing compatibility statements. - */ - public RefJxtaLoader(URL[] urls, ClassLoader parent, CompatibilityEquater equator) { - super(urls, parent); - this.equator = equator; - } - - /** - * Make a stub for a version that uses URL, so that code that load - * services can be written properly, even if it works only for classes - * that do not need download. - * - * @param name The class name. - * @param url The location of the class. - * @param resolve If {@code true} then resolve the class. - * @return the class - * @throws ClassNotFoundException if class not found - */ - protected Class loadClass(String name, URL url, boolean resolve) throws ClassNotFoundException { - try { - return loadClass(name, resolve); - } catch (ClassNotFoundException e) { - if (url != null) { - addURL(url); - return loadClass(name, resolve); - } else { - throw e; - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - - Class newClass = (Class) findLoadedClass(name); - - if (newClass == null) { // I'd rather say parent.loadClass() but it is private - try { - newClass = (Class) super.loadClass(name, false); - } catch (ClassNotFoundException ignored) { - // that's ok - } - } - - if (newClass == null) { - try { - newClass = (Class) findSystemClass(name); - if (newClass != null) { - return newClass; - } - } catch (ClassNotFoundException ignored) { - // that's ok - } - - // We need to also check if the Context ClassLoader associated to the - // the current thread can load the class. - if (newClass == null) { - try { - newClass = (Class) Thread.currentThread().getContextClassLoader().loadClass(name); - if (newClass != null) { - return newClass; - } - } catch (ClassNotFoundException ignored) { - // that's ok - } - } - - // try { - // byte[] buf = bytesForClass(name); - // newClass = defineClass(name, buf, 0, buf.length); - // } catch (IOException e) { - // throw new ClassNotFoundException(e.toString()); - // } - } - - if (resolve) { - resolveClass(newClass); - } - - return newClass; - } - - // /** - // * {@inheritDoc} - // **/ - // protected byte[] bytesForClass(String name) - // throws IOException, ClassNotFoundException { - // - // File file = new File( dir, name.replace('.', File.separatorChar) + ".java"); - // FileInputStream in = new FileInputStream(file); - // int length = (int) file.length(); - // if (length == 0) - // throw new ClassNotFoundException(name); - // byte[] buf = new byte[length]; - // in.read(buf); - // return buf; - // } - - /** - * {@inheritDoc} - */ - @Override - public synchronized Class findClass(ModuleSpecID spec) throws ClassNotFoundException { - - Map> compats = classes.get(spec); - - if (null == compats) { - throw new ClassNotFoundException("No matching class for : " + spec); - } - - for (Map.Entry> anEntry : compats.entrySet()) { - String aCompat = anEntry.getKey(); - - StructuredDocument asDoc; - - try { - asDoc = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, new StringReader(aCompat)); - } catch (IOException ignored) { - continue; - } - - if (equator.compatible(asDoc)) { - return anEntry.getValue(); - } - } - - throw new ClassNotFoundException(spec.toString()); - } - - /** - * {@inheritDoc} - */ - @Override - public Class loadClass(ModuleSpecID spec) throws ClassNotFoundException { - - Class found = findClass(spec); - - resolveClass(found); - - return found; - } - - /** - * Loads a class - * - * @param name class name - * @param url url to class - * @return the Class - * @throws ClassNotFoundException if class not found - */ - public Class loadClass(String name, URL url) throws ClassNotFoundException { - return loadClass(name, url, true); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized Class defineClass(ModuleImplAdvertisement impl) throws ClassFormatError { - String asString = impl.getCompat().toString(); - - // See if we have any classes defined for this ModuleSpecID. - // Note that there may be multiple definitions with different compatibility statements. - Map> compats = classes.get(impl.getModuleSpecID()); - - if (null == compats) { - compats = new HashMap>(); - classes.put(impl.getModuleSpecID(), compats); - } - - // See if there is a class defined which matches the compatibility statement of the implAdv. - Class loaded = compats.get(asString); - - if (null == loaded) { - try { - loaded = loadClass(impl.getCode(), new URL(impl.getUri()), false); - } catch (ClassNotFoundException failed) { - throw new ClassFormatError("Class '" + impl.getCode() + "' could not be loaded from : " + impl.getUri()); - } catch (MalformedURLException failed) { - throw new ClassFormatError("Cannot load class '" + impl.getCode() + "' from : " + impl.getUri()); - } - - // Remember the class along with the matching compatibility statement. - compats.put(asString, loaded); - } - - // Force update of impl advertisement. This is done because the class will frequently redefine itself. - implAdvs.put(loaded, impl); - - return loaded; - } - - /** - * {@inheritDoc} - */ - @Override - public ModuleImplAdvertisement findModuleImplAdvertisement(Class clazz) { - ModuleImplAdvertisement result = implAdvs.get(clazz); - - if (null == result) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "No module imp adv for " + clazz); - } - return null; - } else { - return result.clone(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public ModuleImplAdvertisement findModuleImplAdvertisement(ModuleSpecID msid) { - Class moduleClass; - - try { - moduleClass = findClass(msid); - } catch (ClassNotFoundException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to find class for " + msid, failed); - } - return null; - } - - if (null == moduleClass) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "No class for " + msid); - } - return null; - } else { - return findModuleImplAdvertisement(moduleClass); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - - result.append("Classes : "); - for (Map.Entry>> eachMCID : classes.entrySet()) { - ModuleSpecID mcid = eachMCID.getKey(); - result.append("\n\t" + mcid + " :"); - for (Map.Entry> eachClass : eachMCID.getValue().entrySet()) { - result.append("\n\t\t" + eachClass.getValue().toString()); - } - } - - return result.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/loader/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/loader/package.html deleted file mode 100644 index 241ec06b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/loader/package.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - An implementation of {@link net.jxta.platform.JxtaLoader} for use by the - standard peer group implementations. - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/PasswdMembershipService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/PasswdMembershipService.java deleted file mode 100644 index e6807a71..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/PasswdMembershipService.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership; - - -import java.net.MalformedURLException; -import java.net.UnknownServiceException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.platform.JxtaLoader; -import net.jxta.membership.Authenticator; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleImplAdvertisement; - -import net.jxta.exception.JxtaError; - -import net.jxta.impl.loader.RefJxtaLoader; -import net.jxta.impl.peergroup.StdPeerGroup; - - -/** - * The passwd membership service provides a Membership Service implementation - * which is based on a password scheme similar to the unix - * /etc/passwd system.
            - * - * @deprecated This service is intended only as a sample and should not be used - * for real membership applications. IT IS NOT SECURE. The implementation has - * also moved to {@link net.jxta.impl.membership.passwd.PasswdMembershipService} - * - *

            This implementation is intended mostly as an example of a - * simple Membership Service service and not as a practical secure - * Membership Service. - * - * @see net.jxta.membership.MembershipService - * - **/ -@Deprecated -public class PasswdMembershipService { - - /** - * Log4J Logger - **/ - private static final Logger LOG = Logger.getLogger(PasswdMembershipService.class.getName()); - - /** - * Well known service specification identifier: password membership - */ - public static final ModuleSpecID passwordMembershipSpecID = net.jxta.impl.membership.passwd.PasswdMembershipService.passwordMembershipSpecID; - - /** - * Register the "real" password membership service as soon as someone - * references this class. - **/ - static { - JxtaLoader loader = net.jxta.impl.peergroup.GenericPeerGroup.getJxtaLoader(); - - ModuleImplAdvertisement implAdv = (ModuleImplAdvertisement) AdvertisementFactory.newAdvertisement( - ModuleImplAdvertisement.getAdvertisementType()); - - implAdv.setCode(net.jxta.impl.membership.passwd.PasswdMembershipService.class.getName()); - implAdv.setCompat(StdPeerGroup.STD_COMPAT); - implAdv.setDescription("Password Membership Service"); - implAdv.setModuleSpecID(passwordMembershipSpecID); - implAdv.setProvider(StdPeerGroup.MODULE_IMPL_STD_PROVIDER); - implAdv.setUri(StdPeerGroup.MODULE_IMPL_STD_URI); - - loader.defineClass(implAdv); - } - - public abstract static class PasswdAuthenticator implements Authenticator { - - public abstract void setAuth1Identity(String who); - - public abstract String getAuth1Identity(); - - public abstract void setAuth2_Password(String secret); - - protected abstract String getAuth2_Password(); - } - - /** - * This is the method used to make the password strings. We only provide - * one way encoding since we can compare the encoded strings. - * - *

            FIXME 20010402bondolo@jxta.org : switch to use the standard - * crypt(3) algorithm for encoding the passwords. The current algorithm has - * been breakable since ancient times, crypt(3) is also weak, but harder to - * break. - * - * @param source the string to encode - * @return String the encoded version of the password. - * - **/ - public static String makePsswd(String source) { - - /** - * - * A->D B->Q C->K D->W E->H F->R G->T H->E I->N J->O K->G L->X M->C - * N->V O->Y P->S Q->F R->J S->P T->I U->L V->Z W->A X->B Y->M Z->U - * - **/ - - final String xlateTable = "DQKWHRTENOGXCVYSFJPILZABMU"; - - StringBuilder work = new StringBuilder(source); - - for (int eachChar = work.length() - 1; eachChar >= 0; eachChar--) { - char aChar = Character.toUpperCase(work.charAt(eachChar)); - - int replaceIdx = xlateTable.indexOf(aChar); - - if (-1 != replaceIdx) { - work.setCharAt(eachChar, (char) ('A' + replaceIdx)); - } - } - - return work.toString(); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/none/NoneMembershipService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/none/NoneMembershipService.java deleted file mode 100644 index cd11469b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/none/NoneMembershipService.java +++ /dev/null @@ -1,700 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.none; - - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; - -import java.net.URISyntaxException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.credential.AuthenticationCredential; -import net.jxta.credential.Credential; -import net.jxta.credential.CredentialPCLSupport; -import net.jxta.document.Attribute; -import net.jxta.document.Attributable; -import net.jxta.document.Advertisement; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.TextElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.membership.Authenticator; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.service.Service; - -import net.jxta.exception.ProtocolNotSupportedException; -import net.jxta.exception.PeerGroupException; - - -/** - * A Membership Service implementation which is intended to be used with peer - * groups which require no real authentication. - * - *

            The none service allows you to claim any identity within the peergroup, - * but for peergroups which use this Membership Service method, it is - * likely that the identity is used only for informational purposes. - * - *

            A default credential with the name "nobody" is automatically available - * without requiring authentication by this service. - * - */ -public class NoneMembershipService implements MembershipService { - - /** - * Log4J Logger - **/ - private static final Logger LOG = Logger.getLogger(NoneMembershipService.class.getName()); - - /** - * Credential format for the None Membership service. - * - *

            Credentials for the None Membership Service consist of the following - * unencrypted, unsigned XML tags: - * - *

              - *
            • PeerGroupID
            • - *
            • PeerID
            • - *
            • Identity
            • - *
            - **/ - private final static class NoneCredential implements Credential, CredentialPCLSupport { - - private NoneMembershipService source; - - private String whoami; - - private ID peerid; - - /** - * Whether the credential is valid. - **/ - boolean valid = true; - - /** - * property change support - **/ - private PropertyChangeSupport support = new PropertyChangeSupport(this); - - protected NoneCredential(NoneMembershipService source, String whoami) { - - this.source = source; - this.whoami = whoami; - this.peerid = source.peergroup.getPeerID(); - } - - protected NoneCredential(NoneMembershipService source, Element root) throws PeerGroupException { - - this.source = source; - - initialize(root); - } - - /** - * {@inheritDoc} - **/ - public ID getPeerGroupID() { - return source.peergroup.getPeerGroupID(); - } - - /** - * {@inheritDoc} - **/ - public ID getPeerID() { - return peerid; - } - - /** - * - **/ - private void setPeerID(PeerID peerid) { - this.peerid = peerid; - } - - /** - * {@inheritDoc} - * - *

            NoneCredential are always valid. - **/ - public boolean isExpired() { - return false; - } - - /** - * {@inheritDoc} - * - *

            NoneCredential are always valid. - **/ - public boolean isValid() { - return valid; - } - - /** - * {@inheritDoc} - * - *

            PasswdCredential are always valid except after resign. - **/ - private void setValid(boolean valid) { - boolean oldValid = isValid(); - - this.valid = valid; - - if (oldValid != valid) { - support.firePropertyChange("valid", oldValid, valid); - } - } - - /** - * {@inheritDoc} - **/ - public Object getSubject() { - return whoami; - } - - /** - * - **/ - private void setSubject(String subject) { - whoami = subject; - } - - /** - * {@inheritDoc} - **/ - public Service getSourceService() { - return source.getInterface(); - } - - /** - * {@inheritDoc} - **/ - public StructuredDocument getDocument(MimeMediaType as) throws Exception { - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(as, "jxta:Cred"); - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - ((Attributable) doc).addAttribute("xml:space", "preserve"); - ((Attributable) doc).addAttribute("type", "jxta:NullCred"); - } - - Element e = doc.createElement("PeerGroupID", getPeerGroupID().toString()); - - doc.appendChild(e); - - e = doc.createElement("PeerID", peerid.toString()); - doc.appendChild(e); - - e = doc.createElement("Identity", whoami); - doc.appendChild(e); - - return doc; - } - - /** - * Process an individual element from the document. - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - **/ - protected boolean handleElement(TextElement elem) { - if (elem.getName().equals("PeerGroupID")) { - try { - URI gID = new URI(elem.getTextValue()); - ID pgid = IDFactory.fromURI(gID); - - if (!pgid.equals(getPeerGroupID())) { - throw new IllegalArgumentException( - "Operation is from a different group. " + pgid + " != " + getPeerGroupID()); - } - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerGroupID in advertisement: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("PeerID")) { - try { - URI pID = new URI(elem.getTextValue()); - ID pid = IDFactory.fromURI(pID); - - setPeerID((PeerID) pid); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad Peer ID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a peer id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("Identity")) { - setSubject(elem.getTextValue()); - return true; - } - - // element was not handled - return false; - } - - /** - * Intialize from a portion of a structured document. - **/ - protected void initialize(Element root) { - - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports TextElement"); - } - - TextElement doc = (TextElement) root; - - String typedoctype = ""; - - if (root instanceof Attributable) { - Attribute itsType = ((Attributable) root).getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - } - - String doctype = doc.getName(); - - if (!doctype.equals("jxta:NullCred") && !typedoctype.equals("jxta:NullCred")) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doctype); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - TextElement elem = (TextElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandleded element \'" + elem.getName() + "\' in " + doc.getName()); - } - } - } - - // sanity check time! - - if (null == getSubject()) { - throw new IllegalArgumentException("subject was never initialized."); - } - - if (null == getPeerID()) { - throw new IllegalArgumentException("peer id was never initialized."); - } - - // FIXME bondolo@jxta.org 20030409 should check for duplicate elements and for peergroup element - } - - /** - * Add a listener - * - * @param listener the listener - **/ - public void addPropertyChangeListener(PropertyChangeListener listener) { - support.addPropertyChangeListener(listener); - } - - /** - * Add a listener - * - * @param propertyName the property to watch - * @param listener the listener - **/ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.addPropertyChangeListener(propertyName, listener); - } - - /** - * Remove a listener - * - * @param listener the listener - **/ - public void removePropertyChangeListener(PropertyChangeListener listener) { - support.removePropertyChangeListener(listener); - } - - /** - * Remove a listener - * - * @param propertyName the property which was watched - * @param listener the listener - **/ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.removePropertyChangeListener(propertyName, listener); - } - } - - - /** - * Authenticator Class for the None Membership Service. Pre-filled in and - * ready for join(). - **/ - public final static class NoneAuthenticator implements Authenticator { - - MembershipService source; - AuthenticationCredential application; - - String whoami = "nobody"; - - /** - * Creates an authenticator for the null membership service. Anything entered - * into the identity info section of the Authentication credential is - * ignored. - * - * @param source The instance of the null membership service which - * created this authenticator. - * @param application Anything entered into the identity info section of - * the Authentication credential is ignored. - **/ - NoneAuthenticator(NoneMembershipService source, AuthenticationCredential application) { - this.source = source; - this.application = application; - } - - /** - * Returns the service which generated this authenticator. - **/ - public MembershipService getSourceService() { - return source; - } - - /** - * {@inheritDoc} - * - *

            This implementation is always ready for - * join() - **/ - synchronized public boolean isReadyForJoin() { - // always ready. - return true; - } - - /** - * {@inheritDoc} - **/ - public String getMethodName() { - return "NullAuthentication"; - } - - /** - * {@inheritDoc} - **/ - public AuthenticationCredential getAuthenticationCredential() { - return application; - } - - public void setAuth1Identity(String who) { - if (null == who) { - throw new IllegalArgumentException("You must supply an identity"); - } - whoami = who; - } - - public String getAuth1Identity() { - return whoami; - } - } - - private ModuleImplAdvertisement implAdvertisement = null; - - /** - * The peergroup we live in. - **/ - private PeerGroup peergroup = null; - - /** - * our current credentials - **/ - private List principals; - - /** - * our current auth credentials - **/ - private List principalsAuth; - - /** - * the default "nobody" credential - **/ - private NoneCredential defaultCredential = null; - - /** - * property change support - **/ - private PropertyChangeSupport support; - - /** - * default constructor. Normally called only by the peer group. - **/ - public NoneMembershipService() throws PeerGroupException { - principals = new ArrayList(); - principalsAuth = new ArrayList(); - support = new PropertyChangeSupport(getInterface()); - } - - /** - * Add a listener - * - * @param listener the listener - **/ - public void addPropertyChangeListener(PropertyChangeListener listener) { - support.addPropertyChangeListener(listener); - } - - /** - * Add a listener - * - * @param propertyName the property to watch - * @param listener the listener - **/ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.addPropertyChangeListener(propertyName, listener); - } - - /** - * Remove a listener - * - * @param listener the listener - **/ - public void removePropertyChangeListener(PropertyChangeListener listener) { - support.removePropertyChangeListener(listener); - } - - /** - * Remove a listener - * - * @param propertyName the property which was watched - * @param listener the listener - **/ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.removePropertyChangeListener(propertyName, listener); - } - - /** - * {@inheritDoc} - **/ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - - implAdvertisement = (ModuleImplAdvertisement) impl; - - peergroup = group; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring None Membership Service : " + assignedID); - - configInfo.append("\n\tImplementation:"); - configInfo.append("\n\t\tModule Spec ID: " + implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : " + implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : " + implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : " + implAdvertisement.getCode()); - configInfo.append("\n\tGroup Params:"); - configInfo.append("\n\t\tGroup: " + group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID: " + group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID: " + group.getPeerID()); - LOG.config(configInfo.toString()); - } - - defaultCredential = new NoneCredential(this, "nobody"); - - resign(); - } - - /** - * {@inheritDoc} - **/ - public Service getInterface() { - return this; // we have no method access control - } - - /** - * {@inheritDoc} - **/ - public int startApp(String[] arg) { - return 0; - } - - /** - * {@inheritDoc} - **/ - public void stopApp() { - resign(); - - peergroup = null; - } - - /** - * {@inheritDoc} - **/ - public Advertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * {@inheritDoc} - **/ - public Authenticator apply(AuthenticationCredential application) throws PeerGroupException, ProtocolNotSupportedException { - - String method = application.getMethod(); - - if ((null != method) && !"StringAuthentication".equals(method) && !"NoneAuthentication".equals(method)) { - throw new ProtocolNotSupportedException("Authentication method not recognized"); - } - - return new NoneAuthenticator(this, application); - } - - /** - * {@inheritDoc} - **/ - public Credential getDefaultCredential() { - return defaultCredential; - } - - /** - * {@inheritDoc} - **/ - public synchronized Enumeration getCurrentCredentials() { - return Collections.enumeration(principals); - } - - /** - * {@inheritDoc} - **/ - public synchronized Enumeration getAuthCredentials() { - return Collections.enumeration(principalsAuth); - } - - /** - * {@inheritDoc} - **/ - public Credential join(Authenticator authenticated) throws PeerGroupException { - - if (!(authenticated instanceof NoneAuthenticator)) { - throw new ClassCastException("This is not my authenticator!"); - } - - if (!authenticated.isReadyForJoin()) { - throw new PeerGroupException("Not ready to join()!"); - } - - NoneAuthenticator myAuthenticated = (NoneAuthenticator) authenticated; - - Credential newCred; - - synchronized (this) { - newCred = new NoneCredential(this, myAuthenticated.getAuth1Identity()); - - principals.add(newCred); - principalsAuth.add(myAuthenticated.application); - } - - support.firePropertyChange("addCredential", null, newCred); - - return newCred; - } - - /** - * {@inheritDoc} - **/ - public void resign() { - List allCreds = new ArrayList(); - - allCreds.addAll(principals); - allCreds.remove(defaultCredential); - - synchronized (this) { - // remove all existing credentials - principals.clear(); - principalsAuth.clear(); - - // re-add the default credential. - principals.add(defaultCredential); - } - - Iterator eachCred = allCreds.iterator(); - - while (eachCred.hasNext()) { - NoneCredential aCred = (NoneCredential) eachCred.next(); - - aCred.setValid(false); - } - } - - /** - * {@inheritDoc} - **/ - public Credential makeCredential(Element element) throws PeerGroupException, Exception { - return new NoneCredential(this, element); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/none/NoneMembershipServiceBeanInfo.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/none/NoneMembershipServiceBeanInfo.java deleted file mode 100644 index d2a05b22..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/none/NoneMembershipServiceBeanInfo.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.none; - - -import java.beans.BeanDescriptor; -import java.beans.EventSetDescriptor; -import java.beans.PropertyChangeListener; -import java.beans.PropertyDescriptor; -import java.beans.SimpleBeanInfo; - -import java.beans.IntrospectionException; -import java.lang.reflect.UndeclaredThrowableException; - - -/** - * Our beaninfo - **/ -public class NoneMembershipServiceBeanInfo extends SimpleBeanInfo { - - /** - * {@inheritDoc} - **/ - @Override - public BeanDescriptor getBeanDescriptor() { - return new BeanDescriptor(NoneMembershipService.class); - } - - /** - * {@inheritDoc} - **/ - @Override - public EventSetDescriptor[] getEventSetDescriptors() { - try { - EventSetDescriptor changed = new EventSetDescriptor(NoneMembershipService.class, "propertyChange" - , - PropertyChangeListener.class, "propertyChange"); - - changed.setDisplayName("bound property change"); - - EventSetDescriptor[] rv = { changed }; - - return rv; - } catch (IntrospectionException failed) { - throw new UndeclaredThrowableException(failed, "Configuration error"); - } - } - - /** - * {@inheritDoc} - **/ - @Override - public PropertyDescriptor[] getPropertyDescriptors() { - try { - PropertyDescriptor defaultcredential = new PropertyDescriptor("defaultCredential", NoneMembershipService.class); - - defaultcredential.setBound(true); - - PropertyDescriptor rv[] = { defaultcredential }; - - return rv; - } catch (IntrospectionException failed) { - throw new UndeclaredThrowableException(failed, "Configuration error"); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/none/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/none/package.html deleted file mode 100644 index ae78841b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/none/package.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - A Membership Service implementation which is intended to be used with peer - groups which require no real authentication. - -

            The none service allows you to claim any identity within the peergroup, - but for peergroups which use this Membership Service method, it is - likely that the identity is used only for informational purposes. - -

            A default credential with the name "nobody" is automatically available - without requiring authentication by this service. - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/package.html deleted file mode 100644 index 45054eb1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/package.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - The membership service allows a peer to establish an identity within a peer - group. - -

            This package contains implementations of the Membership service. - - @see net.jxta.membership - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/passwd/PasswdMembershipService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/passwd/PasswdMembershipService.java deleted file mode 100644 index ab61af50..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/passwd/PasswdMembershipService.java +++ /dev/null @@ -1,909 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.passwd; - - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.HashMap; - -import java.net.URISyntaxException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.credential.AuthenticationCredential; -import net.jxta.credential.Credential; -import net.jxta.credential.CredentialPCLSupport; -import net.jxta.document.Advertisement; -import net.jxta.document.Attribute; -import net.jxta.document.Attributable; -import net.jxta.document.Element; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.membership.Authenticator; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.ModuleSpecID; -import net.jxta.service.Service; - -import net.jxta.exception.JxtaError; -import net.jxta.exception.ProtocolNotSupportedException; -import net.jxta.exception.PeerGroupException; - - -/** - * The passwd membership service provides a Membership Service implementation - * which is based on a password scheme similar to the unix - * /etc/passwd system.
            - * - *

            This implementation is intended as an example of a - * simple Membership Service and NOT as a practical secure - * Membership Service. - * - * @see net.jxta.membership.MembershipService - * - **/ -public class PasswdMembershipService implements MembershipService { - - /** - * Log4J Logger - **/ - private static final Logger LOG = Logger.getLogger(PasswdMembershipService.class.getName()); - - /** - * Well known service specification identifier: password membership - */ - public static final ModuleSpecID passwordMembershipSpecID = (ModuleSpecID) - ID.create(URI.create("urn:jxta:uuid-DeadBeefDeafBabaFeedBabe000000050206")); - - /** - * This class provides the sub-class of Credential which is associated - * with the password membership service. - **/ - public final static class PasswdCredential implements Credential, CredentialPCLSupport { - - /** - * The MembershipService service which generated this credential. - **/ - PasswdMembershipService source; - - /** - * The identity associated with this credential - **/ - String whoami; - - /** - * The peerid associated with this credential. - **/ - ID peerid; - - /** - * The peerid which has been "signed" so that the identity may be verified. - **/ - String signedPeerID; - - /** - * property change support - **/ - private PropertyChangeSupport support = new PropertyChangeSupport(this); - - /** - * Whether the credential is valid. - **/ - boolean valid = true; - - protected PasswdCredential(PasswdMembershipService source, String whoami, String signedPeerID) { - - this.source = source; - this.whoami = whoami; - this.peerid = source.peergroup.getPeerID(); - this.signedPeerID = signedPeerID; - } - - protected PasswdCredential(PasswdMembershipService source, Element root) throws PeerGroupException { - - this.source = source; - - initialize(root); - } - - /** - * Add a listener - * - * @param listener the listener - **/ - public void addPropertyChangeListener(PropertyChangeListener listener) { - support.addPropertyChangeListener(listener); - } - - /** - * Add a listener - * - * @param propertyName the property to watch - * @param listener the listener - **/ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.addPropertyChangeListener(propertyName, listener); - } - - /** - * Remove a listener - * - * @param listener the listener - **/ - public void removePropertyChangeListener(PropertyChangeListener listener) { - support.removePropertyChangeListener(listener); - } - - /** - * Remove a listener - * - * @param propertyName the property which was watched - * @param listener the listener - **/ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.removePropertyChangeListener(propertyName, listener); - } - - /** - * {@inheritDoc} - **/ - public ID getPeerGroupID() { - return source.peergroup.getPeerGroupID(); - } - - /** - * {@inheritDoc} - **/ - public ID getPeerID() { - return peerid; - } - - /** - * Set the peerid for this credential. - * - * @param peerid the peerid for this credential - **/ - private void setPeerID(PeerID peerid) { - this.peerid = peerid; - } - - /** - * {@inheritDoc} - * - *

            PasswdCredential never expire. - **/ - public boolean isExpired() { - return false; - } - - /** - * {@inheritDoc} - * - *

            PasswdCredential are almost always valid. - **/ - public boolean isValid() { - return valid; - } - - /** - * {@inheritDoc} - * - *

            PasswdCredential are always valid except after resign. - **/ - private void setValid(boolean valid) { - boolean oldValid = isValid(); - - this.valid = valid; - - if (oldValid != valid) { - support.firePropertyChange("valid", oldValid, valid); - } - } - - /** - * {@inheritDoc} - **/ - public Object getSubject() { - return whoami; - } - - /** - * Sets the subject for this Credential - * - * @param subject The subject for this credential. - **/ - private void setSubject(String subject) { - whoami = subject; - } - - /** - * {@inheritDoc} - **/ - public Service getSourceService() { - return source; - } - - /** - * {@inheritDoc} - **/ - public StructuredDocument getDocument(MimeMediaType as) throws Exception { - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(as, "jxta:Cred"); - - if (doc instanceof XMLDocument) { - ((Attributable) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - ((Attributable) doc).addAttribute("xml:space", "preserve"); - } - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("type", "jxta:PasswdCred"); - } - - Element e = doc.createElement("PeerGroupID", getPeerGroupID().toString()); - - doc.appendChild(e); - - e = doc.createElement("PeerID", getPeerID().toString()); - doc.appendChild(e); - - e = doc.createElement("Identity", whoami); - doc.appendChild(e); - - // FIXME 20010327 Do some kind of signing here based on password. - e = doc.createElement("ReallyInsecureSignature", signedPeerID); - doc.appendChild(e); - - return doc; - } - - /** - * Process an individual element from the document. - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - **/ - protected boolean handleElement(XMLElement elem) { - if (elem.getName().equals("PeerGroupID")) { - try { - URI gID = new URI(elem.getTextValue()); - ID pgid = IDFactory.fromURI(gID); - - if (!pgid.equals(getPeerGroupID())) { - throw new IllegalArgumentException( - "Operation is from a different group. " + pgid + " != " + getPeerGroupID()); - } - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerGroupID in advertisement: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("PeerID")) { - try { - URI pID = new URI(elem.getTextValue()); - ID pid = IDFactory.fromURI(pID); - - setPeerID((PeerID) pid); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad Peer ID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a peer id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("Identity")) { - setSubject(elem.getTextValue()); - return true; - } - - if (elem.getName().equals("ReallyInsecureSignature")) { - signedPeerID = elem.getTextValue(); - return true; - } - - // element was not handled - return false; - } - - /** - * Intialize from a portion of a structured document. - **/ - protected void initialize(Element root) { - - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XMLElement"); - } - - XMLElement doc = (XMLElement) root; - - String typedoctype = ""; - Attribute itsType = ((Attributable) root).getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - String doctype = doc.getName(); - - if (!doctype.equals("jxta:PasswdCred") && !typedoctype.equals("jxta:PasswdCred")) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doctype); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandleded element \'" + elem.getName() + "\' in " + doc.getName()); - } - } - } - - // sanity check time! - - if (null == getSubject()) { - throw new IllegalArgumentException("subject was never initialized."); - } - - if (null == getPeerID()) { - throw new IllegalArgumentException("peer id was never initialized."); - } - - if (null == signedPeerID) { - throw new IllegalArgumentException("signed peer id was never initialized."); - } - - // FIXME bondolo@jxta.org 20030409 should check for duplicate elements and for peergroup element - } - } - - - /** - * Creates an authenticator for the passwd membership service. Anything - * entered into the identity info section of the Authentication - * credential is ignored. - * - *

            HACK ALERT! THE INHERITANCE FROM - * net.jxta.impl.membership.PasswdMembershipService.PasswdAuthenticator - * IS A TOTAL HACK FOR BACKWARDS COMPATIBILITY. - * - * @param source The instance of the passwd membership service which - * created this authenticator. - * @param application Anything entered into the identity info section of - * the Authentication credential is ignored. - **/ - public final static class PasswdAuthenticator extends net.jxta.impl.membership.PasswdMembershipService.PasswdAuthenticator { - - /** - * The Membership Service which generated this authenticator. - **/ - PasswdMembershipService source; - - /** - * The Authentication which was provided to the Apply operation of the - * membership service. - **/ - AuthenticationCredential application; - - /** - * the identity which is being claimed - **/ - String whoami = null; - - /** - * the password for that identity. - **/ - String password = null; - - /** - * Creates an authenticator for the password MembershipService service. The only method - * supported is "PasswdAuthentication". Anything entered into the identity info - * section of the Authentication credential is ignored. - * - * @param source The instance of the password membership service which created this - * authenticator. - * @param application The Anything entered into the identity info section of the Authentication - * credential is ignored. - **/ - PasswdAuthenticator(PasswdMembershipService source, AuthenticationCredential application) { - this.source = source; - this.application = application; - - // XXX 20010328 bondolo@jxta.org Could do something with the authentication credential here. - } - - /** - * {@inheritDoc} - **/ - public MembershipService getSourceService() { - return (MembershipService) source.getInterface(); - } - - /** - * {@inheritDoc} - **/ - synchronized public boolean isReadyForJoin() { - return ((null != password) && (null != whoami)); - } - - /** - * {@inheritDoc} - **/ - public String getMethodName() { - return "PasswdAuthentication"; - } - - /** - * {@inheritDoc} - **/ - public AuthenticationCredential getAuthenticationCredential() { - return application; - } - - @Override - public void setAuth1Identity(String who) { - whoami = who; - } - - @Override - public String getAuth1Identity() { - return whoami; - } - - @Override - public void setAuth2_Password(String secret) { - password = secret; - } - - @Override - protected String getAuth2_Password() { - return password; - } - } - - /** - * the peergroup to which this service is associated. - **/ - private PeerGroup peergroup = null; - - /** - * the default "nobody" credential - **/ - private Credential defaultCredential = null; - - /** - * The current set of principals associated with this peer within this peegroup. - **/ - private List principals; - - /** - * The set of AuthenticationCredentials which were used to establish the principals. - **/ - private List authCredentials; - - /** - * The ModuleImplAdvertisement which was used to instantiate this service. - **/ - private ModuleImplAdvertisement implAdvertisement = null; - - /** - * An internal table containing the identity and password pairs as parsed from the - * the PeerGroupAdvertisement. - **/ - private Map logins = null; - - /** - * property change support - **/ - private PropertyChangeSupport support; - - /** - * Default constructor. Normally only called by the peer group. - **/ - public PasswdMembershipService() throws PeerGroupException { - principals = new ArrayList(); - authCredentials = new ArrayList(); - - support = new PropertyChangeSupport(getInterface()); - } - - /** - * Add a listener - * - * @param listener the listener - **/ - public void addPropertyChangeListener(PropertyChangeListener listener) { - support.addPropertyChangeListener(listener); - } - - /** - * Add a listener - * - * @param propertyName the property to watch - * @param listener the listener - **/ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.addPropertyChangeListener(propertyName, listener); - } - - /** - * Remove a listener - * - * @param listener the listener - **/ - public void removePropertyChangeListener(PropertyChangeListener listener) { - support.removePropertyChangeListener(listener); - } - - /** - * Remove a listener - * - * @param propertyName the property which was watched - * @param listener the listener - **/ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.removePropertyChangeListener(propertyName, listener); - } - - /** - * {@inheritDoc} - **/ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - - peergroup = group; - implAdvertisement = (ModuleImplAdvertisement) impl; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Password Membership Service : " + assignedID); - - configInfo.append("\n\tImplementation:"); - configInfo.append("\n\t\tModule Spec ID: " + implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : " + implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : " + implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : " + implAdvertisement.getCode()); - configInfo.append("\n\tGroup Params:"); - configInfo.append("\n\t\tGroup: " + group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID: " + group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID: " + group.getPeerID()); - LOG.config(configInfo.toString()); - } - - PeerGroupAdvertisement configAdv = group.getPeerGroupAdvertisement(); - - XMLElement myParam = (XMLElement) configAdv.getServiceParam(assignedID); - - logins = new HashMap(); - - if (null == myParam) { - throw new PeerGroupException("parameters for group passwords missing"); - } - - for (Enumeration allLogins = myParam.getChildren(); allLogins.hasMoreElements();) { - XMLElement aLogin = (XMLElement) allLogins.nextElement(); - - if (aLogin.getName().equals("login")) { - String etcPasswd = aLogin.getTextValue(); - int nextDelim = etcPasswd.indexOf(':'); - - if (-1 == nextDelim) { - continue; - } - String login = etcPasswd.substring(0, nextDelim).trim(); - int lastDelim = etcPasswd.indexOf(':', nextDelim + 1); - String passwd = etcPasswd.substring(nextDelim + 1, lastDelim); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Adding login : \'" + login + "\' with encoded password : \'" + passwd + "\'"); - } - logins.put(login, passwd); - } - } - - // FIXME 20010327 bondolo@jxta.org Make up the signed bit. - - // We initialise our set of principals to the resigned state. - resign(); - } - - /** - * {@inheritDoc} - **/ - public Service getInterface() { - return this; - } - - /** - * {@inheritDoc} - **/ - public Advertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * {@inheritDoc} - * - *

            Currently this service starts by itself and does not expect - * arguments. - */ - public int startApp(String[] arg) { - return 0; - } - - /** - * {@inheritDoc} - * - *

            This request is currently ignored. - **/ - public void stopApp() { - resign(); - } - - /** - * {@inheritDoc} - **/ - public Authenticator apply(AuthenticationCredential application) throws PeerGroupException, ProtocolNotSupportedException { - - String method = application.getMethod(); - - if ((null != method) && !"StringAuthentication".equals(method) && !"PasswdAuthentication".equals(method)) { - throw new ProtocolNotSupportedException("Authentication method not recognized"); - } - - return new PasswdAuthenticator(this, application); - } - - /** - * {@inheritDoc} - **/ - public Credential getDefaultCredential() { - return defaultCredential; - } - - /** - * {@inheritDoc} - **/ - private void setDefaultCredential(Credential newDefault) { - Credential oldDefault = defaultCredential; - - defaultCredential = newDefault; - - support.firePropertyChange("defaultCredential", oldDefault, newDefault); - } - - /** - * {@inheritDoc} - **/ - public synchronized Enumeration getCurrentCredentials() { - return Collections.enumeration(principals); - } - - /** - * {@inheritDoc} - **/ - public synchronized Enumeration getAuthCredentials() { - return Collections.enumeration(authCredentials); - } - - /** - * {@inheritDoc} - **/ - public Credential join(Authenticator authenticated) throws PeerGroupException { - - if (!(authenticated instanceof PasswdAuthenticator)) { - throw new ClassCastException("This is not my authenticator!"); - } - - if (this != authenticated.getSourceService()) { - throw new ClassCastException("This is not my authenticator!"); - } - - if (!authenticated.isReadyForJoin()) { - throw new PeerGroupException("Not Ready to join!"); - } - - String identity = ((PasswdAuthenticator) authenticated).getAuth1Identity(); - String password = ((PasswdAuthenticator) authenticated).getAuth2_Password(); - - if (!checkPasswd(identity, password)) { - throw new PeerGroupException("Incorrect Password!"); - } - - // FIXME 20010327 bondolo@jxta.org Make up the signed bit. - - Credential newCred; - - synchronized (this) { - newCred = new PasswdCredential(this, identity, "blah"); - - principals.add(newCred); - - authCredentials.add(authenticated.getAuthenticationCredential()); - } - - support.firePropertyChange("addCredential", null, newCred); - - if (null == getDefaultCredential()) { - setDefaultCredential(newCred); - } - - return newCred; - } - - /** - * {@inheritDoc} - **/ - public synchronized void resign() { - Iterator eachCred = Arrays.asList(principals.toArray()).iterator(); - - synchronized (this) { - principals.clear(); - authCredentials.clear(); - } - - setDefaultCredential(null); - - while (eachCred.hasNext()) { - PasswdCredential aCred = (PasswdCredential) eachCred.next(); - - aCred.setValid(false); - } - } - - /** - * {@inheritDoc} - **/ - public Credential makeCredential(Element element) throws PeerGroupException, Exception { - - return new PasswdCredential(this, element); - } - - /** - * Given an identity and an encoded password determine if the password is - * correct. - * - * @param identity the identity which the user is trying to claim - * @param passwd the password guess being tested. - * @return true if the password was correct for the specified identity - * otherwise false. - **/ - private boolean checkPasswd(String identity, String passwd) { - boolean result; - - if (!logins.containsKey(identity)) { - return false; - } - - String encodedPW = makePsswd(passwd); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Password \'" + passwd + "\' encodes as: \'" + encodedPW + "\'"); - } - - String mustMatch = (String) logins.get(identity); - - // if there is a null password for this identity then match everything. - if (mustMatch.equals("")) { - return true; - } - - result = encodedPW.equals(mustMatch); - - return result; - } - - /** - * This is the method used to make the password strings. We only provide - * one way encoding since we can compare the encoded strings. - * - *

            FIXME 20010402 bondolo : switch to use the standard - * crypt(3) algorithm for encoding the passwords. The current algorithm has - * been breakable since ancient times, crypt(3) is also weak, but harder to - * break. - * - * @param source the string to encode - * @return String the encoded version of the password. - * - **/ - public static String makePsswd(String source) { - - /** - * - * A->D B->Q C->K D->W E->H F->R G->T H->E I->N J->O K->G L->X M->C - * N->V O->Y P->S Q->F R->J S->P T->I U->L V->Z W->A X->B Y->M Z->U - * - **/ - - final String xlateTable = "DQKWHRTENOGXCVYSFJPILZABMU"; - - StringBuilder work = new StringBuilder(source); - - for (int eachChar = work.length() - 1; eachChar >= 0; eachChar--) { - char aChar = Character.toUpperCase(work.charAt(eachChar)); - - int replaceIdx = xlateTable.indexOf(aChar); - - if (-1 != replaceIdx) { - work.setCharAt(eachChar, (char) ('A' + replaceIdx)); - } - } - - return work.toString(); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/passwd/PasswdMembershipServiceBeanInfo.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/passwd/PasswdMembershipServiceBeanInfo.java deleted file mode 100644 index 14531216..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/passwd/PasswdMembershipServiceBeanInfo.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.passwd; - - -import java.beans.BeanDescriptor; -import java.beans.EventSetDescriptor; -import java.beans.PropertyChangeListener; -import java.beans.PropertyDescriptor; -import java.beans.SimpleBeanInfo; - -import java.beans.IntrospectionException; -import java.lang.reflect.UndeclaredThrowableException; - - -/** - * Our beaninfo - **/ -public class PasswdMembershipServiceBeanInfo extends SimpleBeanInfo { - - /** - * {@inheritDoc} - **/ - @Override - public BeanDescriptor getBeanDescriptor() { - return new BeanDescriptor(PasswdMembershipService.class); - } - - /** - * {@inheritDoc} - **/ - @Override - public EventSetDescriptor[] getEventSetDescriptors() { - try { - EventSetDescriptor changed = new EventSetDescriptor(PasswdMembershipService.class, "propertyChange" - , - PropertyChangeListener.class, "propertyChange"); - - changed.setDisplayName("bound property change"); - - EventSetDescriptor[] rv = { changed }; - - return rv; - } catch (IntrospectionException failed) { - throw new UndeclaredThrowableException(failed, "Configuration error"); - } - } - - /** - * {@inheritDoc} - **/ - @Override - public PropertyDescriptor[] getPropertyDescriptors() { - try { - PropertyDescriptor defaultcredential = new PropertyDescriptor("defaultCredential", PasswdMembershipService.class); - - defaultcredential.setBound(true); - - PropertyDescriptor rv[] = { defaultcredential }; - - return rv; - } catch (IntrospectionException failed) { - throw new UndeclaredThrowableException(failed, "Configuration error"); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/passwd/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/passwd/package.html deleted file mode 100644 index 34e85e71..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/passwd/package.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - The passwd membership service provides a Membership Service implementation - which is based on a password scheme similar to the POSIX - /etc/passwd system. - -

            This implementation is intended as an example of a - simple Membership Service and NOT as a practical secure - Membership Service. - - @see net.jxta.membership - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/CMKeyStoreManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/CMKeyStoreManager.java deleted file mode 100644 index 39a49f8c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/CMKeyStoreManager.java +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.security.KeyStore; - -import java.io.IOException; -import java.security.KeyStoreException; -import java.security.NoSuchProviderException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; - -import net.jxta.impl.cm.Cm; -import net.jxta.impl.peergroup.StdPeerGroup; - - -/** - * Manages a Keystore located within the JXTA CM. - **/ -public class CMKeyStoreManager implements KeyStoreManager { - - /** - * Log4J Logger - **/ - private final static transient Logger LOG = Logger.getLogger(CMKeyStoreManager.class.getName()); - - /** - * Our default keystore type. - **/ - private final static String DEFAULT_KEYSTORE_TYPE = "jks"; - - /** - * The keystore type - **/ - private final String keystore_type; - - /** - * The keystore type - **/ - private final String keystore_provider; - - /** - * The JXTA CM where the keystore lives. - **/ - private final Cm keystore_cm; - - /** - * The CM ID where the keystore lives. - **/ - private final ID keystore_location; - - /** - * Default constructor. - * - * @param type The keystore type to use. The current default is the "JKS" - * keystore which is specified via {@code null}. - * @param provider The JCE cryptographic provider to use for the keystore. - * May also be {@code null} for the default provider. - * @param group The peer group which will provide the CM. - * @param location The ID under which the keystore will be stored in the - * CM. - * @throws NoSuchProviderException Thrown if the requested provider is not - * available. - * @throws KeyStoreException Thrown for errors getting a keystore of the - * requested type. - **/ - public CMKeyStoreManager(String type, String provider, PeerGroup group, ID location) throws NoSuchProviderException, KeyStoreException { - - if (null == type) { - type = DEFAULT_KEYSTORE_TYPE; - provider = null; - } - - keystore_type = type; - - keystore_provider = provider; - - keystore_cm = ((StdPeerGroup) group).getCacheManager(); - - keystore_location = location; - - // check if we can get an instance. - if (null == keystore_provider) { - KeyStore.getInstance(keystore_type); - } else { - KeyStore.getInstance(keystore_type, keystore_provider); - } - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("pse location = " + keystore_location + " in " + keystore_cm); - } - } - - /** - * {@inheritDoc} - **/ - public boolean isInitialized() { - return isInitialized(null); - } - - /** - * {@inheritDoc} - **/ - public boolean isInitialized(char[] store_password) { - try { - KeyStore store; - - if (null == keystore_provider) { - store = KeyStore.getInstance(keystore_type); - } else { - store = KeyStore.getInstance(keystore_type, keystore_provider); - } - - InputStream is = keystore_cm.getInputStream("Raw", keystore_location.toString()); - - if (null == is) { - return false; - } - - store.load(is, store_password); - - return true; - } catch (Exception failed) { - return false; - } - } - - /** - * {@inheritDoc} - **/ - public void createKeyStore(char[] store_password) throws KeyStoreException, IOException { - try { - KeyStore store; - - if (null == keystore_provider) { - store = KeyStore.getInstance(keystore_type); - } else { - store = KeyStore.getInstance(keystore_type, keystore_provider); - } - - store.load(null, store_password); - - saveKeyStore(store, store_password); - } catch (NoSuchProviderException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchProviderException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (NoSuchAlgorithmException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (CertificateException failed) { - KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * {@inheritDoc} - **/ - public KeyStore loadKeyStore(char[] password) throws KeyStoreException, IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Loading (" + keystore_type + "," + keystore_provider + ") store from " + keystore_location); - } - - try { - KeyStore store; - - if (null == keystore_provider) { - store = KeyStore.getInstance(keystore_type); - } else { - store = KeyStore.getInstance(keystore_type, keystore_provider); - } - - InputStream is = keystore_cm.getInputStream("Raw", keystore_location.toString()); - - store.load(is, password); - - return store; - } catch (NoSuchAlgorithmException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (CertificateException failed) { - KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (NoSuchProviderException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchProviderException during keystore processing"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * {@inheritDoc} - **/ - public void saveKeyStore(KeyStore store, char[] password) throws IOException, KeyStoreException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Writing " + store + " to " + keystore_location); - } - - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - store.store(bos, password); - bos.close(); - - keystore_cm.save("Raw", keystore_location.toString(), bos.toByteArray(), Long.MAX_VALUE, 0); - } catch (NoSuchAlgorithmException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (CertificateException failed) { - KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * {@inheritDoc} - **/ - public void eraseKeyStore() throws IOException { - - keystore_cm.remove("Raw", keystore_location.toString()); - } - - /** - * {@inheritDoc} - **/ - public String toString() { - StringBuilder sb = new StringBuilder("PSE keystore details: \n"); - sb.append(" Class: ").append(this.getClass().getName()).append("\n"); - sb.append(" Type: ").append(keystore_type==null ? "" : keystore_type).append("\n"); - sb.append(" Provider: ").append(keystore_provider==null ? "" : keystore_provider).append("\n"); - sb.append(" Location: ").append(keystore_location==null ? "" : keystore_location.toString()).append("\n"); - return sb.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/DialogAuthenticator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/DialogAuthenticator.java deleted file mode 100644 index 42b79195..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/DialogAuthenticator.java +++ /dev/null @@ -1,492 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Insets; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Iterator; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPasswordField; - -import javax.crypto.EncryptedPrivateKeyInfo; - -import net.jxta.credential.AuthenticationCredential; -import net.jxta.id.ID; -import net.jxta.membership.InteractiveAuthenticator; -import net.jxta.peer.PeerID; - - -/** - * An interactive graphical authenticator associated with the PSE membership - * service. - * - * @see net.jxta.membership.Authenticator - * @see net.jxta.membership.InteractiveAuthenticator - * @see net.jxta.membership.MembershipService - * @see net.jxta.impl.membership.pse.PSEMembershipService - **/ -public final class DialogAuthenticator extends StringAuthenticator implements InteractiveAuthenticator { - - /** - * Entries we stick into the combo list - **/ - private static class JComboEntry { - ID itsID; - - X509Certificate itsCertificate; - - String itsName; - - JComboEntry(ID entryID, X509Certificate itsCert) { - itsID = entryID; - itsCertificate = itsCert; - itsName = PSEUtils.getCertSubjectCName(itsCertificate); - - if (null == itsName) { - itsName = "< no common name >"; - } - - // remove the -CA which is common to ca root certs. - if (itsName.endsWith("-CA")) { - itsName = itsName.substring(0, itsName.length() - 3); - } - } - - /** - * {@inheritDoc} - **/ - @Override - public String toString() { - return itsName; - } - } - - - /** - * Swing user interface for password entry and identity selection. - * - *

            FIXME bondolo 20040329 should be localizable. - **/ - private class PasswordDialog extends JDialog implements ActionListener { - - private boolean initKeyStore; - private final PeerID seedPeer; - private final X509Certificate seedCert; - private final EncryptedPrivateKeyInfo seedKey; - - private final JLabel storePassLabel; - private final JPasswordField storePassField; - - private final JLabel identityLabel; - private final JComboBox identityList; - - private final JLabel identityPassLabel; - private final JPasswordField identityPassField; - - private final JButton okButton; - - private final JButton cancelButton; - - private boolean canceled = true; - - /** - * Dialog to prompt for a password - **/ - PasswordDialog(PeerID seedPeer, X509Certificate seedCert, EncryptedPrivateKeyInfo seedKey) { - super(JOptionPane.getRootFrame(), ((null != seedCert) ? "Initialize JXTA Keystore" : "JXTA Secure Login") - , /* modal*/ - true); - - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - addWindowListener(new WindowAdapter() { - - /** - * @inheritDoc - */ - - @Override - public void windowClosing(WindowEvent e) { - canceled = true; - } - }); - - this.seedPeer = seedPeer; - this.seedCert = seedCert; - this.seedKey = seedKey; - - initKeyStore = (null != seedCert); - - JPanel contentPane = new JPanel(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.FIRST_LINE_START - , - GridBagConstraints.BOTH, new Insets(4, 4, 4, 4), 0, 0); - - storePassField = new JPasswordField("", 10); - - if (!initKeyStore) { - // add listener to populate identities list - storePassField.addKeyListener(new PasswordDialogKeyHandler()); - } - - if (!initKeyStore) { - identityList = new JComboBox(); - } else { - JComboEntry seedEntry = new JComboEntry(seedPeer, seedCert); - - Object[] names = { seedEntry }; - - identityList = new JComboBox(names); - identityList.setMaximumRowCount(1); - } - - identityPassField = new JPasswordField("", 10); - - identityPassField.addKeyListener(new PasswordDialogKeyHandler()); - - storePassLabel = new JLabel("Key Store Password"); - storePassLabel.setLabelFor(storePassField); - contentPane.add(storePassLabel, c); - c.gridx = 1; - contentPane.add(storePassField, c); - - c.gridx = 0; - c.gridy = 1; - c.anchor = GridBagConstraints.LINE_START; - identityLabel = new JLabel("Identity"); - identityLabel.setLabelFor(identityList); - contentPane.add(identityLabel, c); - c.gridx = 1; - c.fill = GridBagConstraints.BOTH; - contentPane.add(identityList, c); - - c.gridx = 0; - c.gridy = 2; - c.fill = GridBagConstraints.BOTH; - identityPassLabel = new JLabel("Identity Password"); - identityPassLabel.setLabelFor(identityPassField); - contentPane.add(identityPassLabel, c); - c.gridx = 1; - contentPane.add(identityPassField, c); - - JPanel buttonPanel = new JPanel(new GridLayout(/* rows*/1, /* cols*/0)); - - okButton = new JButton("OK"); - okButton.addActionListener(this); - buttonPanel.add(okButton); - - cancelButton = new JButton("Cancel"); - cancelButton.addActionListener(this); - buttonPanel.add(cancelButton); - - c.gridx = 0; - c.gridy = 3; - c.gridwidth = 2; - c.anchor = GridBagConstraints.LAST_LINE_END; - c.fill = GridBagConstraints.VERTICAL; - cancelButton.addActionListener(this); - contentPane.add(buttonPanel, c); - - setContentPane(contentPane); - - if (initKeyStore) { - identityPassField.requestFocusInWindow(); - } else { - storePassField.requestFocusInWindow(); - } - } - - /** - * Handler for key events. - **/ - private class PasswordDialogKeyHandler extends KeyAdapter { - - /** - * {@inheritDoc} - **/ - @Override - public void keyReleased(KeyEvent e) { - setOKState(); - } - } - - /** - **/ - private void setOKState() { - boolean enableOK = false; - - if (initKeyStore) { - enableOK = (null - != PSEUtils.pkcs5_Decrypt_pbePrivateKey(identityPassField.getPassword() - , - seedCert.getPublicKey().getAlgorithm(), seedKey)); - - storePassLabel.setEnabled(enableOK); - storePassField.setEnabled(enableOK); - } else { - boolean enableIdentityList = false; - - ID[] roots = getIdentities(storePassField.getPassword()); - - if (null != roots) { - Iterator eachRoot = Arrays.asList(roots).iterator(); - - while (eachRoot.hasNext()) { - ID aPeer = (ID) eachRoot.next(); - - try { - X509Certificate aCert = DialogAuthenticator.this.source.getPSEConfig().getTrustedCertificate(aPeer); - JComboEntry anEntry = new JComboEntry(aPeer, aCert); - - if (!enableIdentityList) { - enableIdentityList = true; - identityList.removeAllItems(); - identityList.setSelectedIndex(-1); - } - - identityList.addItem(anEntry); - identityList.setSelectedIndex(0); - } catch (Exception ignore) { - continue; - } - } - } - - if (enableIdentityList) { - identityList.setMaximumRowCount(identityList.getItemCount()); - } else { - identityList.removeAllItems(); - identityList.setSelectedIndex(-1); - identityPassField.setText(""); - } - - identityLabel.setEnabled(enableIdentityList); - identityList.setEnabled(enableIdentityList); - identityPassLabel.setEnabled(enableIdentityList); - identityPassField.setEnabled(enableIdentityList); - } - - if ((null != getIdentity()) && (null != getKeyStorePassword()) && (null != getIdentityPassword())) { - setAuth1_KeyStorePassword(getKeyStorePassword()); - setAuth2Identity(getIdentity()); - setAuth3_IdentityPassword(getIdentityPassword()); - enableOK = isReadyForJoin(); - } - - okButton.setEnabled(enableOK); - } - - /** - * {@inheritDoc} - **/ - public void actionPerformed(ActionEvent e) { - - if (okButton == e.getSource()) { - canceled = false; - dispose(); - } else if (cancelButton == e.getSource()) { - canceled = true; - dispose(); - } else {} - } - - public void showDialog() { - pack(); - setLocationRelativeTo(null); - - setOKState(); - - setVisible(true); - } - - /** - * Returns the KeyStore password. - * - * @return the KeyStore password. - **/ - public char[] getKeyStorePassword() { - if (!storePassField.isEnabled()) { - return null; - } - - char[] result = storePassField.getPassword(); - - return result; - } - - /** - * Returns the selected Identity. - * - * @return the selected Identity. - **/ - public ID getIdentity() { - if (!identityList.isEnabled()) { - return null; - } - - JComboEntry selectedIdentity = (JComboEntry) identityList.getSelectedItem(); - - if (null == selectedIdentity) { - return null; - } - - return selectedIdentity.itsID; - } - - /** - * Returns the Identity password. - * - * @return the Identity password. - **/ - public char[] getIdentityPassword() { - if (!identityPassField.isEnabled()) { - return null; - } - - char[] result = identityPassField.getPassword(); - - return result; - } - - /** - * Returns the final state of the dialog. Until the "OK" button is - * pressed the dialog is "cancelled". - * - * @param returns the final state of the dialog. - **/ - public boolean wasCanceled() { - return canceled; - } - } - - /** - * Creates an authenticator for the PSE membership service. Anything entered - * into the identity info section of the Authentication credential is - * ignored. - * - * @param source The instance of the PSE membership service which - * created this authenticator. - * @param application Anything entered into the identity info section of - * the Authentication credential is ignored. - **/ - DialogAuthenticator(PSEMembershipService source, AuthenticationCredential application) { - super(source, application); - - // XXX 20010328 bondolo@jxta.org Could do something with the authentication credential here. - } - - /** - * Creates an authenticator for the PSE membership service. Anything entered - * into the identity info section of the Authentication credential is - * ignored. - * - * @param source The instance of the PSE membership service which - * created this authenticator. - * @param application Anything entered into the identity info section of - * the Authentication credential is ignored. - **/ - DialogAuthenticator(PSEMembershipService source, AuthenticationCredential application, X509Certificate seedCert, EncryptedPrivateKeyInfo seedKey) { - super(source, application, seedCert, seedKey); - - // XXX 20010328 bondolo@jxta.org Could do something with the authentication credential here. - } - - /** - * {@inheritDoc} - **/ - @Override - public String getMethodName() { - return "DialogAuthentication"; - } - - /** - * {@inheritDoc} - **/ - public boolean interact() { - PasswordDialog p = new PasswordDialog(source.group.getPeerID(), seedCert, seedKey); - - p.showDialog(); - - if (p.wasCanceled()) { - setAuth1_KeyStorePassword((char[]) null); - setAuth2Identity((ID) null); - setAuth3_IdentityPassword((char[]) null); - - } else { - setAuth1_KeyStorePassword(p.getKeyStorePassword()); - setAuth2Identity(p.getIdentity()); - setAuth3_IdentityPassword(p.getIdentityPassword()); - } - - return !p.wasCanceled(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/EngineAuthenticator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/EngineAuthenticator.java deleted file mode 100644 index 37720c12..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/EngineAuthenticator.java +++ /dev/null @@ -1,365 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import java.net.URI; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.security.cert.X509Certificate; -import javax.crypto.EncryptedPrivateKeyInfo; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.security.KeyStoreException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.credential.AuthenticationCredential; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.membership.Authenticator; -import net.jxta.membership.MembershipService; - - -/** - * An authenticator associated with the PSE membership service. - * - *@see net.jxta.membership.Authenticator - *@see net.jxta.membership.MembershipService - **/ -public class EngineAuthenticator implements Authenticator { - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(EngineAuthenticator.class.getName()); - - /** - * The Membership Service which generated this authenticator. - **/ - transient PSEMembershipService source; - - /** - * The Authentication which was provided to the Apply operation of the - * membership service. - **/ - transient AuthenticationCredential application; - - /** - * - **/ - transient X509Certificate seedCert; - - /** - * - **/ - transient PSEAuthenticatorEngine authenticatorEngine; - - /** - * - **/ - // transient EncryptedPrivateKeyInfo seedKey; - - /** - * the password for that identity. - **/ - transient char[] store_password = null; - - /** - * the identity which is being claimed - **/ - transient ID identity = null; - - /** - * the password for that identity. - **/ - transient char[] key_password = null; - - /** - * Creates an authenticator for the PSE membership service. Anything entered - * into the identity info section of the Authentication credential is - * ignored. - * - * @param source The instance of the PSE membership service which - * created this authenticator. - * @param application Anything entered into the identity info section of - * the Authentication credential is ignored. - **/ - EngineAuthenticator(PSEMembershipService source, AuthenticationCredential application, PSEAuthenticatorEngine authenticatorEngine) { - // this( source, application ); - - this.source = source; - this.application = application; - this.seedCert = authenticatorEngine.getX509Certificate(); - this.authenticatorEngine = authenticatorEngine; - } - - /** - * Creates an authenticator for the PSE membership service. Anything entered - * into the identity info section of the Authentication credential is - * ignored. - * - * @param source The instance of the PSE membership service which - * created this authenticator. - * @param application Anything entered into the identity info section of - * the Authentication credential is ignored. - **/ - EngineAuthenticator(PSEMembershipService source, AuthenticationCredential application) { - this.source = source; - this.application = application; - - // XXX 20010328 bondolo@jxta.org Could do something with the authentication credential here. - } - - /** - * {@inheritDoc} - **/ - @Override - protected void finalize() throws Throwable { - if (null != store_password) { - Arrays.fill(store_password, '\0'); - } - - if (null != key_password) { - Arrays.fill(key_password, '\0'); - } - - super.finalize(); - } - - /** - * {@inheritDoc} - **/ - public MembershipService getSourceService() { - return (MembershipService) source.getInterface(); - } - - /** - * {@inheritDoc} - **/ - public AuthenticationCredential getAuthenticationCredential() { - return application; - } - - /** - * {@inheritDoc} - **/ - public String getMethodName() { - return "EngineAuthentication"; - } - - /** - * {@inheritDoc} - **/ - synchronized public boolean isReadyForJoin() { - if (null != seedCert) { - return authenticatorEngine.isEnginePresent(); - } else { - return source.pseStore.validPasswd(identity, store_password, key_password); - } - } - - /** - * Get KeyStore password - **/ - public char[] getAuth1_KeyStorePassword() { - return store_password; - } - - /** - * Set KeyStore password - **/ - public void setAuth1_KeyStorePassword(String store_password) { - if (null == store_password) { - setAuth1_KeyStorePassword((char[]) null); - } else { - setAuth1_KeyStorePassword(store_password.toCharArray()); - } - } - - /** - * Set KeyStore password - **/ - public void setAuth1_KeyStorePassword(char[] store_password) { - if (null != this.store_password) { - Arrays.fill(this.store_password, '\0'); - } - - if (null == store_password) { - this.store_password = null; - } else { - this.store_password = store_password.clone(); - } - } - - /** - * Return the available identities. - **/ - public PeerID[] getIdentities(char[] store_password) { - - if (seedCert != null) { - PeerID[] seed = { source.group.getPeerID() }; - - return seed; - } else { - try { - ID[] allkeys = source.pseStore.getKeysList(store_password); - - // XXX bondolo 20040329 it may be appropriate to login - // something other than a peer id. - List peersOnly = new ArrayList(); - - Iterator eachKey = Arrays.asList(allkeys).iterator(); - - while (eachKey.hasNext()) { - ID aKey = (ID) eachKey.next(); - - if (aKey instanceof PeerID) { - peersOnly.add(aKey); - } - } - - return (PeerID[]) peersOnly.toArray(new PeerID[peersOnly.size()]); - } catch (IOException failed) { - return null; - } catch (KeyStoreException failed) { - return null; - } - } - } - - public X509Certificate getCertificate(char[] store_password, ID aPeer) { - if (seedCert != null) { - if (aPeer.equals(source.group.getPeerID())) { - return seedCert; - } else { - return null; - } - } else { - try { - return source.pseStore.getTrustedCertificate(aPeer, store_password); - } catch (IOException failed) { - return null; - } catch (KeyStoreException failed) { - return null; - } - } - } - - /** - * Get Identity - **/ - public ID getAuth2Identity() { - return identity; - } - - /** - * Set Identity - **/ - public void setAuth2Identity(String id) { - try { - URI idURI = new URI(id); - ID identity = IDFactory.fromURI(idURI); - - setAuth2Identity(identity); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad ID"); - } - } - - /** - * Set Identity - **/ - public void setAuth2Identity(ID identity) { - this.identity = identity; - } - - /** - * Get identity password - **/ - public char[] getAuth3_IdentityPassword() { - return key_password; - } - - /** - * Set identity password - **/ - public void setAuth3_IdentityPassword(String key_password) { - setAuth3_IdentityPassword(key_password.toCharArray()); - } - - /** - * Set identity password - **/ - public void setAuth3_IdentityPassword(char[] key_password) { - if (null != this.key_password) { - Arrays.fill(this.key_password, '\0'); - } - - if (null == key_password) { - this.key_password = null; - } else { - this.key_password = key_password.clone(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/FileKeyStoreManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/FileKeyStoreManager.java deleted file mode 100644 index 21a2475f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/FileKeyStoreManager.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import net.jxta.logging.Logging; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.cert.CertificateException; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Manages a Keystore located within a single File. - */ -public class FileKeyStoreManager implements KeyStoreManager { - - /** - * Log4J Logger - */ - private final static transient Logger LOG = Logger.getLogger(URIKeyStoreManager.class.getName()); - - private final static String DEFAULT_KEYSTORE_TYPE = "jks"; - - private final static String DEFAULT_KEYSTORE_FILENAME = "jxta_keystore"; - - /** - * The keystore type - */ - private final String keystore_type; - - /** - * The keystore type - */ - private final String keystore_provider; - - /** - * The file where the keystore lives. This must be a file even if the - * keystore really is a set of files or a directory. - */ - private final File keystore_location; - - /** - * Default constructor. - * - * @param type keystore type - * @param provider the provider - * @param location Store location - * @throws NoSuchProviderException if the security provider requested is not available in the environment. - * @throws KeyStoreException if a keystore error occurs - */ - public FileKeyStoreManager(String type, String provider, File location) throws NoSuchProviderException, KeyStoreException { - if (null == type) { - type = DEFAULT_KEYSTORE_TYPE; - provider = null; - } - - // if provided a directory, use the default file name. - if (location.isDirectory()) { - location = new File(location, DEFAULT_KEYSTORE_FILENAME); - } - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("pse location = " + location); - } - - keystore_type = type; - - keystore_provider = provider; - - keystore_location = location; - - // check if we can get an instance. - if (null == keystore_provider) { - KeyStore.getInstance(keystore_type); - } else { - KeyStore.getInstance(keystore_type, keystore_provider); - } - } - - /** - * {@inheritDoc} - */ - public boolean isInitialized() { - return isInitialized(null); - } - - /** - * {@inheritDoc} - */ - public boolean isInitialized(char[] store_password) { - try { - KeyStore store; - - if (null == keystore_provider) { - store = KeyStore.getInstance(keystore_type); - } else { - store = KeyStore.getInstance(keystore_type, keystore_provider); - } - - store.load(keystore_location.toURI().toURL().openStream(), store_password); - - return true; - } catch (Exception failed) { - return false; - } - } - - /** - * {@inheritDoc} - */ - public void createKeyStore(char[] store_password) throws KeyStoreException, IOException { - try { - KeyStore store; - - if (null == keystore_provider) { - store = KeyStore.getInstance(keystore_type); - } else { - store = KeyStore.getInstance(keystore_type, keystore_provider); - } - - store.load(null, store_password); - - saveKeyStore(store, store_password); - } catch (NoSuchProviderException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchProviderException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (NoSuchAlgorithmException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (CertificateException failed) { - KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * {@inheritDoc} - */ - public KeyStore loadKeyStore(char[] password) throws KeyStoreException, IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Loading (" + keystore_type + "," + keystore_provider + ") store from " + keystore_location); - } - - try { - KeyStore store; - - if (null == keystore_provider) { - store = KeyStore.getInstance(keystore_type); - } else { - store = KeyStore.getInstance(keystore_type, keystore_provider); - } - - store.load(keystore_location.toURI().toURL().openStream(), password); - - return store; - } catch (NoSuchAlgorithmException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (CertificateException failed) { - KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (NoSuchProviderException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchProviderException during keystore processing"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * {@inheritDoc} - */ - public void saveKeyStore(KeyStore store, char[] password) throws KeyStoreException, IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Writing " + store + " to " + keystore_location); - } - - try { - OutputStream os = new FileOutputStream(keystore_location); - - store.store(os, password); - } catch (NoSuchAlgorithmException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (CertificateException failed) { - KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * {@inheritDoc} - */ - public void eraseKeyStore() throws IOException { - - if (keystore_location.isFile() && keystore_location.canWrite()) { - keystore_location.delete(); - } else { - throw new UnsupportedOperationException("Unable to delete"); - } - } - - /** - * {@inheritDoc} - **/ - public String toString() { - StringBuilder sb = new StringBuilder("PSE keystore details: \n"); - sb.append(" Class: ").append(this.getClass().getName()).append("\n"); - sb.append(" Type: ").append(keystore_type==null ? "" : keystore_type).append("\n"); - sb.append(" Provider: ").append(keystore_provider==null ? "" : keystore_provider).append("\n"); - sb.append(" Location: ").append(keystore_location==null ? "" : keystore_location.toString()).append("\n"); - return sb.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/KeyStoreManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/KeyStoreManager.java deleted file mode 100644 index 0775320c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/KeyStoreManager.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import java.io.IOException; -import java.security.KeyStore; -import java.security.KeyStoreException; - - -/** - * Abstracts the management of KeyStores. This is commonly used to abstract the - * location of the KeyStore and the details of creating, loading, saving and - * deleting the KeyStore. - *

            - *

            Applications should not assume that accesses to KeyStoreManager are - * thread safe. All access to the KeyStoreManager should be externally - * synchronized on the KeyStoreManager object. - */ -public interface KeyStoreManager { - - /** - * Returns true if the KeyStore has been initialized (created). - * Since this method does not provide a passphrase it is really only useful - * for determining if a new KeyStore needs to be created. - * - * @return true if the KeyStore has been previously initialized - * otherwise false. - * @throws KeyStoreException If the KeyStore is protected by a store - * password that has not been set. - */ - boolean isInitialized() throws KeyStoreException; - - /** - * Returns true if the Keystore has been initialized (created). - * This method also ensures that the provided passphrase is valid for the - * keystore. - * - * @param password The KeyStore passphrase. - * @return true if the Keystore has been initialized otherwise - * false. - * @throws KeyStoreException If an incorrect KeyStore password is provided. - */ - boolean isInitialized(char[] password) throws KeyStoreException; - - /** - * Create the KeyStore using the specified KeyStore passphrase. - * - * @param password The KeyStore passphrase. - * @throws KeyStoreException If an incorrect KeyStore passphrase is provided. - * @throws IOException If there is a problem creating the KeyStore. - */ - void createKeyStore(char[] password) throws IOException, KeyStoreException; - - /** - * Load the KeyStore. - * - * @param password The KeyStore passphrase. - * @throws KeyStoreException If an incorrect KeyStore password is provided. - * @throws IOException If there is a problem loading the KeyStore. - * @return the keystore - */ - KeyStore loadKeyStore(char[] password) throws IOException, KeyStoreException; - - /** - * Save the provided KeyStore using the specified KeyStore passphrase. - * - * @param store The KeyStore to save. - * @param password The encryption passphrase for the keystore. - * @throws IOException Thrown for errors writing the keystore. - * @throws KeyStoreException Thrown for errors with the provided key or key store. - */ - void saveKeyStore(KeyStore store, char[] password) throws IOException, KeyStoreException; - - /** - * Erase the KeyStore. Some KeyStore implementations may not allow the - * KeyStore container itself to be erased and in some cases specific - * certificates and keys may be unerasable. All implementations should - * erase all user provided certificates and keys. - * - * @throws IOException If there is a problem erasing the KeyStore or the - * KeyStore cannot be erased. - */ - void eraseKeyStore() throws IOException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEAuthenticatorEngine.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEAuthenticatorEngine.java deleted file mode 100644 index 2c386bba..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEAuthenticatorEngine.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.membership.pse; - - -import java.security.PublicKey; -import java.security.cert.X509Certificate; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.SignatureException; -import java.security.NoSuchAlgorithmException; - -import net.jxta.peergroup.PeerGroup; - - -/** - * - * @author aubergine - */ -public interface PSEAuthenticatorEngine { - - public PublicKey getPublicKey() throws SecurityException; - - public byte[] sign(byte[] data) throws InvalidKeyException, SignatureException, IOException; - - public String getSignatureAlgorithm(); - - public boolean isEnginePresent() throws SecurityException; - - public X509Certificate getX509Certificate() throws SecurityException; - - public char[] getKeyPass(PeerGroup peerGroup) throws SecurityException; - - public char[] getStorePass(PeerGroup peerGroup) throws SecurityException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEAuthenticatorEngineFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEAuthenticatorEngineFactory.java deleted file mode 100644 index d1c6cf9b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEAuthenticatorEngineFactory.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.exception.PeerGroupException; -import net.jxta.impl.protocol.PSEConfigAdv; - - -/** - * - * @author nick - */ -public abstract class PSEAuthenticatorEngineFactory { - - private static PSEAuthenticatorEngineFactory defaultEngine = null; - - public static void setPSESecurityEngineFactory(PSEAuthenticatorEngineFactory newEngine) { - synchronized (PSEAuthenticatorEngineFactory.class) { - defaultEngine = newEngine; - } - } - - /** - * Returns the default Authenticator Engine. - * - * @return The current default Authenticator Engine. - **/ - public static PSEAuthenticatorEngineFactory getDefault() { - synchronized (PSEAuthenticatorEngineFactory.class) { - if (defaultEngine == null) { - defaultEngine = new PSEAuthenticatorEngineDefaultFactory(); - } - - return defaultEngine; - } - } - - /** - * Creates a new Authenticator Engine instance based upon the context and configuration. - * - * @param service The service that this keystore manager will be working for. - * @param config The configuration parameters. - **/ - public abstract PSEAuthenticatorEngine getInstance(PSEMembershipService service, PSEConfigAdv config) throws PeerGroupException; - - /** - * Default implementation which provides the default behaviour (which is to do nothing). - **/ - private static class PSEAuthenticatorEngineDefaultFactory extends PSEAuthenticatorEngineFactory { - - @Override - public PSEAuthenticatorEngine getInstance(PSEMembershipService service, PSEConfigAdv config) throws PeerGroupException { - return null; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEConfig.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEConfig.java deleted file mode 100644 index b578083d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEConfig.java +++ /dev/null @@ -1,648 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.*; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Manages the state of a Personal Security Enviroment. - */ -public final class PSEConfig { - - /** - * Log4J Logger - */ - private final static transient Logger LOG = Logger.getLogger(PSEConfig.class.getName()); - - /** - * Manager for the keystore we are using. - */ - private final KeyStoreManager keystore_manager; - - /** - * The keystore passphrase. - */ - private char[] keystore_password = null; - - /** - * Standard constructor. - * - * @param storeManager The StoreManager to be used for this PSEConfig - * instance. - * @param store_password The passphrase for the keystore or null. - * The passphrase may be set independantly via - * {@link #setKeyStorePassword(char[])}. - */ - PSEConfig(KeyStoreManager storeManager, char[] store_password) { - this.keystore_manager = storeManager; - setKeyStorePassword(store_password); - } - - /** - * Sets the passphrase to be used when unlocking the keystore. - * - * @param store_password The passphrase used to unlock the keystore may be - * {@code null} for keystores with no passphrase. - */ - public final void setKeyStorePassword(char[] store_password) { - if (null != this.keystore_password) { - Arrays.fill(this.keystore_password, '\0'); - } - - if (null == store_password) { - this.keystore_password = null; - } else { - this.keystore_password = store_password.clone(); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void finalize() throws Throwable { - if (null != keystore_password) { - Arrays.fill(keystore_password, '\0'); - } - - super.finalize(); - } - - /** - * Returns {@code true} if the PSE has been initialized (created). Some - * keystore formats may not require initialization and may always return - * {@code true}. {@code false} may also be returned if the keystore passphrase is - * incorrect. - * - * @return {@code true} if the PSE has been previously initialized - * otherwise {@code false}. - */ - public boolean isInitialized() { - try { - if (keystore_password != null) { - return keystore_manager.isInitialized(keystore_password); - } else { - return keystore_manager.isInitialized(); - } - } catch (Exception ignored) { - return false; - } - } - - /** - * Initializes the PSE environment. - * - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public void initialize() throws KeyStoreException, IOException { - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Initializing new PSE keystore..."); - } - - synchronized (keystore_manager) { - try { - if (keystore_manager.isInitialized(keystore_password)) { - return; - } - - keystore_manager.createKeyStore(keystore_password); - } catch (KeyStoreException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failure accessing or creating keystore.", failed); - } - - keystore_manager.eraseKeyStore(); - - throw failed; - } - } - } - - /** - * Removes an existing PSE enviroment. - * - * @throws IOException If the PSE cannot be successfully deleted. - */ - public void erase() throws IOException { - synchronized (keystore_manager) { - keystore_manager.eraseKeyStore(); - } - } - - /** - * Gets a copy of the KeyStore associated with this PSE instance. The - * returned KeyStore is a copy and not tied to the instance maintained by - * the PSE. Changing the returned keystore will not result in changes to - * the PSE. - * - * @return The keystore or {@code null} if it cannot be retrieved. - */ - public KeyStore getKeyStore() { - Throwable failure; - - try { - return getKeyStore(keystore_password); - } catch (KeyStoreException failed) { - failure = failed; - } catch (IOException failed) { - failure = failed; - } - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failure recovering keystore : " + failure); - } - - return null; - } - - /** - * Gets a copy of the KeyStore associated with this PSE instance. The - * returned KeyStore is a copy and not tied to the instance maintained by - * the PSE. Changing the returned keystore will not result in changes to - * the PSE. - * - * @param store_password The passphrase used to unlock the keystore may be - * {@code null} for keystores with no passphrase. - * @return The keystore. - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - * @since JXTA 2.4 - */ - public KeyStore getKeyStore(char[] store_password) throws KeyStoreException, IOException { - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(store_password); - - return store; - } - } - - /** - * Check if the provided passwords are correct for the specified identity. - * - * @param id The identity to be validated. - * @param store_password The passphrase used to unlock the keystore may be - * {@code null} for keystores with no passphrase. - * @param key_password The passphrase associated with the private key or - * {@code null} if the key has no passphrase. - * @return {@code true} if the passwords were valid for the given id - * otherwise {@code false}. - */ - boolean validPasswd(ID id, char[] store_password, char[] key_password) { - - if (null == id) { - return false; - } - - Throwable failure; - - try { - synchronized (keystore_manager) { - KeyStore store; - - if (null != store_password) { - store = keystore_manager.loadKeyStore(store_password); - } else { - if (null != keystore_password) { - store = keystore_manager.loadKeyStore(keystore_password); - } else { - throw new UnrecoverableKeyException("KeyStore passphrase not initialized"); - } - } - - String alias = id.toString(); - - Key key = store.getKey(alias, key_password); - - return (null != key); - } - } catch (UnrecoverableKeyException failed) { - failure = failed; - } catch (NoSuchAlgorithmException failed) { - failure = failed; - } catch (KeyStoreException failed) { - failure = failed; - } catch (IOException failed) { - failure = failed; - } - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failure checking passphrase : " + failure); - } - - return false; - } - - /** - * Returns the list of the trusted certificates available in this keystore. - * - * @return an array of the IDs of the available trusted certificates. - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public ID[] getTrustedCertsList() throws KeyStoreException, IOException { - List trustedCertsList = new ArrayList(); - - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(keystore_password); - - Enumeration eachAlias = store.aliases(); - - while (eachAlias.hasMoreElements()) { - String anAlias = eachAlias.nextElement(); - - if (store.isCertificateEntry(anAlias) || store.isKeyEntry(anAlias)) { - try { - URI id = new URI(anAlias); - - trustedCertsList.add(IDFactory.fromURI(id)); - } catch (URISyntaxException badID) {// ignored - } - } - } - - return trustedCertsList.toArray(new ID[trustedCertsList.size()]); - } - } - - /** - * Returns the list of root certificates for which there is an associated - * local private key. - * - * @return an array of the available keys. May be an empty array. - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public ID[] getKeysList() throws KeyStoreException, IOException { - return getKeysList(keystore_password); - } - - /** - * Returns the list of root certificates for which there is an associated - * local private key. - * - * @param store_password The passphrase used to unlock the keystore may be - * {@code null} for keystores with no passphrase. - * @return an array of the available keys. May be an empty array. - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - ID[] getKeysList(char[] store_password) throws KeyStoreException, IOException { - List keyedRootsList = new ArrayList(); - - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(store_password); - - Enumeration eachAlias = store.aliases(); - - while (eachAlias.hasMoreElements()) { - String anAlias = eachAlias.nextElement(); - - if (store.isKeyEntry(anAlias)) { - try { - URI id = new URI(anAlias); - - keyedRootsList.add(IDFactory.fromURI(id)); - } catch (URISyntaxException badID) {// ignored - } - } - } - - return keyedRootsList.toArray(new ID[keyedRootsList.size()]); - } - } - - /** - * Returns the ID of the provided certificate or null if the certificate is - * not found in the keystore. - * - * @param cert The certificate who's ID is desired. - * @return The ID of the certificate or null if no matching - * Certificate was found. - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public ID getTrustedCertificateID(X509Certificate cert) throws KeyStoreException, IOException { - - String anAlias = null; - - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(keystore_password); - - anAlias = store.getCertificateAlias(cert); - } - - // not found. - if (null == anAlias) { - return null; - } - - try { - URI id = new URI(anAlias); - - return IDFactory.fromURI(id); - } catch (URISyntaxException badID) { - return null; - } - } - - /** - * Returns the trusted cert for the specified id. - * - * @param id The id of the Certificate to retrieve. - * @return Certificate for the specified ID or null if the store does not - * contain the specified certificate. - * @throws KeyStoreException When the wrong keystore key has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public X509Certificate getTrustedCertificate(ID id) throws KeyStoreException, IOException { - - return getTrustedCertificate(id, keystore_password); - } - - /** - * Returns the trusted cert for the specified id. - * - * @param id The id of the Certificate to retrieve. - * @param store_password The passphrase used to unlock the keystore may be - * {@code null} for keystores with no passphrase. - * @return Certificate for the specified ID or null if the store does not - * contain the specified certificate. - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - X509Certificate getTrustedCertificate(ID id, char[] store_password) throws KeyStoreException, IOException { - - String alias = id.toString(); - - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(store_password); - - if (!store.containsAlias(alias)) { - return null; - } - - return (X509Certificate) store.getCertificate(alias); - } - } - - /** - * Returns the trusted cert chain for the specified id. - * - * @param id The ID of the certificate who's certificate chain is desired. - * @return Certificate chain for the specified ID or null if the PSE does - * not contain the specified certificate. - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public X509Certificate[] getTrustedCertificateChain(ID id) throws KeyStoreException, IOException { - - String alias = id.toString(); - - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(keystore_password); - - if (!store.containsAlias(alias)) { - return null; - } - - Certificate certs[] = store.getCertificateChain(alias); - - if (null == certs) { - return null; - } - - X509Certificate x509certs[] = new X509Certificate[certs.length]; - - System.arraycopy(certs, 0, x509certs, 0, certs.length); - - return x509certs; - } - } - - /** - * Returns the private key for the specified ID. - * - * @param id The ID of the requested private key. - * @param key_password The passphrase associated with the private key or - * {@code null} if the key has no passphrase. - * @return PrivateKey for the specified ID. - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public PrivateKey getKey(ID id, char[] key_password) throws KeyStoreException, IOException { - - String alias = id.toString(); - - try { - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(keystore_password); - - if (!store.containsAlias(alias) || !store.isKeyEntry(alias)) { - return null; - } - - return (PrivateKey) store.getKey(alias, key_password); - } - } catch (NoSuchAlgorithmException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Something failed", failed); - } - - KeyStoreException failure = new KeyStoreException("Something Failed"); - - failure.initCause(failed); - throw failure; - } catch (UnrecoverableKeyException failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Key passphrase failure", failed); - } - - KeyStoreException failure = new KeyStoreException("Key passphrase failure"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * Returns true if the specified id is associated with a private - * key. - * - * @param id The ID of the requested private key. - * @return true if a private key with the specified ID is present - * otherwise false - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public boolean isKey(ID id) throws KeyStoreException, IOException { - return isKey(id, keystore_password); - } - - /** - * Returns true if the specified id is associated with a private - * key. - * - * @param id The ID of the requested private key. - * @param store_password The passphrase used to unlock the keystore may be - * {@code null} for keystores with no passphrase. - * @return true if a private key with the specified ID is present - * otherwise false - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public boolean isKey(ID id, char[] store_password) throws KeyStoreException, IOException { - String alias = id.toString(); - - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(store_password); - - return store.containsAlias(alias) & store.isKeyEntry(alias); - } - } - - /** - * Adds a trusted certificate with the specified id to the key store. The - * certificate replaces any existing certificate or private key stored at - * this ID. - * - * @param id The ID under which the certificate will be stored. - * @param cert Certificate for the specified ID. - * @throws KeyStoreException When the wrong keystore has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public void setTrustedCertificate(ID id, X509Certificate cert) throws KeyStoreException, IOException { - String alias = id.toString(); - - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(keystore_password); - - store.deleteEntry(alias); - - store.setCertificateEntry(alias, cert); - - keystore_manager.saveKeyStore(store, keystore_password); - } - } - - /** - * Adds a private key to the PSE using the specified ID. The key replaces - * any existing certificate or private key stored at this ID. The key is - * stored using the provided key passphrase. - * - * @param id The ID under which the certificate chain and private key will be stored. - * @param certchain The certificate chain matching the private key. - * @param key The private key to be stored in the kestore. - * @param key_password The passphrase associated with the private key or - * {@code null} if the key has no passphrase. - * @throws KeyStoreException When the wrong keystore key has been provided. - * @throws IOException For errors related to processing the keystore. - */ - public void setKey(ID id, Certificate[] certchain, PrivateKey key, char[] key_password) throws KeyStoreException, IOException { - - String alias = id.toString(); - - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(keystore_password); - - // Remove any existing entry. - store.deleteEntry(alias); - - store.setKeyEntry(alias, key, key_password, certchain); - - keystore_manager.saveKeyStore(store, keystore_password); - } - } - - /** - * Erases the specified id from the keystore. - * - * @param id The ID of the key or certificate to be deleted. - * @throws KeyStoreException When the wrong keystore password has been - * provided. - * @throws IOException For errors related to processing the keystore. - */ - public void erase(ID id) throws KeyStoreException, IOException { - String alias = id.toString(); - - synchronized (keystore_manager) { - KeyStore store = keystore_manager.loadKeyStore(keystore_password); - - store.deleteEntry(alias); - - keystore_manager.saveKeyStore(store, keystore_password); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSECredential.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSECredential.java deleted file mode 100644 index 0916f004..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSECredential.java +++ /dev/null @@ -1,861 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import net.jxta.credential.Credential; -import net.jxta.credential.CredentialPCLSupport; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.service.Service; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.SequenceInputStream; -import java.io.StringReader; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.InvalidKeyException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.CertPath; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateFactory; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; -import java.security.cert.Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Timer; -import java.util.TimerTask; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * This class provides the sub-class of Credential which is associated with the - * PSE membership service. - *

            - * There are two varients of the credential: - *

            - *

              - *
            • local - Generated as a result of local login. This type of - * credential can be used for signing and can be serialized for inclusion - * in protocols.
            • - *
            • remote - Generated as a result of deserialization from protocols. - * The credential is verified to ensure that the contents are valid at the - * time it is created.
            • - *
            - *

            - * The schema for this credential format: - *

            - *

            
            - *  <xs:element name="PSECred" type="jxta:PSECred" />
            - * 

            - * <xs:complexType name="PSECred"> - * <xs:sequence> - * <xs:element name="PeerGroupID" type="jxta:JXTAID" /> - * <xs:element name="PeerID" type="jxta:JXTAID" /> - * <!-- An X.509 Certificate --> - * <xs:element name="Certificate" type="xs:string" minOccurs="1" maxOccurs="unbounded" /> - * <!-- A SHA1WithRSA Signature --> - * <xs:element name="Signature" type="xs:string" /> - * </xs:sequence> - * </xs:complexType> - * </code>

            - *

            - * FIXME 20050625 bondolo If the certificate chain for a credential is - * updated in the PSE keystore after a credential is created then the - * credential instance will not reflect those changes. This can be a problem if - * the issuer chain changes or expiries are updated. Even though it's going to - * be hit on performance PSECredential needs to changed to be backed by the PSE - * keystore directly rather than containing the certs. Either that or some kind - * of notification systems. It's probably best to assume that our simple cm - * based keystore is the easiest and least dynamic case. Every other key store - * is going to be more dynamic and difficult. The work around for now is to - * force a membership resign everytime the keystore contents are changed. - * - * @see net.jxta.credential.Credential - * @see net.jxta.impl.membership.pse.PSEMembershipService - */ -public final class PSECredential implements Credential, CredentialPCLSupport { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(PSECredential.class.getName()); - - /** - * A Timer we use for managing the cert expirations. - */ - private static Timer expirationTimer = new Timer("PSECredential Expiration Timer", true); - - /** - * The MembershipService service which generated this credential. - *

            - * XXX 20030609 bondolo@jxta.org Perhaps this should be a weak reference. - */ - private PSEMembershipService source; - - /** - * The peer group associated with this credential. - */ - private ID peerGroupID = null; - - /** - * The peerid associated with this credential. - */ - private ID peerID = null; - - /** - * The pse alias from which this credential was generated. Only locally - * created credentials will be intialized with a key ID. - */ - private ID keyID = null; - - /** - * The identity associated with this credential - */ - private CertPath certs = null; - - /** - * The private key associated with this credential. Used for signing. Only - * a locally created credential will have an initialized private key. - */ - private PrivateKey privateKey = null; - - /** - * Optional Timer task - */ - private TimerTask becomesValidTask = null; - private TimerTask expiresTask = null; - - /** - * Are we still a valid credential? - */ - private boolean valid = true; - - /** - * Is this a local credential? - */ - private final boolean local; - - /** - * property change support - */ - private PropertyChangeSupport support = new PropertyChangeSupport(this); - - /** - * Create a new local credential. This credential can be used for signing - * and can be serialized. - */ - protected PSECredential(PSEMembershipService source, ID keyID, CertPath certChain, PrivateKey privateKey) throws IOException { - this.source = source; - this.peerID = source.group.getPeerID(); - this.peerGroupID = source.group.getPeerGroupID(); - setKeyID(keyID); - setCertificateChain(certChain); - setPrivateKey(privateKey); - this.local = true; - } - - /** - * Create a new remote credential. This credential cannot be used for - * signing and cannot be re-serialized. - */ - public PSECredential(Element root) { - this.local = false; - initialize(root); - } - - /** - * Create a new remote credential. This credential cannot be used for - * signing and cannot be re-serialized. - */ - public PSECredential(PSEMembershipService source, Element root) { - this.local = false; - this.source = source; - initialize(root); - - if (!peerGroupID.equals(source.group.getPeerGroupID())) { - throw new IllegalArgumentException( - "Credential is from a different group. " + peerGroupID + " != " + source.group.getPeerGroupID()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - - if (this == target) { - return true; - } - - if (target instanceof PSECredential) { - PSECredential asCred = (PSECredential) target; - - boolean result = peerID.equals(asCred.peerID) - && source.group.getPeerGroupID().equals(asCred.source.group.getPeerGroupID()); - - result &= certs.equals(asCred.certs); - - return result; - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - protected void finalize() throws Throwable { - if (null != becomesValidTask) { - becomesValidTask.cancel(); - } - - if (null != expiresTask) { - expiresTask.cancel(); - } - - super.finalize(); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = peerID.hashCode() * source.group.getPeerGroupID().hashCode() * certs.hashCode(); - - if (0 == result) { - result = 1; - } - - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "\"" + getSubject() + "\" " + getPeerID() + " [" + source + " / " + getPeerGroupID() + "]"; - } - - /** - * Add a listener - * - * @param listener the listener - */ - public void addPropertyChangeListener(PropertyChangeListener listener) { - support.addPropertyChangeListener(listener); - } - - /** - * Add a listener - * - * @param propertyName the property to watch - * @param listener the listener - */ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.addPropertyChangeListener(propertyName, listener); - } - - /** - * Remove a listener - * - * @param listener the listener - */ - public void removePropertyChangeListener(PropertyChangeListener listener) { - support.removePropertyChangeListener(listener); - } - - /** - * Remove a listener - * - * @param propertyName the property which was watched - * @param listener the listener - */ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.removePropertyChangeListener(propertyName, listener); - } - - /** - * {@inheritDoc} - */ - public ID getPeerGroupID() { - return peerGroupID; - } - - /** - * set the peer id associated with this credential - */ - private void setPeerGroupID(ID newID) { - this.peerGroupID = newID; - } - - /** - * {@inheritDoc} - */ - public ID getPeerID() { - return peerID; - } - - /** - * set the peer id associated with this credential - */ - private void setPeerID(PeerID peerID) { - this.peerID = peerID; - } - - /** - * {@inheritDoc} - *

            - * A PSE Credential is valid as long as the associated certificate is - * valid. - */ - public boolean isExpired() { - try { - ((X509Certificate) certs.getCertificates().get(0)).checkValidity(); - return false; - } catch (CertificateExpiredException expired) { - return true; - } catch (CertificateNotYetValidException notyet) { - return true; - } - } - - /** - * {@inheritDoc} - *

            - * A PSE Credential is valid as long as the associated certificate is - * valid and as long as the membership service still has the credential. - */ - public boolean isValid() { - return valid && !isExpired(); - } - - /** - * {@inheritDoc} - *

            - * A PSE Credential is valid as long as the associated certificate is - * valid. - */ - void setValid(boolean valid) { - boolean oldValid = isValid(); - - this.valid = valid; - - if (oldValid != valid) { - support.firePropertyChange("valid", oldValid, valid); - } - } - - /** - * {@inheritDoc} - */ - public Object getSubject() { - return ((X509Certificate) certs.getCertificates().get(0)).getSubjectDN(); - } - - /** - * {@inheritDoc} - */ - public Service getSourceService() { - return source; - } - - /** - * {@inheritDoc} - */ - public StructuredDocument getDocument(MimeMediaType encodeAs) throws Exception { - if (!isValid()) { - throw new javax.security.cert.CertificateException("Credential is not valid. Cannot generate document."); - } - - if (!local) { - throw new IllegalStateException("This credential is not a local credential and document cannot be created."); - } - - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(encodeAs, "jxta:Cred"); - - if (doc instanceof XMLDocument) { - ((XMLDocument) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - ((XMLDocument) doc).addAttribute("xml:space", "preserve"); - } - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("type", "jxta:PSECred"); - } - - Element e; - - e = doc.createElement("PeerGroupID", getPeerGroupID().toString()); - doc.appendChild(e); - - e = doc.createElement("PeerID", getPeerID().toString()); - doc.appendChild(e); - - // add the Certificate element - - net.jxta.impl.protocol.Certificate certChain = new net.jxta.impl.protocol.Certificate(); - - List certsList = certs.getCertificates(); - - certChain.setCertificates(certsList); - - StructuredDocument certsDoc = (StructuredDocument) certChain.getDocument(encodeAs); - - if (certsDoc instanceof Attributable) { - ((Attributable) certsDoc).addAttribute("type", certsDoc.getKey().toString()); - } - - StructuredDocumentUtils.copyElements(doc, doc, certsDoc, "Certificate"); - - // Add the signature. - - List someStreams = new ArrayList(3); - - try { - someStreams.add(new ByteArrayInputStream(getPeerGroupID().toString().getBytes("UTF-8"))); - someStreams.add(new ByteArrayInputStream(getPeerID().toString().getBytes("UTF-8"))); - for (Object aCertsList : certsList) { - X509Certificate aCert = (X509Certificate) aCertsList; - - someStreams.add(new ByteArrayInputStream(aCert.getEncoded())); - } - - InputStream signStream = new SequenceInputStream(Collections.enumeration(someStreams)); - - byte[] sig = source.peerSecurityEngine.sign(source.peerSecurityEngine.getSignatureAlgorithm(), this, signStream); - - e = doc.createElement("Signature", PSEUtils.base64Encode(sig)); - doc.appendChild(e); - } catch (java.io.UnsupportedEncodingException never) {// UTF-8 is always available - } - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("algorithm", source.peerSecurityEngine.getSignatureAlgorithm()); - } - - return doc; - } - - /** - * Returns the certificate associated with this credential. - * - * @return the certificate associated with this credential. - */ - public X509Certificate getCertificate() { - return (X509Certificate) certs.getCertificates().get(0); - } - - /** - * Returns the certificate chain associated with this credential. - * - * @return the certificate chain associated with this credential. - */ - public X509Certificate[] getCertificateChain() { - List certList = certs.getCertificates(); - - return (X509Certificate[]) certList.toArray(new X509Certificate[certList.size()]); - } - - /** - * Set the certificate associated with this credential - * - * @param certChain the certificate chain associated with this credential. - */ - private void setCertificateChain(CertPath certChain) { - - certs = certChain; - - Date now = new Date(); - Date becomesValid = ((X509Certificate) certs.getCertificates().get(0)).getNotBefore(); - Date expires = ((X509Certificate) certs.getCertificates().get(0)).getNotAfter(); - - if (becomesValid.compareTo(now) > 0) { - if (null != becomesValidTask) { - becomesValidTask.cancel(); - } - - becomesValidTask = new TimerTask() { - - @Override - public void run() { - support.firePropertyChange("expired", false, true); - if (valid) { - support.firePropertyChange("valid", false, true); - } - } - }; - - expirationTimer.schedule(becomesValidTask, becomesValid); - } - - if (null != expiresTask) { - expiresTask.cancel(); - } - - if (expires.compareTo(now) > 0) { - expiresTask = new TimerTask() { - - @Override - public void run() { - support.firePropertyChange("expired", true, false); - if (valid) { - support.firePropertyChange("valid", true, false); - } - } - }; - - expirationTimer.schedule(expiresTask, expires); - } - - boolean nowGood = (null == becomesValidTask) && (null != expiresTask); - - support.firePropertyChange("expired", true, nowGood); - setValid(nowGood); - } - - /** - * Returns the private key associated with this credential. Only valid for - * locally generated credentials. - * - * @return the private key associated with this credential. - * @deprecated Use <@link #getSigner(String)> or <@link #getSignatureVerifier(String)> instead. - */ - @Deprecated - public PrivateKey getPrivateKey() { - - if (!local) { - throw new IllegalStateException("This credential is not a local credential and cannot be used for signing."); - } - - if (null == privateKey) { - throw new IllegalStateException("This local credential is engine based and cannot provide the private key."); - } - - return privateKey; - } - - /** - * Sets the private key associated with this credential. - * - * @param privateKey the private key associated with this credential. - */ - private void setPrivateKey(PrivateKey privateKey) { - - this.privateKey = privateKey; - } - - /** - * Returns the key id associated with this credential, if any. Only locally - * generated credentials have a key ID. - * - * @return Returns the key id associated with this credential, if any. - */ - public ID getKeyID() { - return keyID; - } - - /** - * Sets the key id associated with this credential. - */ - private void setKeyID(ID keyID) { - this.keyID = keyID; - } - - /** - * Get a Signature object based upon the private key associated with this - * credential. - * - * @param algorithm the signing algorithm to use. - * @return Signature. - */ - public Signature getSigner(String algorithm) throws NoSuchAlgorithmException { - if (!local) { - throw new IllegalStateException("This credential is not a local credential and cannot be used for signing."); - } - - Signature sign = Signature.getInstance(algorithm); - - try { - sign.initSign(privateKey); - } catch (java.security.InvalidKeyException failed) { - IllegalStateException failure = new IllegalStateException("Invalid private key"); - - failure.initCause(failed); - throw failure; - } - - return sign; - } - - /** - * /** - * Get a Signature verifier object based upon the certificate associated - * with this credential. - * - * @param algorithm the signing algorithm to use. - * @return Signature. - */ - public Signature getSignatureVerifier(String algorithm) throws NoSuchAlgorithmException { - Signature verify = Signature.getInstance(algorithm); - - try { - verify.initVerify((X509Certificate) certs.getCertificates().get(0)); - } catch (java.security.InvalidKeyException failed) { - IllegalStateException failure = new IllegalStateException("Invalid certificate"); - - failure.initCause(failed); - throw failure; - } - - return verify; - } - - /** - * Process an individual element from the document. - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - */ - protected boolean handleElement(XMLElement elem) { - if (elem.getName().equals("PeerGroupID")) { - try { - ID pid = IDFactory.fromURI(new URI(elem.getTextValue())); - - setPeerGroupID((PeerGroupID) pid); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerGroupID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a group id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("PeerID")) { - try { - ID pid = IDFactory.fromURI(new URI(elem.getTextValue())); - - setPeerID((PeerID) pid); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad Peer ID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a peer id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals("Certificate")) { - // XXX Compatibility hack so that net.jxta.impl.protocol.Certificate will recognize element - // as a certificate. - if (null == elem.getAttribute("type")) { - elem.addAttribute("type", net.jxta.impl.protocol.Certificate.getMessageType()); - } - - net.jxta.impl.protocol.Certificate certChain = new net.jxta.impl.protocol.Certificate(elem); - - try { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - certs = cf.generateCertPath(Arrays.asList(certChain.getCertificates())); - } catch (java.security.cert.CertificateException failure) { - throw new IllegalArgumentException("bad certificates in chain."); - } - - return true; - } - - if (elem.getName().equals("Signature")) { - - if (null == certs) { - throw new IllegalArgumentException("Signature out of order in Credential."); - } - - List someStreams = new ArrayList(3); - - try { - byte[] signatureToCompare = PSEUtils.base64Decode(new StringReader(elem.getTextValue())); - - someStreams.add(new ByteArrayInputStream(getPeerGroupID().toString().getBytes("UTF-8"))); - someStreams.add(new ByteArrayInputStream(getPeerID().toString().getBytes("UTF-8"))); - Iterator eachCert = certs.getCertificates().iterator(); - - for (Certificate certificate : certs.getCertificates()) { - X509Certificate aCert = (X509Certificate) certificate; - - someStreams.add(new ByteArrayInputStream(aCert.getEncoded())); - } - - InputStream signStream = new SequenceInputStream(Collections.enumeration(someStreams)); - - // FIXME 20051007 bondolo Fix handling of signature type. - - if (!PSEUtils.verifySignature("SHA1WITHRSA", getCertificate(), signatureToCompare, signStream)) { - throw new IllegalArgumentException("Certificated did not match"); - } - } catch (Throwable failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to validate signature ", failed); - } - - throw new IllegalArgumentException("Failed to validate signature " + failed.getMessage()); - } - - return true; - } - - // element was not handled - return false; - } - - /** - * Intialize from a portion of a structured document. - */ - protected void initialize(Element root) { - - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XMLElement"); - } - - XMLElement doc = (XMLElement) root; - - String typedoctype = ""; - - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - String doctype = doc.getName(); - - if (!doctype.equals("jxta:PSECred") && !typedoctype.equals("jxta:PSECred")) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doctype); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled element \'" + elem.getName() + "\' in " + doc.getName()); - } - } - } - - // sanity check time! - - if (null == getSubject()) { - throw new IllegalArgumentException("subject was never initialized."); - } - - if (null == getPeerGroupID()) { - throw new IllegalArgumentException("peer group was never initialized."); - } - - if (null == getPeerID()) { - throw new IllegalArgumentException("peer id was never initialized."); - } - - if (null == certs) { - throw new IllegalArgumentException("certificates were never initialized."); - } - - // FIXME bondolo@jxta.org 20030409 should check for duplicate elements and for peergroup element - } - - public X509Certificate[] generateServiceCertificate(ID assignedID) throws IOException, KeyStoreException, InvalidKeyException, SignatureException { - return source.generateServiceCertificate(assignedID, this); - } - - public PSECredential getServiceCredential(ID assignedID) throws IOException, PeerGroupException, InvalidKeyException, SignatureException { - return source.getServiceCredential(assignedID, this); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSECrendentialBeanInfo.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSECrendentialBeanInfo.java deleted file mode 100644 index cf48a89b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSECrendentialBeanInfo.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import java.beans.BeanDescriptor; -import java.beans.EventSetDescriptor; -import java.beans.PropertyChangeListener; -import java.beans.PropertyDescriptor; -import java.beans.SimpleBeanInfo; - -import java.beans.IntrospectionException; -import java.lang.reflect.UndeclaredThrowableException; - - -/** - * BeanInfo for PSECrendential - **/ -public class PSECrendentialBeanInfo extends SimpleBeanInfo { - - /** - * {@inheritDoc} - **/ - @Override - public BeanDescriptor getBeanDescriptor() { - return new BeanDescriptor(PSECredential.class); - } - - /** - * {@inheritDoc} - **/ - @Override - public EventSetDescriptor[] getEventSetDescriptors() { - try { - EventSetDescriptor changed = new EventSetDescriptor(PSECredential.class, "propertyChange" - , - PropertyChangeListener.class, "propertyChange"); - - changed.setDisplayName("bound property change"); - - EventSetDescriptor[] rv = { changed }; - - return rv; - } catch (IntrospectionException failed) { - throw new UndeclaredThrowableException(failed, "Configuration error"); - } - } - - /** - * {@inheritDoc} - **/ - @Override - public PropertyDescriptor[] getPropertyDescriptors() { - try { - PropertyDescriptor subject = new PropertyDescriptor("subject", PSECredential.class); - - PropertyDescriptor peerid = new PropertyDescriptor("peerID", PSECredential.class); - - PropertyDescriptor peerGroupID = new PropertyDescriptor("peerGroupID", PSECredential.class); - - PropertyDescriptor certificate = new PropertyDescriptor("certificate", PSECredential.class); - - PropertyDescriptor privatekey = new PropertyDescriptor("privateKey", PSECredential.class); - - PropertyDescriptor expired = new PropertyDescriptor("expired", PSECredential.class); - - expired.setBound(true); - - PropertyDescriptor valid = new PropertyDescriptor("valid", PSECredential.class); - - valid.setBound(true); - - PropertyDescriptor rv[] = { subject, peerid, peerGroupID, certificate, privatekey, expired, valid }; - - return rv; - } catch (IntrospectionException failed) { - throw new UndeclaredThrowableException(failed, "Configuration error"); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEKeyStoreManagerFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEKeyStoreManagerFactory.java deleted file mode 100644 index 3d28b78b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEKeyStoreManagerFactory.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import java.util.NoSuchElementException; -import java.net.URI; -import java.io.File; - -import java.security.KeyStoreException; -import java.security.NoSuchProviderException; - -import net.jxta.peergroup.PeerGroup; -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.document.Element; -import net.jxta.protocol.ConfigParams; -import net.jxta.exception.PeerGroupException; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.XMLElement; - -import net.jxta.impl.cm.Cm; -import net.jxta.impl.peergroup.StdPeerGroup; -import net.jxta.impl.protocol.PSEConfigAdv; - - -/** - * Encapsulates the behaviour for creating KeyStoreManager Objects. - **/ -public abstract class PSEKeyStoreManagerFactory { - - /** - * The default KeyStoreManagerGenerator - **/ - private static PSEKeyStoreManagerFactory defaultGenerator = null; - - /** - * Sets the default KeyStoreManagerGenerator. - * - * @param newDefault The new default KeyStoreManagerGenerator. - **/ - public static void setDefault(PSEKeyStoreManagerFactory newDefault) { - synchronized (PSEKeyStoreManagerFactory.class) { - defaultGenerator = newDefault; - } - } - - /** - * Returns the default KeyStoreManagerGenerator. - * - * @return The current default KeyStoreManagerGenerator. - **/ - public static PSEKeyStoreManagerFactory getDefault() { - synchronized (PSEKeyStoreManagerFactory.class) { - if (defaultGenerator == null) { - defaultGenerator = new PSEKeyStoreManagerFactoryDefault(); - } - - return defaultGenerator; - } - } - - /** - * Creates a new KeyStoreManager instance based upon the context and configuration. - * - * @param service The service that this keystore manager will be working for. - * @param config The configuration parameters. - **/ - public abstract KeyStoreManager getInstance(PSEMembershipService service, PSEConfigAdv config) throws PeerGroupException; - - /** - * Provides the default behaviour for generating KeyStore managers for PSE Membership Service Instances. - **/ - private static class PSEKeyStoreManagerFactoryDefault extends PSEKeyStoreManagerFactory { - - /** - * {@inheritDoc} - * - *

            If no location is specified then use the CMKeyStoreManager otherwise use the URIKeyStoreManager. - **/ - @Override - public KeyStoreManager getInstance(PSEMembershipService service, PSEConfigAdv config) throws PeerGroupException { - - URI location = config.getKeyStoreLocation(); - KeyStoreManager store_manager; - - try { - if (null == location) { - store_manager = new CMKeyStoreManager(config.getKeyStoreType(), config.getKeyStoreProvider() - , - service.getGroup(), service.getAssignedID()); - } else { - if (!location.isAbsolute()) { - // Resolve the location of the keystore relative to our prefs location. - location = service.group.getStoreHome().resolve(location); - } - - store_manager = new URIKeyStoreManager(config.getKeyStoreType(), config.getKeyStoreProvider(), location); - } - - return store_manager; - } catch (NoSuchProviderException not_available) { - throw new PeerGroupException("Requested KeyStore provider not available", not_available); - } catch (KeyStoreException bad) { - throw new PeerGroupException("KeyStore failure initializing KeyStoreManager", bad); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEMembershipService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEMembershipService.java deleted file mode 100644 index 0a6de2e1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEMembershipService.java +++ /dev/null @@ -1,797 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.net.URI; -import java.security.PrivateKey; -import java.security.cert.CertPath; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; - -import java.io.IOException; -import java.security.KeyStoreException; -import java.security.NoSuchProviderException; -import java.security.cert.CertificateException; -import java.security.InvalidKeyException; -import java.security.SignatureException; -import java.security.spec.InvalidKeySpecException; -import java.util.NoSuchElementException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.credential.AuthenticationCredential; -import net.jxta.credential.Credential; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.membership.Authenticator; -import net.jxta.membership.MembershipService; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.service.Service; - -import net.jxta.id.ID; - -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.ProtocolNotSupportedException; - -import net.jxta.impl.protocol.Certificate; -import net.jxta.impl.protocol.PSEConfigAdv; -import net.jxta.impl.membership.pse.PSEUtils.IssuerInfo; - - -/** - * A JXTA Membership Service utilizing PKI to provide secure identities. - * - * @see net.jxta.membership.MembershipService - **/ -public final class PSEMembershipService implements MembershipService { - - /** - * Log4J Logger - **/ - private final static transient Logger LOG = Logger.getLogger(PSEMembershipService.class.getName()); - - /** - * Well known service specification identifier: pse membership - */ - public final static ModuleSpecID pseMembershipSpecID = (ModuleSpecID) ID.create( - URI.create(ID.URIEncodingName + ":" + ID.URNNamespace + ":uuid-DeadBeefDeafBabaFeedBabe000000050306")); - - /** - * the peergroup to which this service is associated. - **/ - PeerGroup group = null; - - /** - * The ID assigned to this instance. - **/ - private ID assignedID = null; - - /** - * The ModuleImplAdvertisement which was used to instantiate this service. - **/ - private ModuleImplAdvertisement implAdvertisement = null; - - /** - * The current set of principals associated with this peer within this peergroup. - **/ - private final List principals = new ArrayList(); - - /** - * The set of AuthenticationCredentials which were used to establish the principals. - **/ - private final List authCredentials = new ArrayList(); - - /** - * property change support - **/ - private final PropertyChangeSupport support; - - /** - * the keystore we are working with. - **/ - PSEConfig pseStore = null; - - /** - * the default credential - **/ - private PSECredential defaultCredential = null; - - /** - * The configuration we are using. - **/ - private PSEConfigAdv config; - - /** - * PSEPeerSecurityEngine ( and PSEAuthenticatorEngine ) loader - */ - - PSEPeerSecurityEngine peerSecurityEngine = null; - - private PSEAuthenticatorEngine authenticatorEngine = null; - - /** - * Default constructor. Normally only called by the peer group. - **/ - public PSEMembershipService() throws PeerGroupException { - support = new PropertyChangeSupport(getInterface()); - } - - /** - * @inheritDoc - **/ - public void addPropertyChangeListener(PropertyChangeListener listener) { - support.addPropertyChangeListener(listener); - } - - /** - * @inheritDoc - **/ - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.addPropertyChangeListener(propertyName, listener); - } - - /** - * @inheritDoc - **/ - public void removePropertyChangeListener(PropertyChangeListener listener) { - support.removePropertyChangeListener(listener); - } - - /** - * @inheritDoc - **/ - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - support.removePropertyChangeListener(propertyName, listener); - } - - /** - * {@inheritDoc} - **/ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - this.group = group; - this.assignedID = assignedID; - this.implAdvertisement = (ModuleImplAdvertisement) impl; - - ConfigParams configAdv = group.getConfigAdvertisement(); - - // Get our peer-defined parameters in the configAdv - Element param = configAdv.getServiceParam(assignedID); - - Advertisement paramsAdv = null; - - if (null != param) { - try { - paramsAdv = AdvertisementFactory.newAdvertisement((XMLElement) param); - } catch (NoSuchElementException ignored) { - ; - } - - if (!(paramsAdv instanceof PSEConfigAdv)) { - throw new PeerGroupException("Provided Advertisement was not a " + PSEConfigAdv.getAdvertisementType()); - } - - config = (PSEConfigAdv) paramsAdv; - } else { - // Create the default advertisement. - config = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType()); - } - - peerSecurityEngine = PSESecurityEngineFactory.getDefault().getInstance(this, config); - - authenticatorEngine = PSEAuthenticatorEngineFactory.getDefault().getInstance(this, config); - - KeyStoreManager storeManager = PSEKeyStoreManagerFactory.getDefault().getInstance(this, config); - - pseStore = new PSEConfig(storeManager, null); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring PSE Membership Service : " + assignedID); - - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: " + implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : " + implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : " + implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : " + implAdvertisement.getCode()); - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : " + group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID : " + group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID : " + group.getPeerID()); - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tPSE state : " + (pseStore.isInitialized() ? "inited" : "new")); - configInfo.append( - "\n\t\tPSE KeyStore location : " - + ((null != config.getKeyStoreLocation()) - ? config.getKeyStoreLocation().toString() - : assignedID.toString())); - configInfo.append( - "\n\t\tPSE KeyStore type : " + ((null != config.getKeyStoreType()) ? config.getKeyStoreType() : "")); - configInfo.append( - "\n\t\tPSE KeyStore provider : " - + ((null != config.getKeyStoreProvider()) ? config.getKeyStoreProvider() : "")); - LOG.config(configInfo.toString()); - } - - resign(); - } - - /** - * {@inheritDoc} - **/ - public Service getInterface() { - return this; - } - - /** - * {@inheritDoc} - **/ - public Advertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * {@inheritDoc} - * - *

            Currently this service starts by itself and does not expect - * arguments. - */ - public int startApp(String[] arg) { - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("PSE Membmership Service started."); - } - - return 0; - } - - /** - * {@inheritDoc} - **/ - public void stopApp() { - resign(); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("PSE Membmership Service stopped."); - } - } - - public PeerGroup getGroup() { - return group; - } - - public ID getAssignedID() { - return assignedID; - } - - /** - * {@inheritDoc} - * - *

            Supports methods "StringAuthentication", - * "DialogAuthentication", - * "EngineAuthentication" and - * "InteractiveAuthentication" (an alias for - * "DialogAuthentication") - **/ - public Authenticator apply(AuthenticationCredential application) throws ProtocolNotSupportedException { - - String method = application.getMethod(); - - boolean newKey; - - if (!pseStore.isInitialized()) { - // It is not inited, it's new. - newKey = true; - } else { - X509Certificate configCert = config.getCertificate(); - - if (null != configCert) { - try { - ID allTrustedCerts[] = pseStore.getTrustedCertsList(); - - Iterator eachTrustedCert = Arrays.asList(allTrustedCerts).iterator(); - - newKey = true; - - // See if the config cert is already in the keystore. - while (eachTrustedCert.hasNext()) { - ID aTrustedCertID = (ID) eachTrustedCert.next(); - - if (pseStore.isKey(aTrustedCertID)) { - X509Certificate aTrustedCert = pseStore.getTrustedCertificate(aTrustedCertID); - - if (aTrustedCert.equals(configCert)) { - newKey = false; - break; - } - } - } - } catch (KeyStoreException bad) { - // The keystore is probably initialized but locked. Nothing else we can do. - newKey = false; - } catch (IOException bad) { - // Could not read the keystore. I'm not sure it wouldn't be better to just fail. - newKey = false; - } - } else { - // don't have anything to validate against. - newKey = false; - } - } - - if ("StringAuthentication".equals(method)) { - if (newKey) { - return new StringAuthenticator(this, application, config.getCertificate(), config.getEncryptedPrivateKey()); - } else { - return new StringAuthenticator(this, application); - } - } else if ("EngineAuthentication".equals(method)) { - if (pseStore.isInitialized()) { - return new EngineAuthenticator(this, application, authenticatorEngine); - } else { - return new EngineAuthenticator(this, application, authenticatorEngine); - } - } else if ("DialogAuthentication".equals(method) || "InteractiveAuthentication".equals(method) || (null == method)) { - if (newKey) { - return new DialogAuthenticator(this, application, config.getCertificate(), config.getEncryptedPrivateKey()); - } else { - return new DialogAuthenticator(this, application); - } - } else { - throw new ProtocolNotSupportedException("Authentication method not recognized"); - } - } - - /** - * {@inheritDoc} - **/ - public Credential getDefaultCredential() { - return defaultCredential; - } - - /** - * Sets the default credential. Also updates the peer advertisement with - * the certificate of the default credential. - * - * @param newDefault the new default credential. May also be - * null if no default is desired. - **/ - private void setDefaultCredential(PSECredential newDefault) { - - Credential oldDefault = defaultCredential; - - synchronized (this) { - defaultCredential = newDefault; - } - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("New Default credential : " + newDefault); - } - - try { - // include the root cert in the peer advertisement - PeerAdvertisement peeradv = group.getPeerAdvertisement(); - - if (null != newDefault) { - // include the root cert in the peer advertisement - XMLDocument paramDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - - Certificate peerCerts = new Certificate(); - - peerCerts.setCertificates(newDefault.getCertificateChain()); - - XMLDocument peerCertsAsDoc = (XMLDocument) peerCerts.getDocument(MimeMediaType.XMLUTF8); - - StructuredDocumentUtils.copyElements(paramDoc, paramDoc, peerCertsAsDoc, "RootCert"); - - peeradv.putServiceParam(PeerGroup.peerGroupClassID, paramDoc); - } else { - peeradv.removeServiceParam(PeerGroup.peerGroupClassID); - } - } catch (Exception ignored) { - ; - } - - support.firePropertyChange("defaultCredential", oldDefault, newDefault); - } - - /** - * {@inheritDoc} - **/ - public Enumeration getCurrentCredentials() { - List credList = new ArrayList(principals); - - return Collections.enumeration(credList); - } - - /** - * {@inheritDoc} - **/ - public Enumeration getAuthCredentials() { - List credList = new ArrayList(authCredentials); - - return Collections.enumeration(credList); - } - - /** - * {@inheritDoc} - **/ - public Credential join(Authenticator authenticated) throws PeerGroupException { - - if (this != authenticated.getSourceService()) { - throw new ClassCastException("This is not my authenticator!"); - } - - if (!authenticated.isReadyForJoin()) { - throw new PeerGroupException("Authenticator not ready to join!"); - } - - PSECredential newCred; - - char[] store_password = null; - ID identity; - char[] key_password = null; - - try { - if (authenticated instanceof StringAuthenticator) { - StringAuthenticator auth = (StringAuthenticator) authenticated; - - store_password = auth.getAuth1_KeyStorePassword(); - identity = auth.getAuth2Identity(); - key_password = auth.getAuth3_IdentityPassword(); - } else if (authenticated instanceof EngineAuthenticator) { - EngineAuthenticator auth = (EngineAuthenticator) authenticated; - - store_password = auth.getAuth1_KeyStorePassword(); - identity = auth.getAuth2Identity(); - key_password = auth.getAuth3_IdentityPassword(); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("I dont know how to deal with this authenticator " + authenticated); - } - - throw new PeerGroupException("I dont know how to deal with this authenticator"); - } - - if (null != store_password) { - pseStore.setKeyStorePassword(store_password); - } - - if (!pseStore.isInitialized()) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Initializing the PSE key store."); - } - - try { - pseStore.initialize(); - } catch (KeyStoreException bad) { - throw new PeerGroupException("Could not initialize new PSE keystore.", bad); - } catch (IOException bad) { - throw new PeerGroupException("Could not initialize new PSE keystore.", bad); - } - } - - try { - ID[] allkeys = pseStore.getKeysList(); - - if (!Arrays.asList(allkeys).contains(identity)) { - // Add this key to the keystore. - X509Certificate[] seed_cert = config.getCertificateChain(); - - if (null == seed_cert) { - throw new IOException("Could not read root certificate chain"); - } - - PrivateKey seedPrivKey = config.getPrivateKey(key_password); - - if (null == seedPrivKey) { - throw new IOException("Could not read private key"); - } - - pseStore.setKey(identity, seed_cert, seedPrivKey, key_password); - } - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not save new key pair.", failed); - } - - throw new PeerGroupException("Could not save new key pair.", failed); - } catch (KeyStoreException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not save new key pair.", failed); - } - - throw new PeerGroupException("Could not save new key pair.", failed); - } - - try { - X509Certificate certList[] = pseStore.getTrustedCertificateChain(identity); - - if (null == certList) { - certList = new X509Certificate[1]; - - certList[0] = pseStore.getTrustedCertificate(identity); - - if (certList[0] == null && authenticatorEngine != null) { - certList[0] = authenticatorEngine.getX509Certificate(); - } - } - - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - CertPath certs = cf.generateCertPath(Arrays.asList(certList)); - - PrivateKey privateKey = pseStore.getKey(identity, key_password); - - newCred = new PSECredential(this, identity, certs, privateKey); - - synchronized (this) { - principals.add(newCred); - - authCredentials.add(authenticated.getAuthenticationCredential()); - } - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not create credential.", failed); - } - - throw new PeerGroupException("Could not create credential.", failed); - } catch (KeyStoreException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not create credential.", failed); - } - - throw new PeerGroupException("Could not create credential.", failed); - } catch (CertificateException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not create credential.", failed); - } - - throw new PeerGroupException("Could not create credential.", failed); - } - } finally { - if (null != store_password) { - Arrays.fill(store_password, '\0'); - } - - if (null != key_password) { - Arrays.fill(key_password, '\0'); - } - } - - // XXX bondolo potential but unlikely race condition here. - if (null == getDefaultCredential()) { - setDefaultCredential(newCred); - } - - support.firePropertyChange("addCredential", null, newCred); - - return newCred; - } - - /** - * {@inheritDoc} - **/ - public void resign() { - Iterator eachCred = Arrays.asList(principals.toArray()).iterator(); - - synchronized (this) { - principals.clear(); - authCredentials.clear(); - } - - setDefaultCredential(null); - - // clear the keystore password. - pseStore.setKeyStorePassword(null); - - while (eachCred.hasNext()) { - PSECredential aCred = (PSECredential) eachCred.next(); - - aCred.setValid(false); - } - } - - /** - * {@inheritDoc} - **/ - public Credential makeCredential(Element element) { - - return new PSECredential(this, element); - } - - /** - * Returns the key store object associated with this PSE Membership Service. - **/ - public PSEConfig getPSEConfig() { - return pseStore; - } - - /** - * Service Certificates Support - */ - - /** - * Generate a new service certificate for the assigned ID given an authenticated local credential. - * - * @param assignedID The assigned ID of the service credential. - * @param credential The issuer credential for the service credential. - **/ - X509Certificate[] generateServiceCertificate(ID assignedID, PSECredential credential) throws IOException, KeyStoreException, InvalidKeyException, SignatureException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Generating new service cert for " + assignedID); - } - - IssuerInfo serviceinfo = peerSecurityEngine.generateCertificate(credential); - - // write the client root cert and private key - X509Certificate[] serviceChain = { serviceinfo.cert, serviceinfo.issuer }; - - char keyPass[]; - - if (null != serviceinfo.issuerPkey) { - ByteArrayInputStream bis = new ByteArrayInputStream(serviceinfo.issuerPkey.getEncoded()); - byte privateKeySignature[] = peerSecurityEngine.sign(null, credential, bis); - - keyPass = PSEUtils.base64Encode(privateKeySignature, false).toCharArray(); - } else { - keyPass = authenticatorEngine.getKeyPass(group); - } - - getPSEConfig().setKey(assignedID, serviceChain, serviceinfo.subjectPkey, keyPass); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Generated new service cert"); - } - - return serviceChain; - } - - /** - * Recover the service credential for the assigned ID given an authenticated local credential. - * - * @param assignedID The assigned ID of the service credential. - * @param credential The issuer credential for the service credential. - **/ - public PSECredential getServiceCredential(ID assignedID, PSECredential credential) throws IOException, PeerGroupException, InvalidKeyException, SignatureException { - - PSECredential pseCredential = null; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting service redential for " + assignedID); - } - - Authenticator authenticate = null; - - if (null != authenticatorEngine) { - AuthenticationCredential authCred = new AuthenticationCredential(group, "EngineAuthentication", null); - - try { - authenticate = apply(authCred); - } catch (Exception failed) { - ; - } - - if (null == authenticate) { - return null; - } - - EngineAuthenticator auth = (EngineAuthenticator) authenticate; - - auth.setAuth1_KeyStorePassword(authenticatorEngine.getStorePass(group)); - auth.setAuth2Identity(assignedID); - auth.setAuth3_IdentityPassword(authenticatorEngine.getKeyPass(group)); - } else { - AuthenticationCredential authCred = new AuthenticationCredential(group, "StringAuthentication", null); - - try { - authenticate = apply(authCred); - } catch (Exception failed) { - ; - } - - if (null == authenticate) { - return null; - } - - PrivateKey privateKey = credential.getPrivateKey(); - - // make a new service certificate - ByteArrayInputStream bis = new ByteArrayInputStream(privateKey.getEncoded()); - byte privateKeySignature[] = peerSecurityEngine.sign(null, credential, bis); - String passkey = PSEUtils.base64Encode(privateKeySignature, false); - - StringAuthenticator auth = (StringAuthenticator) authenticate; - - auth.setAuth1_KeyStorePassword((String) null); - auth.setAuth2Identity(assignedID); - auth.setAuth3_IdentityPassword(passkey); - } - - if (authenticate.isReadyForJoin()) { - pseCredential = (PSECredential) join(authenticate); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not authenticate service credential"); - } - } - - return pseCredential; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEMembershipServiceBeanInfo.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEMembershipServiceBeanInfo.java deleted file mode 100644 index 559a61ca..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEMembershipServiceBeanInfo.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.membership.pse; - - -import java.beans.BeanDescriptor; -import java.beans.EventSetDescriptor; -import java.beans.SimpleBeanInfo; -import java.beans.PropertyDescriptor; - -import java.beans.IntrospectionException; -import java.lang.reflect.UndeclaredThrowableException; - - -/** - * Our beaninfo - **/ -public class PSEMembershipServiceBeanInfo extends SimpleBeanInfo { - - /** - * {@inheritDoc} - **/ - @Override - public BeanDescriptor getBeanDescriptor() { - return new BeanDescriptor(PSEMembershipService.class); - } - - /** - * {@inheritDoc} - **/ - @Override - public EventSetDescriptor[] getEventSetDescriptors() { - try { - EventSetDescriptor changed = new EventSetDescriptor(PSEMembershipService.class, "propertyChange" - , - java.beans.PropertyChangeListener.class, "propertyChange"); - - changed.setDisplayName("bound property change"); - - EventSetDescriptor[] rv = { changed }; - - return rv; - } catch (IntrospectionException failed) { - throw new UndeclaredThrowableException(failed, "Configuration error"); - } - } - - /** - * {@inheritDoc} - **/ - @Override - public PropertyDescriptor[] getPropertyDescriptors() { - try { - PropertyDescriptor defaultcredential = new PropertyDescriptor("defaultCredential", PSEMembershipService.class - , - "getDefaultCredential", "setDefaultCredential"); - - defaultcredential.setBound(true); - - PropertyDescriptor addcredential = new PropertyDescriptor("addCredential", PSEMembershipService.class); - - addcredential.setBound(true); - - PropertyDescriptor rv[] = { addcredential, defaultcredential }; - - return rv; - } catch (IntrospectionException failed) { - throw new UndeclaredThrowableException(failed, "Configuration error"); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEPeerSecurityEngine.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEPeerSecurityEngine.java deleted file mode 100644 index 11c544b6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEPeerSecurityEngine.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.membership.pse; - - -import java.io.InputStream; -import java.io.IOException; -import java.security.PublicKey; -import java.security.InvalidKeyException; -import java.security.Signature; -import java.security.SignatureException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.KeyPair; - -import javax.security.auth.x500.X500Principal; - -import net.jxta.impl.membership.pse.PSEUtils.IssuerInfo; - - -/** - * Provides algorithm support for PSE. - * - **/ -public interface PSEPeerSecurityEngine { - - /** - * Cryptographically sign an input stream using the specified credential - * with the specified algorithm. - * - * @param algorithm The signature algorithm to use. - * @param credential The credential which is signing the stream. - * @param bis The input stream to be signed. - * @return The resulting signature. - **/ - public byte[] sign(String algorithm, PSECredential credential, InputStream bis) throws InvalidKeyException, SignatureException, IOException; - - /** - * Cryptographically verify a signature against an input stream using the - * specified credential with the specified algorithm. - * - * @param algorithm The signature algorithm to use. - * @param signature The signature to be verified. - * @param credential The credential which is signing the stream. - * @param bis The input stream to be signed. - * @return {@code true} If the signature is valid otherwise {@code false}. - **/ - public boolean verify(String algorithm, PSECredential credential, byte[] signature, InputStream bis) throws InvalidKeyException, SignatureException, IOException; - - /** - * Generate a new service certificate. - * - * @param credential The credential which will be the issuer of the service certificate. - **/ - public IssuerInfo generateCertificate(PSECredential credential) throws SecurityException; - - /** - * Returns the default signature algorithm for this security engine. - **/ - public String getSignatureAlgorithm(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSESecurityEngineFactory.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSESecurityEngineFactory.java deleted file mode 100644 index b108b3f5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSESecurityEngineFactory.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.security.PrivateKey; -import java.security.cert.X509Certificate; - -import java.io.IOException; -import java.security.InvalidKeyException; -import java.security.SignatureException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.exception.PeerGroupException; -import net.jxta.impl.protocol.PSEConfigAdv; - -import net.jxta.impl.membership.pse.PSEUtils.IssuerInfo; - - -/** - * A factory for PSE Security Engines. - * - * @see PSEPeerSecurityEngine - */ -public abstract class PSESecurityEngineFactory { - - private static PSESecurityEngineFactory defaultSecurityEngine = null; - - /** - * Set the default PSESecurityEngineFactoryss - **/ - public static void setPSESecurityEngineManager(PSESecurityEngineFactory newSecurityEngine) { - synchronized (PSESecurityEngineFactory.class) { - defaultSecurityEngine = newSecurityEngine; - } - } - - /** - * Returns the default Security Engine Factory. - * - * @return The current default Security Engine Factory. - **/ - public static PSESecurityEngineFactory getDefault() { - synchronized (PSESecurityEngineFactory.class) { - if (defaultSecurityEngine == null) { - defaultSecurityEngine = new PSESecurityEngineDefaultFactory(); - } - - return defaultSecurityEngine; - } - } - - /** - * Creates a new Peer Security Engine instance based upon the context and configuration.sss - * - * @param service The service that this keystore manager will be working for. - * @param config The configuration parameters. - **/ - public abstract PSEPeerSecurityEngine getInstance(PSEMembershipService service, PSEConfigAdv config) throws PeerGroupException; - - /** - * Default implementation which provides the default behaviour (which is to do nothing). - **/ - private static class PSESecurityEngineDefaultFactory extends PSESecurityEngineFactory { - @Override - public PSEPeerSecurityEngine getInstance(PSEMembershipService service, PSEConfigAdv config) throws PeerGroupException { - return new PSEPeerSecurityEngineDefault(); - } - } - - - /** - * Default implementation which provides the default behaviour. - **/ - private static class PSEPeerSecurityEngineDefault implements PSEPeerSecurityEngine { - - /** - * Log4J Logger - **/ - private static final Logger LOG = Logger.getLogger(PSEPeerSecurityEngineDefault.class.getName()); - - /** - * {@inheritDoc} - **/ - public byte[] sign(String algorithm, PSECredential credential, InputStream bis) throws InvalidKeyException, SignatureException, IOException { - - if (null == algorithm) { - algorithm = getSignatureAlgorithm(); - } - - return PSEUtils.computeSignature(algorithm, credential.getPrivateKey(), bis); - } - - /** - * {@inheritDoc} - **/ - public boolean verify(String algorithm, PSECredential credential, byte[] signature, InputStream bis) throws InvalidKeyException, SignatureException, IOException { - if (null == algorithm) { - algorithm = getSignatureAlgorithm(); - } - - return PSEUtils.verifySignature(algorithm, credential.getCertificate(), signature, bis); - } - - /** - * {@inheritDoc} - **/ - public IssuerInfo generateCertificate(PSECredential credential) throws SecurityException { - - // we need a new cert. - IssuerInfo info = new IssuerInfo(); - - info.cert = credential.getCertificate(); - info.subjectPkey = credential.getPrivateKey(); - String cname = PSEUtils.getCertSubjectCName(info.cert); - - if (null != cname) { - // remove the -CA which is common to ca root certs. - if (cname.endsWith("-CA")) { - cname = cname.substring(0, cname.length() - 3); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Generating new service cert for \'" + cname + "\'"); - } - - // generate the service cert and private key - IssuerInfo serviceinfo = PSEUtils.genCert(cname, info); - - // IssuerInfo serviceinfo = membership.genCert( cname, info, "SHA1withRSA" ); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Generated new service cert for \'" + cname + "\'"); - } - - return serviceinfo; - } - - /** - * {@inheritDoc} - **/ - public String getSignatureAlgorithm() { - return "SHA1withRSA"; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEUtils.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEUtils.java deleted file mode 100644 index 9e923a7b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/PSEUtils.java +++ /dev/null @@ -1,874 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import net.jxta.impl.util.BASE64InputStream; -import net.jxta.impl.util.BASE64OutputStream; -import net.jxta.logging.Logging; -import org.bouncycastle.asn1.x509.X509NameTokenizer; -import org.bouncycastle.asn1.DERObjectIdentifier; -import org.bouncycastle.jce.X509Principal; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.x509.X509V3CertificateGenerator; - -import javax.crypto.Cipher; -import javax.crypto.EncryptedPrivateKeyInfo; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.PBEParameterSpec; -import javax.security.auth.x500.X500Principal; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.math.BigInteger; -import java.security.AlgorithmParameters; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.Security; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; -import java.util.Calendar; -import java.util.Date; -import java.util.Hashtable; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Singleton class of static utility methods. - */ -public final class PSEUtils { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(PSEUtils.class.getName()); - - /** - * Singleton instance. - */ - private static final PSEUtils UTILS = new PSEUtils(); - - /** - * A SecureRandom for generating keys. - */ - final transient SecureRandom srng = new SecureRandom(); - - /** - * Singleton utility class - */ - private PSEUtils() { - - try { - ClassLoader sysloader = ClassLoader.getSystemClassLoader(); - - Class loaded = sysloader.loadClass(BouncyCastleProvider.class.getName()); - - Provider provider = (Provider) loaded.newInstance(); - - Security.addProvider(provider); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Loaded Security Providers into system class loader"); - } - } catch (Exception disallowed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, - "Failed loading Security Providers into System Class Loader. Will try local class loader (which may not work)", - disallowed); - } - - // Add the providers we use. - Security.addProvider(new BouncyCastleProvider()); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Loaded Security Providers into local class loader"); - } - } - - // Provider [] providers = Security.getProviders(); - // Iterator eachProvider = Arrays.asList(providers).iterator(); - // - // while (eachProvider.hasNext()) { - // Provider aProvider = (Provider) eachProvider.next(); - // - // System.out.println("\n\n" + aProvider.getName() + " - " + aProvider.getVersion() + " - " + aProvider.getInfo()); - // - // Iterator allMappings = aProvider.entrySet().iterator(); - // - // while (allMappings.hasNext()) { - // Map.Entry aMapping = (Map.Entry) allMappings.next(); - // - // Object key = aMapping.getKey(); - // System.out.println(key + " (" + key.getClass().getName() + ") --> " + aMapping.getValue() + " (" + key.getClass().getName() + ")"); - // } - // } - } - - /** - * Issuer Information - */ - public static class IssuerInfo { - public X509Certificate cert; // subject Cert - public PrivateKey subjectPkey; // subject private key - public X509Certificate issuer; // issuer Cert - public PrivateKey issuerPkey; // issuer private key - } - - /** - * Generate a Cert - * - * @param cn subject cn for the certificate - * @param issuerinfo the cert issuer or null if self-signed root cert. - * @return the details of the generated cert. - * @throws SecurityException if the cert could not be generated. - */ - public static IssuerInfo genCert(String cn, IssuerInfo issuerinfo) throws SecurityException { - try { - String useCN; - - if (null == issuerinfo) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Generating Self Signed Cert ..."); - } - - if (!cn.endsWith("-CA")) { - useCN = cn + "-CA"; - } else { - useCN = cn; - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Generating Client Cert ..."); - } - - useCN = cn; - } - - // set name attribute - Hashtable attrs = new Hashtable(); - - attrs.put(X509Principal.CN, useCN); - attrs.put(X509Principal.O, "www.jxta.org"); - - // XXX bondolo 20040405 wouldn't SN or UID be a better choice? - // set ou to 20 random digits - byte[] ou = new byte[10]; - - UTILS.srng.nextBytes(ou); - String ouStr = toHexDigits(ou); - - attrs.put(X509Principal.OU, ouStr); - - X509Principal subject = new X509Principal(attrs); - X500Principal samesubject = new X500Principal(subject.getEncoded()); - KeyPairGenerator g = KeyPairGenerator.getInstance("RSA"); - - g.initialize(1024, UTILS.srng); - - KeyPair keypair = g.generateKeyPair(); - - return genCert(samesubject, keypair, issuerinfo); - } catch (NoSuchAlgorithmException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not generate certificate", e); - } - SecurityException failure = new SecurityException("Could not generate certificate"); - - failure.initCause(e); - throw failure; - } - } - - /** - * Generate a Cert given a keypair - * - * @param subject subjectDN for the certificate - * @param keypair the keypair to use. - * @param issuerinfo the cert issuer or null if self-signed root cert. - * @return the details of the generated cert. - * @throws SecurityException if the cert could not be generated. - */ - public static IssuerInfo genCert(X500Principal subject, KeyPair keypair, IssuerInfo issuerinfo) throws SecurityException { - try { - // set up issuer - PrivateKey signer; - X509Principal issuer; - - if (null == issuerinfo) { // self-signed root cert - signer = keypair.getPrivate(); - issuer = new X509Principal(subject.getEncoded()); - } else { // issuer signed service sert - signer = issuerinfo.subjectPkey; - X500Principal issuer_subject = issuerinfo.cert.getSubjectX500Principal(); - - issuer = new X509Principal(issuer_subject.getEncoded()); - } - - // set validity 10 years from today - Date today = new Date(); - Calendar cal = Calendar.getInstance(); - - cal.setTime(today); - cal.add(Calendar.YEAR, 10); - Date until = cal.getTime(); - - // generate cert - X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); - - certGen.setIssuerDN(issuer); - certGen.setSubjectDN(new X509Principal(subject.getEncoded())); - certGen.setNotBefore(today); - certGen.setNotAfter(until); - certGen.setPublicKey(keypair.getPublic()); - // certGen.setSignatureAlgorithm("SHA1withDSA"); - certGen.setSignatureAlgorithm("SHA1WITHRSA"); - // FIXME bondolo 20040317 needs fixing. - certGen.setSerialNumber(BigInteger.valueOf(1)); - - // return issuer info for generating service cert - IssuerInfo info = new IssuerInfo(); - - // the cert - info.cert = certGen.generateX509Certificate(signer, UTILS.srng); - - // For saving service cert private key - info.subjectPkey = keypair.getPrivate(); - - // for signing service cert - info.issuer = (null == issuerinfo) ? info.cert : issuerinfo.cert; - - // for signing service cert - info.issuerPkey = signer; - - // dump the certificate? - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - if (null == issuer) { - LOG.fine("Root Cert : \n" + info.cert.toString()); - } else { - LOG.fine("Client Cert : \n" + info.cert.toString()); - } - } - - return info; - } catch (SignatureException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.FINE, "Could not generate certificate", e); - } - - SecurityException failure = new SecurityException("Could not generate certificate"); - - failure.initCause(e); - throw failure; - } catch (InvalidKeyException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.FINE, "Could not generate certificate", e); - } - - SecurityException failure = new SecurityException("Could not generate certificate"); - - failure.initCause(e); - throw failure; - } catch (IOException e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.FINE, "Could not generate certificate", e); - } - - SecurityException failure = new SecurityException("Could not generate certificate"); - - failure.initCause(e); - throw failure; - } - } - - /** - * return the CN token from the provided cert's subjectDN - * - * @param cert the certificate to examine - * @return the CN name or null if none could be found. - */ - public static String getCertSubjectCName(X509Certificate cert) { - - // get the subject dname - X500Principal subject = cert.getSubjectX500Principal(); - - X509NameTokenizer tokens = new X509NameTokenizer(subject.getName()); - - // iterate over the attributes of the dname - while (tokens.hasMoreTokens()) { - String aToken = tokens.nextToken(); - - if (aToken.length() < 3) { - continue; - } - - String attribute = aToken.substring(0, 3); - - if ("CN=".equalsIgnoreCase(attribute)) { - return aToken.substring(3); - } - } - - return null; - } - - /** - * return the CN token from the provided cert's issuerDN - * - * @param cert the certificate to examine - * @return the CN name or null if none could be found. - */ - public static String getCertIssuerCName(X509Certificate cert) { - - // get the subject dname - X500Principal issuer = cert.getIssuerX500Principal(); - - X509NameTokenizer tokens = new X509NameTokenizer(issuer.getName()); - - // iterate over the attributes of the dname - while (tokens.hasMoreTokens()) { - String aToken = tokens.nextToken(); - - if (aToken.length() < 3) { - continue; - } - - String attribute = aToken.substring(0, 3); - - if ("CN=".equalsIgnoreCase(attribute)) { - return aToken.substring(3); - } - } - - return null; - } - - /** - * Compute the signature of a stream. - * - * @param key the private key used to sign the stream - * @param stream the stream to sign. - * @return byte[] the signature - */ - public static byte[] computeSignature(String algorithm, PrivateKey key, InputStream stream) throws InvalidKeyException, SignatureException, IOException { - Signature sign; - - try { - sign = Signature.getInstance(algorithm); - } catch (NoSuchAlgorithmException badsigner) { - throw new IOException("Could not initialize signer with algorithm " + algorithm); - } - sign.initSign(key, UTILS.srng); - - byte[] buffer = new byte[1024]; - - while (true) { - int read = stream.read(buffer); - - if (read < 0) { - break; - } - - sign.update(buffer, 0, read); - } - - return sign.sign(); - } - - /** - * Verify a signature of a stream. - * - * @param cert The certificate containing the public key which will be used - * to verify the signature. - * @param signature The signature to verify. - * @param stream The stream to verify. - * @return boolean true if the signature was valid otherwise false. - */ - public static boolean verifySignature(String algorithm, Certificate cert, byte[] signature, InputStream stream) throws InvalidKeyException, SignatureException, IOException { - Signature sign; - - try { - sign = Signature.getInstance(algorithm); - } catch (NoSuchAlgorithmException badsigner) { - throw new IOException("Could not initialize signer with algorithm " + algorithm); - } - - sign.initVerify(cert); - - byte[] buffer = new byte[1024]; - - while (true) { - int read = stream.read(buffer); - - if (read < 0) { - break; - } - - sign.update(buffer, 0, read); - } - - return sign.verify(signature); - } - - /** - * returns a hash SHA-1 of the given byte array - * - * @param data the data to be hashed - * @return byte[] the hash of the data - */ - public static byte[] hash(String algorithm, byte[] data) { - try { - MessageDigest digest = MessageDigest.getInstance(algorithm); - - return digest.digest(data); - } catch (NoSuchAlgorithmException e) { - return null; - } - } - - /** - * We are trying to use : PBEWITHMD5ANDDES - */ - static final String PKCS5_PBSE1_ALGO = "PBEWITHMD5ANDDES"; - - /** - * Given a private key and a password, encrypt the private key using the - * PBESE1 algorithm. - * - * @param password The password which will be used. - * @param privkey The private key to be encrypted. - * @param iterations Number of iterations. - * @return An encrypted private key info or null if the key could not be - * encrypted. - */ - public static EncryptedPrivateKeyInfo pkcs5_Encrypt_pbePrivateKey(char[] password, PrivateKey privkey, int iterations) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Encrypting " + privkey + " with \'" + new String(password) + "\'"); - } - - PBEKeySpec pbeKeySpec = new PBEKeySpec(password); - byte[] salt = new byte[8]; - - UTILS.srng.nextBytes(salt); - - try { - PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, iterations); - - // convert password into a SecretKey object, using a PBE key factory. - SecretKeyFactory keyFac = SecretKeyFactory.getInstance(PKCS5_PBSE1_ALGO); - SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); - - // Create PBE Cipher - Cipher pbeCipher = Cipher.getInstance(PKCS5_PBSE1_ALGO); - - // Initialize PBE Cipher with key and parameters - pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); - - byte[] encryptedPrivKey = pbeCipher.doFinal(privkey.getEncoded()); - - AlgorithmParameters algo = AlgorithmParameters.getInstance(PKCS5_PBSE1_ALGO); - - algo.init(pbeParamSpec); - - EncryptedPrivateKeyInfo result = new EncryptedPrivateKeyInfo(algo, encryptedPrivKey); - - return result; - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Encrypt failed", failed); - } - return null; - } - } - - /** - * Given an encrypted private key and a password, decrypt the private key - * using the PBESE1 algorithm. - * - * @param password The password which will be used. - * @param encryptedPrivKey The private key to be encrypted. - * @return The decrypted private key or null if the key could not be decrpyted. - */ - public static PrivateKey pkcs5_Decrypt_pbePrivateKey(char[] password, String algorithm, EncryptedPrivateKeyInfo encryptedPrivKey) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Decrypting " + encryptedPrivKey + "/" + algorithm + " with \'" + new String(password) + "\'"); - } - - PBEKeySpec pbeKeySpec = new PBEKeySpec(password); - - try { - AlgorithmParameters algo = encryptedPrivKey.getAlgParameters(); - - if (null == algo) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not get algo parameters from " + encryptedPrivKey); - } - - throw new IllegalStateException("Could not get algo parameters from " + encryptedPrivKey); - } - - PBEParameterSpec pbeParamSpec = algo.getParameterSpec(PBEParameterSpec.class); - - // convert password into a SecretKey object, using a PBE key factory. - try { - SecretKeyFactory keyFac = SecretKeyFactory.getInstance(PKCS5_PBSE1_ALGO); - SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); - - // Create PBE Cipher - Cipher pbeCipher = Cipher.getInstance(PKCS5_PBSE1_ALGO); - - // Initialize PBE Cipher with key and parameters - pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec); - - KeySpec key_spec; - - key_spec = encryptedPrivKey.getKeySpec(pbeCipher); - - KeyFactory kf = KeyFactory.getInstance(algorithm); - - return kf.generatePrivate(key_spec); - } catch (InvalidKeySpecException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Incorrect key for " + encryptedPrivKey + " : " + failed); - } - return null; - } - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Decrypt failed", failed); - } - return null; - } - } - - // Load a wrapped object in base64 format: - // The following three methods were modified - // from similar pureTLS methods. - /** - * WrappedObject.java - *

            - * Copyright (C) 1999, Claymore Systems, Inc. - * All Rights Reserved. - *

            - * ekr@rtfm.com Fri Jun 4 09:11:27 1999 - *

            - * This package is a SSLv3/TLS implementation written by Eric Rescorla - * and licensed by Claymore Systems, Inc. - *

            - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by Claymore Systems, Inc. - * 4. Neither the name of Claymore Systems, Inc. nor the name of Eric - * Rescorla may be used to endorse or promote products derived from this - * software without specific prior written permission. - *

            - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - - public static String loadBase64Object(BufferedReader rdr, String type) throws IOException { - if (null != findObject(rdr, type)) { - return readBase64Object(rdr, type); - } else { - return null; - } - } - - public static byte[] loadObject(BufferedReader rdr, String type) throws IOException { - if (null != findObject(rdr, type)) { - return readObject(rdr, type); - } else { - return null; - } - } - - public static String findObject(BufferedReader br, String type) throws IOException { - String prefix = "-----BEGIN "; - String suffix = (type == null) ? "-----" : type + "-----"; - - while (true) { - br.mark(1024); - - String line = br.readLine(); - - if (null == line) { - return null; - } - - if (!line.startsWith(prefix)) { - continue; - } - - if (!line.endsWith(suffix)) { - continue; - } - - br.reset(); - - return line.substring(prefix.length(), line.length() - 5); - } - } - - /** - * We read a block of n-lines (\n terminated) and return a String of n-lines - * concatenated together. This keeps the format consistent with the pureTLS - * requirements. - */ - public static String readBase64Object(BufferedReader br, String type) throws IOException { - String line = br.readLine(); - - String prefix = "-----BEGIN "; - String suffix = (type == null) ? "-----" : type + "-----"; - - if (!line.startsWith(prefix) || !line.endsWith(suffix)) { - throw new IOException("Not at begining of object"); - } - - StringBuilder block = new StringBuilder(); - - while (true) { - line = br.readLine(); - - if (null == line) { - break; - } - - if (line.startsWith("-----END ")) { - break; - } - - block.append(line); - block.append('\n'); - } - - return block.toString(); - } - - /** - * Read an object - */ - public static byte[] readObject(BufferedReader br, String type) throws IOException { - String base64 = readBase64Object(br, type); - - return base64Decode(new StringReader(base64)); - } - - /** - * - */ - - /** - * Write an object that is already base64 encoded. - */ - public static void writeBase64Object(BufferedWriter bw, String type, String object) throws IOException { - - bw.write("-----BEGIN "); - bw.write(type); - bw.write("-----"); - bw.newLine(); - - bw.write(object); - - char lastChar = object.charAt(object.length() - 1); - - if (('\n' != lastChar) && ('\r' != lastChar)) { - bw.newLine(); - } - - bw.write("-----END "); - bw.write(type); - bw.write("-----"); - bw.newLine(); - - bw.flush(); - } - - public static void writeObject(BufferedWriter out, String type, byte[] object) throws IOException { - String base64 = base64Encode(object); - - writeBase64Object(out, type, base64); - } - - /** - * Convert a byte array into a BASE64 encoded String. - * - * @param in The bytes to be converted - * @return the BASE64 encoded String. - */ - public static String base64Encode(byte[] in) throws IOException { - return base64Encode(in, true); - } - - /** - * Convert a byte array into a BASE64 encoded String. - * - * @param in the bytes to be converted - * @return the BASE64 encoded String. - */ - public static String base64Encode(byte[] in, boolean wrap) throws IOException { - StringWriter base64 = new StringWriter(); - - BASE64OutputStream b64os; - - if (wrap) { - b64os = new BASE64OutputStream(base64, 72); - } else { - b64os = new BASE64OutputStream(base64); - } - b64os.write(in); - b64os.close(); - - String encoded = base64.toString(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Encoded " + in.length + " bytes -> " + encoded.length() + " characters."); - } - - return encoded; - } - - /** - * Convert a BASE64 Encoded String into byte array. - * - * @param in BASE64 encoded String - * @return the decoded bytes. - */ - public static byte[] base64Decode(Reader in) throws IOException { - BASE64InputStream b64is = new BASE64InputStream(in); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - do { - int c = b64is.read(); - - if (c < 0) { - break; - } - - bos.write(c); - } while (true); - - byte[] result = bos.toByteArray(); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Decoded " + result.length + " bytes."); - } - - return result; - } - - /** - * Private replacement for toHexString since we need the leading 0 digits. - * Returns a String containing byte value encoded as 2 hex characters. - * - * @param theByte a byte containing the value to be encoded. - * @return String containing byte value encoded as 2 hex characters. - */ - private static String toHexDigits(byte theByte) { - final char[] HEXDIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - StringBuilder result = new StringBuilder(2); - - result.append(HEXDIGITS[(theByte >>> 4) & 15]); - result.append(HEXDIGITS[theByte & 15]); - - return result.toString(); - } - - private static String toHexDigits(byte[] bytes) { - StringBuilder encoded = new StringBuilder(bytes.length * 2); - - // build the string. - for (byte aByte : bytes) { - encoded.append(toHexDigits(aByte).toUpperCase()); - } - return encoded.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/StringAuthenticator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/StringAuthenticator.java deleted file mode 100644 index 9b6180ff..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/StringAuthenticator.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import java.net.URI; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.security.cert.X509Certificate; -import javax.crypto.EncryptedPrivateKeyInfo; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.security.KeyStoreException; - -import net.jxta.credential.AuthenticationCredential; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.membership.Authenticator; -import net.jxta.membership.MembershipService; - - -/** - * An authenticator associated with the PSE membership service. - * - *@see net.jxta.membership.Authenticator - *@see net.jxta.membership.MembershipService - **/ -public class StringAuthenticator implements Authenticator { - - /** - * The Membership Service which generated this authenticator. - **/ - transient PSEMembershipService source; - - /** - * The Authentication which was provided to the Apply operation of the - * membership service. - **/ - transient AuthenticationCredential application; - - /** - * The certficate which we are authenticating against - **/ - transient X509Certificate seedCert; - - /** - * The encrypted private key which we must unlock. - **/ - transient EncryptedPrivateKeyInfo seedKey; - - /** - * the password for that identity. - **/ - transient char[] store_password = null; - - /** - * the identity which is being claimed - **/ - transient ID identity = null; - - /** - * the password for that identity. - **/ - transient char[] key_password = null; - - /** - * Creates an authenticator for the PSE membership service. Anything entered - * into the identity info section of the Authentication credential is - * ignored. - * - * @param source The instance of the PSE membership service which - * created this authenticator. - * @param application Anything entered into the identity info section of - * the Authentication credential is ignored. - **/ - StringAuthenticator(PSEMembershipService source, AuthenticationCredential application, X509Certificate seedCert, EncryptedPrivateKeyInfo seedKey) { - this(source, application); - - this.seedCert = seedCert; - this.seedKey = seedKey; - } - - /** - * Creates an authenticator for the PSE membership service. Anything entered - * into the identity info section of the Authentication credential is - * ignored. - * - * @param source The instance of the PSE membership service which created - * this authenticator. - * @param application Anything entered into the identity info section of - * the Authentication credential is ignored. - **/ - StringAuthenticator(PSEMembershipService source, AuthenticationCredential application) { - this.source = source; - this.application = application; - - // XXX 20010328 bondolo@jxta.org Could do something with the authentication credential here. - } - - /** - * {@inheritDoc} - **/ - @Override - protected void finalize() throws Throwable { - if (null != store_password) { - Arrays.fill(store_password, '\0'); - } - - if (null != key_password) { - Arrays.fill(key_password, '\0'); - } - - super.finalize(); - } - - /** - * {@inheritDoc} - **/ - public MembershipService getSourceService() { - return (MembershipService) source.getInterface(); - } - - /** - * {@inheritDoc} - **/ - public AuthenticationCredential getAuthenticationCredential() { - return application; - } - - /** - * {@inheritDoc} - **/ - public String getMethodName() { - return "StringAuthentication"; - } - - /** - * {@inheritDoc} - **/ - synchronized public boolean isReadyForJoin() { - if (null != seedCert) { - return null != PSEUtils.pkcs5_Decrypt_pbePrivateKey(key_password, seedCert.getPublicKey().getAlgorithm(), seedKey); - } else { - return source.pseStore.validPasswd(identity, store_password, key_password); - } - } - - /** - * Get KeyStore password - **/ - public char[] getAuth1_KeyStorePassword() { - return store_password; - } - - /** - * Set KeyStore password - **/ - public void setAuth1_KeyStorePassword(String store_password) { - if (null == store_password) { - setAuth1_KeyStorePassword((char[]) null); - } else { - setAuth1_KeyStorePassword(store_password.toCharArray()); - } - } - - /** - * Set KeyStore password - **/ - public void setAuth1_KeyStorePassword(char[] store_password) { - if (null != this.store_password) { - Arrays.fill(this.store_password, '\0'); - } - - if (null == store_password) { - this.store_password = null; - } else { - this.store_password = store_password.clone(); - } - } - - /** - * Return the available identities. - **/ - public PeerID[] getIdentities(char[] store_password) { - - if (seedCert != null) { - PeerID[] seed = { source.group.getPeerID() }; - - return seed; - } else { - try { - ID[] allkeys = source.pseStore.getKeysList(store_password); - - // XXX bondolo 20040329 it may be appropriate to login - // something other than a peer id. - List peersOnly = new ArrayList(); - - Iterator eachKey = Arrays.asList(allkeys).iterator(); - - while (eachKey.hasNext()) { - ID aKey = (ID) eachKey.next(); - - if (aKey instanceof PeerID) { - peersOnly.add(aKey); - } - } - - return (PeerID[]) peersOnly.toArray(new PeerID[peersOnly.size()]); - } catch (IOException failed) { - return null; - } catch (KeyStoreException failed) { - return null; - } - } - } - - /** - * Returns the X509 Certificate associated with the specified ID. - * - * @param store_password The password for the keystore. - * @param aPeer The peer who's certificate is desired. For uninitialized - * keystores this must be the peerid of the registering peer. - **/ - public X509Certificate getCertificate(char[] store_password, ID aPeer) { - if (seedCert != null) { - if (aPeer.equals(source.group.getPeerID())) { - return seedCert; - } else { - return null; - } - } else { - try { - return source.pseStore.getTrustedCertificate(aPeer, store_password); - } catch (IOException failed) { - return null; - } catch (KeyStoreException failed) { - return null; - } - } - } - - /** - * Get Identity - **/ - public ID getAuth2Identity() { - return identity; - } - - /** - * Set Identity - **/ - public void setAuth2Identity(String id) { - try { - URI idURI = new URI(id); - ID identity = IDFactory.fromURI(idURI); - - setAuth2Identity(identity); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad ID"); - } - } - - /** - * Set Identity - **/ - public void setAuth2Identity(ID identity) { - this.identity = identity; - } - - /** - * Get identity password - **/ - public char[] getAuth3_IdentityPassword() { - return key_password; - } - - /** - * Set identity password - **/ - public void setAuth3_IdentityPassword(String key_password) { - setAuth3_IdentityPassword(key_password.toCharArray()); - } - - /** - * Set identity password - **/ - public void setAuth3_IdentityPassword(char[] key_password) { - if (null != this.key_password) { - Arrays.fill(this.key_password, '\0'); - } - - if (null == key_password) { - this.key_password = null; - } else { - this.key_password = key_password.clone(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/URIKeyStoreManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/URIKeyStoreManager.java deleted file mode 100644 index 485de10a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/URIKeyStoreManager.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.membership.pse; - - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.net.URI; -import java.security.KeyStore; - -import java.io.IOException; -import java.security.KeyStoreException; -import java.security.NoSuchProviderException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * Manages a Keystore located at URI. This version precludes KeyStores which - * are built from multiple URIs. - **/ -public class URIKeyStoreManager implements KeyStoreManager { - - /** - * Log4J Logger - **/ - private final static transient Logger LOG = Logger.getLogger(URIKeyStoreManager.class.getName()); - - /** - * The default keystore type we will use. - **/ - private final static String DEFAULT_KEYSTORE_TYPE = "jks"; - - /** - * The keystore type - **/ - private final String keystore_type; - - /** - * The keystore type - **/ - private final String keystore_provider; - - /** - * The location where the keystore lives. - **/ - private final URI keystore_location; - - /** - * Default constructor. - **/ - public URIKeyStoreManager(String type, String provider, URI location) throws NoSuchProviderException, KeyStoreException { - if (null == type) { - type = DEFAULT_KEYSTORE_TYPE; - provider = null; - } - - if (!location.isAbsolute()) { - throw new IllegalArgumentException("location must be an absolute URI"); - } - - if ("file".equalsIgnoreCase(location.getScheme())) { - File asFile = new File(location); - - if (asFile.exists() && !asFile.isFile()) { - throw new IllegalArgumentException("location must refer to a file"); - } - } - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("pse location = " + location); - } - - keystore_type = type; - - keystore_provider = provider; - - keystore_location = location; - - // check if we can get an instance. - if (null == keystore_provider) { - KeyStore.getInstance(keystore_type); - } else { - KeyStore.getInstance(keystore_type, keystore_provider); - } - } - - /** - * {@inheritDoc} - **/ - public boolean isInitialized() { - return isInitialized(null); - } - - /** - * {@inheritDoc} - **/ - public boolean isInitialized(char[] store_password) { - try { - KeyStore store; - - if (null == keystore_provider) { - store = KeyStore.getInstance(keystore_type); - } else { - store = KeyStore.getInstance(keystore_type, keystore_provider); - } - - store.load(keystore_location.toURL().openStream(), store_password); - - return true; - } catch (Exception failed) { - return false; - } - } - - /** - * {@inheritDoc} - **/ - public void createKeyStore(char[] store_password) throws KeyStoreException, IOException { - try { - KeyStore store; - - if (null == keystore_provider) { - store = KeyStore.getInstance(keystore_type); - } else { - store = KeyStore.getInstance(keystore_type, keystore_provider); - } - - store.load(null, store_password); - - saveKeyStore(store, store_password); - } catch (NoSuchProviderException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchProviderException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (NoSuchAlgorithmException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (CertificateException failed) { - KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * {@inheritDoc} - **/ - public KeyStore loadKeyStore(char[] password) throws KeyStoreException, IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Loading (" + keystore_type + "," + keystore_provider + ") store from " + keystore_location); - } - - try { - KeyStore store; - - if (null == keystore_provider) { - store = KeyStore.getInstance(keystore_type); - } else { - store = KeyStore.getInstance(keystore_type, keystore_provider); - } - - store.load(keystore_location.toURL().openStream(), password); - - return store; - } catch (NoSuchAlgorithmException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (CertificateException failed) { - KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (NoSuchProviderException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchProviderException during keystore processing"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * {@inheritDoc} - **/ - public void saveKeyStore(KeyStore store, char[] password) throws KeyStoreException, IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Writing " + store + " to " + keystore_location); - } - - try { - OutputStream os = null; - - if ("file".equalsIgnoreCase(keystore_location.getScheme())) { - // Sadly we can't use URL.openConnection() to create the - // OutputStream for file:// URLs. bogus. - os = new FileOutputStream(new File(keystore_location)); - } else { - os = keystore_location.toURL().openConnection().getOutputStream(); - } - store.store(os, password); - } catch (NoSuchAlgorithmException failed) { - KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); - - failure.initCause(failed); - throw failure; - } catch (CertificateException failed) { - KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * {@inheritDoc} - **/ - public void eraseKeyStore() { - - if ("file".equalsIgnoreCase(keystore_location.getScheme())) { - File asFile = new File(keystore_location); - - if (asFile.exists() && asFile.isFile() && asFile.canWrite()) { - asFile.delete(); - } - } else { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Unable to delete non-file URI :" + keystore_location); - } - - throw new UnsupportedOperationException("Unable to delete non-file URI"); - } - } - - /** - * {@inheritDoc} - **/ - public String toString() { - StringBuilder sb = new StringBuilder("PSE keystore details: \n"); - sb.append(" Class: ").append(this.getClass().getName()).append("\n"); - sb.append(" Type: ").append(keystore_type==null ? "" : keystore_type).append("\n"); - sb.append(" Provider: ").append(keystore_provider==null ? "" : keystore_provider).append("\n"); - sb.append(" Location: ").append(keystore_location==null ? "" : keystore_location.toString()).append("\n"); - return sb.toString(); - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/package.html deleted file mode 100644 index 1bf6794f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/membership/pse/package.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - A JXTA Membership Service utilizing PKI to provide secure identities. - - @see net.jxta.membership - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ConditionalMeterBuildSettings.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ConditionalMeterBuildSettings.java deleted file mode 100644 index cbf2f50a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ConditionalMeterBuildSettings.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * The Sun Project JXTA(TM) Software License - * - * Copyright (c) 2001-2006 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: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at https://jxta.dev.java.net. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * https://jxta.dev.java.net/ - * - * This license is based on the BSD license adopted by the Apache Foundation. - * - */ - - -/* **** THIS IS A GENERATED FILE. DO NOT EDIT. **** */ - -package net.jxta.impl.meter; - -import java.util.ResourceBundle; -import net.jxta.impl.meter.*; - -public class ConditionalMeterBuildSettings { - public static boolean isRuntimeMetering() { - boolean runtimeMetering = false; - - try { - ResourceBundle userResourceBundle = ResourceBundle.getBundle( "net.jxta.user" ); - String meteringProperty = "net.jxta.meter.conditionalMetering"; - String meteringValue = userResourceBundle.getString( meteringProperty ); - runtimeMetering = "on".equalsIgnoreCase( meteringValue ); - } catch (Exception ignored) { - } - - return runtimeMetering; - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/GenericServiceMonitor.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/GenericServiceMonitor.java deleted file mode 100644 index b4a99603..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/GenericServiceMonitor.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.meter; - - -import net.jxta.document.Advertisement; -import net.jxta.exception.JxtaException; -import net.jxta.id.ID; -import net.jxta.meter.MonitorResources; -import net.jxta.meter.ServiceMetric; -import net.jxta.meter.ServiceMonitorFilter; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.platform.ModuleClassID; -import net.jxta.protocol.ModuleImplAdvertisement; - - -public abstract class GenericServiceMonitor implements ServiceMonitorImpl, Module { - private ModuleClassID moduleClassID; - protected MonitorManager monitorManager; - - protected long reportRate; - protected int reportRateIndex; - protected ServiceMetric cumulativeServiceMetric; - protected ServiceMetric deltaServiceMetrics[]; - protected ModuleImplAdvertisement implAdvertisement; - - public GenericServiceMonitor() {} - - // public void init(MonitorManager monitorManager, ModuleClassID moduleClassID) { - - public void init(PeerGroup group, ID assignedID, Advertisement advertisement) { - group.unref(); // We do not use the group. These are not quite real modules. - this.implAdvertisement = (ModuleImplAdvertisement) advertisement; - this.moduleClassID = (ModuleClassID) assignedID; - } - - public void init(MonitorManager monitorManager) { - this.monitorManager = monitorManager; - - if (MeterBuildSettings.METERING) { - cumulativeServiceMetric = createServiceMetric(); - deltaServiceMetrics = new ServiceMetric[monitorManager.getReportRatesCount()]; - init(); - } - } - - /* - public void init(MonitorManager monitorManager) { - this.monitorManager = monitorManager; - } - */ - - public int startApp(java.lang.String[] args) { - return 0; - } // fix-me: what's the right return? - - public void stopApp() {} - - protected void init() {} - - public ModuleClassID getModuleClassID() { - return moduleClassID; - } - - public PeerGroup getPeerGroup() { - return monitorManager.getPeerGroup(); - } - - protected ServiceMetric getCumulativeServiceMetric() { - return cumulativeServiceMetric; - } - - public void resetPulseRate(ServiceMonitorPulseInfo pulseInfo, int oldPulseRateIndex) { - this.reportRate = pulseInfo.getPulseRate(); - this.reportRateIndex = pulseInfo.getPulseRateIndex(); - } - - public void validateCumulativeServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter) {// base implementation is to accept - } - - public ServiceMonitorFilter createSupportedCumulativeServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter) { - // base implementation is to accept - return serviceMonitorFilter; - } - - public void validateServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter, long reportRate) {// base implementation is to accept - } - - public ServiceMonitorFilter createSupportedServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter, long reportRate) { - // base implementation is to accept - return serviceMonitorFilter; - } - - protected ServiceMetric createServiceMetric() { - try { - return MonitorResources.createServiceMetric(moduleClassID); - } catch (JxtaException e) { // this will always succeed since we were able to lad the monitor - return null; - } - } - - /** - * Get the service metrics accrued since the last pulse - * - * @return null if there were no metrices since the last call - */ - protected abstract ServiceMetric collectServiceMetrics(); - - public synchronized void beginPulse(ServiceMonitorPulseInfo pulseInfo) { - ServiceMetric baseDeltaServiceMetric = collectServiceMetrics(); - - deltaServiceMetrics[reportRateIndex] = baseDeltaServiceMetric; - - if (baseDeltaServiceMetric != null) { - for (int reportRate = reportRateIndex + 1; reportRate < deltaServiceMetrics.length; reportRate++) { - - if (pulseInfo.isRegisteredFilterForRate(reportRate)) { - - if (deltaServiceMetrics[reportRate] == null) { - deltaServiceMetrics[reportRate] = createServiceMetric(); - } - - deltaServiceMetrics[reportRate].mergeMetrics(baseDeltaServiceMetric); - } - } - } - } - - public void endPulse(ServiceMonitorPulseInfo pulseInfo) { - for (int reportRateIndex = 0; reportRateIndex < monitorManager.getReportRatesCount(); reportRateIndex++) { - if (pulseInfo.isEvenPulseForRateIndex(reportRateIndex)) { - deltaServiceMetrics[reportRateIndex] = null; - } - } - } - - public void beginCumulativeReport() {} - - public void endCumulativeReport() {} - - public ServiceMetric getServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime, int reportIndex, long reportRate) { - int deltaReportRateIndex = monitorManager.getReportRateIndex(reportRate); - - // Fix-Me: For now we are not yet supporting filters - - return deltaServiceMetrics[deltaReportRateIndex]; - } - - public ServiceMetric getCumulativeServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime) { - // Fix-Me: For now we are not yet supporting filters - - return cumulativeServiceMetric; - } - - public void serviceMonitorFilterRegistered(ServiceMonitorFilter serviceMonitorFilter, int reportRateIndex, long reportRate, boolean newRate) { - if (newRate) { - deltaServiceMetrics[reportRateIndex] = createServiceMetric(); - } - } - - public void serviceMonitorFilterDeregistered(ServiceMonitorFilter serviceMonitorFilter, int reportRateIndex, long reportRate, boolean retiredRate) { - if (retiredRate) { - deltaServiceMetrics[reportRateIndex] = null; - } - } - - public void destroy() {} -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/MeterBuildSettings.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/MeterBuildSettings.java deleted file mode 100644 index 4f43a113..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/MeterBuildSettings.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * The Sun Project JXTA(TM) Software License - * - * Copyright (c) 2001-2006 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: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at https://jxta.dev.java.net. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * https://jxta.dev.java.net/ - * - * This license is based on the BSD license adopted by the Apache Foundation. - * - */ - - -/* **** THIS IS A GENERATED FILE. DO NOT EDIT. **** */ - -package net.jxta.impl.meter; - -import net.jxta.impl.meter.*; - -public interface MeterBuildSettings { - public static final boolean METERING = ConditionalMeterBuildSettings.isRuntimeMetering(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/MetricUtilities.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/MetricUtilities.java deleted file mode 100644 index b0e98e52..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/MetricUtilities.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.meter; - - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; - -import java.net.URI; -import java.net.URISyntaxException; - - -public class MetricUtilities { - private static PeerID unknownPeer = (PeerID) ID.create(URI.create("urn:jxta:uuid-DEAF03")); - private static PeerID badPeer = (PeerID) ID.create(URI.create("urn:jxta:uuid-BADBAD03")); - - public static final PeerID UNKNOWN_PEERID = unknownPeer; - public static final PeerID BAD_PEERID = badPeer; - - public static PeerID getPeerIdFromString(String peerIdString) { - PeerID peerId; - - try { - peerId = (PeerID) IDFactory.fromURI(new URI(peerIdString)); - } catch (URISyntaxException e) { - peerId = BAD_PEERID; - } - return peerId; - } - - public static PeerID getPeerIdFromEndpointAddress(EndpointAddress endpointAddress) { - PeerID peerId; - - try { - peerId = (PeerID) IDFactory.fromURI( - new URI( - ID.URIEncodingName + ":" + endpointAddress.getProtocolName() + ":" - + endpointAddress.getProtocolAddress())); - } catch (URISyntaxException e) { - peerId = BAD_PEERID; - } - return peerId; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/MonitorManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/MonitorManager.java deleted file mode 100644 index 4d25c7ba..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/MonitorManager.java +++ /dev/null @@ -1,834 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.meter; - - -import net.jxta.document.Advertisement; -import net.jxta.exception.JxtaException; -import net.jxta.id.ID; -import net.jxta.impl.util.TimeUtils; -import net.jxta.meter.MonitorEvent; -import net.jxta.meter.MonitorException; -import net.jxta.meter.MonitorFilter; -import net.jxta.meter.MonitorFilterException; -import net.jxta.meter.MonitorListener; -import net.jxta.meter.MonitorReport; -import net.jxta.meter.MonitorResources; -import net.jxta.meter.PeerMonitorInfo; -import net.jxta.meter.ServiceMetric; -import net.jxta.meter.ServiceMonitor; -import net.jxta.meter.ServiceMonitorFilter; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.platform.ModuleClassID; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.service.Service; -import net.jxta.util.documentSerializable.DocumentSerializableUtilities; -import net.jxta.util.documentSerializable.DocumentSerializationException; - -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.LinkedList; - - -public class MonitorManager implements Service { - private final static long timeZero = System.currentTimeMillis(); - public static final int NOT_PULSING = -1; - - private static final int NO_PRIOR_REPORT = 0; - - private static long supportedReportRates[] = new long[] { - 500, TimeUtils.ASECOND, 5 * TimeUtils.ASECOND, 10 * TimeUtils.ASECOND, 15 * TimeUtils.ASECOND, 30 * TimeUtils.ASECOND - , - TimeUtils.AMINUTE, 5 * TimeUtils.AMINUTE, 10 * TimeUtils.AMINUTE, 15 * TimeUtils.AMINUTE, 30 * TimeUtils.AMINUTE - , - TimeUtils.ANHOUR, 3 * TimeUtils.ANHOUR, 6 * TimeUtils.ANHOUR, 12 * TimeUtils.ANHOUR, TimeUtils.ADAY, TimeUtils.AWEEK}; - - private int pulsesPerRate[] = new int[supportedReportRates.length]; - private long startTime = System.currentTimeMillis(); - - private LinkedList monitorListenerInfos = new LinkedList(); - private Hashtable serviceMonitorPulseInfos = new Hashtable(); - private int filtersPerRate[] = new int[supportedReportRates.length]; - private long previousReportTimes[] = new long[supportedReportRates.length]; - - private PeerGroup peerGroup; - private Thread reportThread; - - private long pulseRate = NOT_PULSING; - private int pulseRateIndex = NOT_PULSING; - private int pulseNumber = 0; - private long nextPulseTime = NO_PRIOR_REPORT; - private boolean isRunning = true; // true until monitor is destroyed, triggers termination of report thread - - private ModuleClassID[] supportedModuleClassIDs; - private ModuleImplAdvertisement implAdvertisement; - private long lastResetTime = System.currentTimeMillis(); - - public Advertisement getImplAdvertisement() { - return implAdvertisement; - } - - public Service getInterface() { - // This is good enough. No need to get fancy. - return this; - } - - // public MonitorManager(PeerGroup peerGroup) { - - public void init(PeerGroup peerGroup, ID assignedID, Advertisement implAdvertisement) { - this.implAdvertisement = (ModuleImplAdvertisement) implAdvertisement; - this.peerGroup = peerGroup; - createReportThread(); - - for (int i = 0; i < previousReportTimes.length; i++) { - pulsesPerRate[i] = (int) (supportedReportRates[i] / supportedReportRates[0]); - } - } - - public int startApp(java.lang.String[] args) { - return 0; // fix-me - } - - public void stopApp() { - destroy(); - } - - private class MonitorListenerInfo { - MonitorListener monitorListener; - MonitorFilter monitorFilter; - long reportRate; - int reportRateIndex; - boolean sendCumulativeFirst = false; - boolean wasCumulativeSent = false; - - MonitorListenerInfo(MonitorListener monitorListener, long reportRate, MonitorFilter monitorFilter, boolean cumulativeFirst) { - this.monitorListener = monitorListener; - this.monitorFilter = monitorFilter; - this.reportRate = reportRate; - this.sendCumulativeFirst = cumulativeFirst; - this.reportRateIndex = getReportRateIndex(reportRate); - } - } - - public static long[] getReportRates() { // return copy so that users can't modify. - long copy[] = new long[supportedReportRates.length]; - - System.arraycopy(supportedReportRates, 0, copy, 0, supportedReportRates.length); - return copy; - } - - public boolean isLocalMonitoringAvailable(ModuleClassID moduleClassID) { - ServiceMonitor serviceMonitor = getServiceMonitor(moduleClassID); - - return (serviceMonitor != null); - } - - public PeerGroup getPeerGroup() { - return peerGroup; - } - - // Cooperate with the code that loaded this module to replace the strong - // group interface given by init() with a non-counted one. - private void setPeerGroup(PeerGroup pg) { - PeerGroup tmp = peerGroup; - - peerGroup = pg; - tmp.unref(); - tmp = null; - } - - public PeerMonitorInfo getPeerMonitorInfo() { - long[] reportRates = getReportRates(); // makes a copy - ModuleClassID[] moduleClassIDs = getMonitorableServiceTypes(); // ensures that array is initialized. - long runningTime = System.currentTimeMillis() - lastResetTime; - - return new PeerMonitorInfo(MeterBuildSettings.METERING, moduleClassIDs, reportRates, lastResetTime, runningTime); - } - - public int getReportRatesCount() { - return supportedReportRates.length; - } - - public int getReportRateIndex(long reportRate) { - for (int i = 0; i < supportedReportRates.length; i++) { - if (supportedReportRates[i] == reportRate) { - return i; - } - } - - return -1; - } - - public boolean isSupportedReportRate(long reportRate) { - return getReportRateIndex(reportRate) >= 0; - } - - public long getReportRate(int index) { - return supportedReportRates[index]; - } - - public long getBestReportRate(long desiredReportRate) { - for (long supportedReportRate : supportedReportRates) { - if (desiredReportRate <= supportedReportRate) { - return supportedReportRate; - } - } - - return supportedReportRates[supportedReportRates.length - 1]; - } - - public ServiceMonitor getServiceMonitor(ModuleClassID moduleClassID) { - ServiceMonitorPulseInfo serviceMonitorPulseInfo = serviceMonitorPulseInfos.get(moduleClassID); - - if (serviceMonitorPulseInfo != null) { - return serviceMonitorPulseInfo.serviceMonitor; - } else { - - try { - ModuleImplAdvertisement moduleImplAdvertisement = MonitorResources.getServiceMonitorImplAdvertisement( - moduleClassID, implAdvertisement); - ServiceMonitor serviceMonitor = (ServiceMonitor) peerGroup.loadModule(moduleClassID, moduleImplAdvertisement); - - MonitorResources.registerServiceMonitorModuleImplAdvertisement(moduleImplAdvertisement); - - if (serviceMonitor instanceof ServiceMonitorImpl) { - ((ServiceMonitorImpl) serviceMonitor).init(this); - - } - - serviceMonitorPulseInfo = new ServiceMonitorPulseInfo(this, serviceMonitor); - serviceMonitorPulseInfos.put(moduleClassID, serviceMonitorPulseInfo); - return serviceMonitor; - } catch (JxtaException e) { - throw new RuntimeException("Unable to load Service Monitor: " + moduleClassID + "\n\tException: " + e); - } - } - } - - private void resetPulseRate() { - int oldPulseRateIndex = pulseRateIndex; - - pulseRateIndex = NOT_PULSING; - pulseRate = NOT_PULSING; - - for (int i = 0; i < filtersPerRate.length; i++) { - if (filtersPerRate[i] != 0) { - pulseRateIndex = i; - pulseRate = getReportRate(pulseRateIndex); - break; - } - } - - if (oldPulseRateIndex == pulseRateIndex) { - return; - } // nothing changed - - long now = System.currentTimeMillis(); - - if (oldPulseRateIndex == NOT_PULSING) { // case 1: No pulse to pulse - for (int i = 0; i < filtersPerRate.length; i++) { - if (filtersPerRate[i] != 0) { - previousReportTimes[i] = now; - } else { - previousReportTimes[i] = NO_PRIOR_REPORT; - } - } - - pulseNumber = 0; - nextPulseTime = now + pulseRate; - } else if (pulseRateIndex == NOT_PULSING) {// case 2: pulse to No pulse - // Do nothing - } else if (pulseRateIndex < oldPulseRateIndex) { // case 3: pulse going to a faster pulse - for (int i = pulseRateIndex; i < (oldPulseRateIndex - 1); i++) { - if (filtersPerRate[i] != 0) { - previousReportTimes[i] = now; - } else { - previousReportTimes[i] = NO_PRIOR_REPORT; - } - } - - long timeToNextPulse = nextPulseTime - now; - - if (pulseRate < timeToNextPulse) { - int numPulsesToNow = (int) (timeToNextPulse / pulseRate); - int numNewToOldPulses = (int) (supportedReportRates[oldPulseRateIndex] / supportedReportRates[pulseRateIndex]); - - pulseNumber += (numNewToOldPulses - numPulsesToNow) * pulsesPerRate[pulseRateIndex]; - timeToNextPulse = now - (numPulsesToNow * pulseRate); - } else { - pulseNumber += (pulsesPerRate[oldPulseRateIndex] - pulsesPerRate[pulseRateIndex]); - } - - } else if (pulseRateIndex > oldPulseRateIndex) { // case 3: pulse going to a slower pulse - int nextPulseNumber = pulseNumber + pulsesPerRate[oldPulseRateIndex]; - - pulseNumber = ((nextPulseNumber - 1) / pulsesPerRate[pulseRateIndex]) * pulsesPerRate[pulseRateIndex]; - nextPulseTime += (nextPulseNumber - pulseNumber) * supportedReportRates[0]; - - for (int i = 0; i < pulseRateIndex; i++) { - previousReportTimes[i] = NO_PRIOR_REPORT; - } - } - - reportThread.interrupt(); - } - - private MonitorReport getMonitorReport(MonitorFilter monitorFilter, long reportRate, long previousDeltaTime, long beginReportTime) { - MonitorReport monitorReport = new MonitorReport(previousDeltaTime, beginReportTime, false); - - for (Iterator i = monitorFilter.getModuleClassIDs(); i.hasNext();) { - ModuleClassID moduleClassID = (ModuleClassID) i.next(); - - ServiceMonitorFilter serviceMonitorFilter = monitorFilter.getServiceMonitorFilter(moduleClassID); - - ServiceMonitor serviceMonitor = getServiceMonitor(moduleClassID); - - if (serviceMonitorFilter != null) { - ServiceMetric serviceMetric = serviceMonitor.getServiceMetric(serviceMonitorFilter, previousDeltaTime - , - beginReportTime, getReportRateIndex(reportRate), reportRate); - - if (serviceMetric != null) { - monitorReport.addServiceMetric(serviceMetric); - } - } - } - return monitorReport; - } - - public void validateCumulativeMonitorFilter(MonitorFilter monitorFilter) throws MonitorFilterException { - boolean isAnyServiceFilters = false; - - for (Iterator i = monitorFilter.getServiceMonitorFilters(); i.hasNext();) { - ServiceMonitorFilter serviceMonitorFilter = (ServiceMonitorFilter) i.next(); - - ModuleClassID moduleClassID = serviceMonitorFilter.getModuleClassID(); - ServiceMonitor serviceMonitor = getServiceMonitor(moduleClassID); - - if (serviceMonitor == null) { - throw new MonitorFilterException(MonitorFilterException.SERVICE_NOT_SUPPORTED, moduleClassID); - } - - serviceMonitor.validateCumulativeServiceMonitorFilter(serviceMonitorFilter); - isAnyServiceFilters = true; - } - - if (!isAnyServiceFilters) { - throw new MonitorFilterException("Empty Monitor Filter"); - } - - } - - public void validateMonitorFilter(MonitorFilter monitorFilter, long reportRate) throws MonitorFilterException { - - if (!isSupportedReportRate(reportRate)) { - throw new MonitorFilterException(MonitorFilterException.REPORT_RATE_NOT_SUPPORTED, reportRate); - } - - boolean isAnyServiceFilters = false; - - for (Iterator i = monitorFilter.getServiceMonitorFilters(); i.hasNext();) { - ServiceMonitorFilter serviceMonitorFilter = (ServiceMonitorFilter) i.next(); - - ModuleClassID moduleClassID = serviceMonitorFilter.getModuleClassID(); - ServiceMonitor serviceMonitor = getServiceMonitor(moduleClassID); - - if (serviceMonitor == null) { - throw new MonitorFilterException(MonitorFilterException.SERVICE_NOT_SUPPORTED, moduleClassID); - } - - serviceMonitor.validateServiceMonitorFilter(serviceMonitorFilter, reportRate); - isAnyServiceFilters = true; - } - - if (!isAnyServiceFilters) { - throw new MonitorFilterException("Empty Monitor Filter"); - } - } - - public MonitorFilter createSupportedCumulativeMonitorFilter(MonitorFilter monitorFilter) throws MonitorFilterException { - MonitorFilter newMonitorFilter = new MonitorFilter(monitorFilter.getDescription()); - boolean anythingAdded = false; - - for (Iterator i = monitorFilter.getServiceMonitorFilters(); i.hasNext();) { - ServiceMonitorFilter serviceMonitorFilter = (ServiceMonitorFilter) i.next(); - - ModuleClassID moduleClassID = serviceMonitorFilter.getModuleClassID(); - ServiceMonitor serviceMonitor = getServiceMonitor(moduleClassID); - - if (serviceMonitor == null) { - continue; - } - - ServiceMonitorFilter newServiceMonitorFilter = serviceMonitor.createSupportedCumulativeServiceMonitorFilter( - serviceMonitorFilter); - - if (newServiceMonitorFilter != null) { - newMonitorFilter.addServiceMonitorFilter(newServiceMonitorFilter); - anythingAdded = true; - } - } - - if (anythingAdded) { - return newMonitorFilter; - } else { - return null; - } - } - - public MonitorFilter createSupportedMonitorFilter(MonitorFilter monitorFilter, long reportRate) throws MonitorFilterException { - MonitorFilter newMonitorFilter = new MonitorFilter(monitorFilter.getDescription()); - boolean anythingAdded = false; - - for (Iterator i = monitorFilter.getServiceMonitorFilters(); i.hasNext();) { - ServiceMonitorFilter serviceMonitorFilter = (ServiceMonitorFilter) i.next(); - - ModuleClassID moduleClassID = serviceMonitorFilter.getModuleClassID(); - ServiceMonitor serviceMonitor = getServiceMonitor(moduleClassID); - - if (serviceMonitor == null) { - continue; - } - - ServiceMonitorFilter newServiceMonitorFilter = serviceMonitor.createSupportedServiceMonitorFilter(serviceMonitorFilter - , - reportRate); - - if (newServiceMonitorFilter != null) { - newMonitorFilter.addServiceMonitorFilter(newServiceMonitorFilter); - anythingAdded = true; - } - } - - if (anythingAdded) { - return newMonitorFilter; - } else { - return null; - } - } - - public synchronized long addMonitorListener(MonitorFilter monitorFilter, long reportRate, boolean includeCumulative, MonitorListener monitorListener) throws MonitorException { - - validateMonitorFilter(monitorFilter, reportRate); // if validation fails, it will throw an exception - - if (includeCumulative) { - validateCumulativeMonitorFilter(monitorFilter); - } // if validation fails, it will throw an exception - - int reportRateIndex = getReportRateIndex(reportRate); - - try { - monitorFilter = (MonitorFilter) DocumentSerializableUtilities.copyDocumentSerializable(monitorFilter); // make a copy of the filter - } catch (DocumentSerializationException e) { - throw new MonitorException(MonitorException.SERIALIZATION, "Error trying to copy MonitorFilter"); - } - - MonitorListenerInfo monitorListenerInfo = new MonitorListenerInfo(monitorListener, reportRate, monitorFilter - , - includeCumulative); - - monitorListenerInfos.add(monitorListenerInfo); - filtersPerRate[reportRateIndex]++; - - if ((filtersPerRate[reportRateIndex] == 1) && (pulseRateIndex != NOT_PULSING) && (reportRateIndex > pulseRateIndex)) { - previousReportTimes[reportRateIndex] = previousReportTimes[pulseRateIndex]; - } - - for (Iterator i = monitorFilter.getModuleClassIDs(); i.hasNext();) { - ModuleClassID moduleClassID = (ModuleClassID) i.next(); - - ServiceMonitorFilter serviceMonitorFilter = monitorFilter.getServiceMonitorFilter(moduleClassID); - ServiceMonitorPulseInfo serviceMonitorPulseInfo = serviceMonitorPulseInfos.get(moduleClassID); - - serviceMonitorPulseInfo.registerServiceMonitorFilter(serviceMonitorFilter, reportRateIndex, reportRate); - } - - resetPulseRate(); - - return reportRate; - } - - private MonitorListenerInfo getMonitorListenerInfo(MonitorListener monitorListener) { - for (Object monitorListenerInfo1 : monitorListenerInfos) { - MonitorListenerInfo monitorListenerInfo = (MonitorListenerInfo) monitorListenerInfo1; - - if (monitorListenerInfo.monitorListener == monitorListener) { - return monitorListenerInfo; - } - } - return null; - } - - public synchronized int removeMonitorListener(MonitorListener monitorListener) { - int numRemoved = 0; - - for (;;) { // remove all instances of this listener - MonitorListenerInfo monitorListenerInfo = getMonitorListenerInfo(monitorListener); - - if (monitorListenerInfo == null) { - break; - } else { - MonitorFilter monitorFilter = monitorListenerInfo.monitorFilter; - long reportRate = monitorListenerInfo.reportRate; - int reportRateIndex = monitorListenerInfo.reportRateIndex; - - monitorListenerInfos.remove(monitorListenerInfo); - numRemoved++; - filtersPerRate[reportRateIndex]--; - - for (Iterator i = monitorFilter.getModuleClassIDs(); i.hasNext();) { - ModuleClassID moduleClassID = (ModuleClassID) i.next(); - - ServiceMonitorFilter serviceMonitorFilter = monitorFilter.getServiceMonitorFilter(moduleClassID); - ServiceMonitorPulseInfo serviceMonitorPulseInfo = serviceMonitorPulseInfos.get(moduleClassID); - - serviceMonitorPulseInfo.deregisterServiceMonitorFilter(serviceMonitorFilter, reportRateIndex, reportRate); - } - } - } - - resetPulseRate(); - - return numRemoved; - } - - public synchronized MonitorReport getCumulativeMonitorReport(MonitorFilter monitorFilter) throws MonitorException { - validateCumulativeMonitorFilter(monitorFilter); - - long beginReportTime = System.currentTimeMillis(); - - MonitorReport monitorReport = new MonitorReport(startTime, beginReportTime, true); - - for (Iterator i = monitorFilter.getModuleClassIDs(); i.hasNext();) { - ModuleClassID moduleClassID = (ModuleClassID) i.next(); - - ServiceMonitorFilter serviceMonitorFilter = monitorFilter.getServiceMonitorFilter(moduleClassID); - ServiceMonitor serviceMonitor = getServiceMonitor(moduleClassID); - - ServiceMetric serviceMetric = serviceMonitor.getCumulativeServiceMetric(serviceMonitorFilter, timeZero - , - beginReportTime); - - monitorReport.addServiceMetric(moduleClassID, serviceMetric); - } - - return monitorReport; - } - - public ModuleClassID[] getMonitorableServiceTypes() { - if (supportedModuleClassIDs == null) { - ModuleClassID[] registeredModuleClassIDs = MonitorResources.getRegisteredModuleClassIDs(); - LinkedList supportedModuleClassIDsList = new LinkedList(); - - for (ModuleClassID registeredModuleClassID : registeredModuleClassIDs) { - if (isLocalMonitoringAvailable(registeredModuleClassID)) { - supportedModuleClassIDsList.add(registeredModuleClassID); - } - } - - supportedModuleClassIDs = supportedModuleClassIDsList.toArray(new ModuleClassID[0]); - } - return supportedModuleClassIDs; - } - - // fastest pulse rate registered anywhere - public long getPulseRate() { - return getReportRate(pulseRateIndex); - } - - // index of fastest pulse anywhere - public int getPulseRateIndex() { - return pulseRateIndex; - } - - // pulse rate for this monitor - public long getPulseRate(ServiceMonitor serviceMonitor) { - ServiceMonitorPulseInfo serviceMonitorPulseInfo = serviceMonitorPulseInfos.get(serviceMonitor.getModuleClassID()); - - if (serviceMonitorPulseInfo != null) { - return serviceMonitorPulseInfo.getPulseRate(); - } else { - return ServiceMonitorPulseInfo.NOT_PULSING; - } - } - - // index of pulse rate for this monitor - public long getPulseRateIndex(ServiceMonitor serviceMonitor) { - ServiceMonitorPulseInfo serviceMonitorPulseInfo = serviceMonitorPulseInfos.get(serviceMonitor.getModuleClassID()); - - if (serviceMonitorPulseInfo != null) { - return serviceMonitorPulseInfo.getPulseRateIndex(); - } else { - return ServiceMonitorPulseInfo.NOT_PULSING; - } - } - - private void generateReports() { - long beginReportTime = System.currentTimeMillis(); - - for (Enumeration e = serviceMonitorPulseInfos.elements(); e.hasMoreElements();) { - ServiceMonitorPulseInfo serviceMonitorPulseInfo = e.nextElement(); - int servicePulseRateIndex = serviceMonitorPulseInfo.getPulseRateIndex(); - - if ((serviceMonitorPulseInfo.serviceMonitor instanceof ServiceMonitorImpl) - && isEvenPulseForRateIndex(servicePulseRateIndex)) { - ((ServiceMonitorImpl) serviceMonitorPulseInfo.serviceMonitor).beginPulse(serviceMonitorPulseInfo); - } - } - - for (Object monitorListenerInfo1 : monitorListenerInfos) { - MonitorListenerInfo monitorListenerInfo = (MonitorListenerInfo) monitorListenerInfo1; - MonitorFilter monitorFilter = monitorListenerInfo.monitorFilter; - MonitorListener monitorListener = monitorListenerInfo.monitorListener; - - int reportRateIndex = monitorListenerInfo.reportRateIndex; - long reportRate = monitorListenerInfo.reportRate; - - if (isEvenPulseForRateIndex(reportRateIndex)) { - MonitorReport monitorReport = null; - - try { - if (monitorListenerInfo.sendCumulativeFirst && !monitorListenerInfo.wasCumulativeSent) { - monitorReport = getCumulativeMonitorReport(monitorFilter); - - MonitorEvent monitorEvent = new MonitorEvent(peerGroup.getPeerGroupID(), monitorReport); - - monitorListener.processMonitorReport(monitorEvent); - monitorListenerInfo.wasCumulativeSent = true; - } else { - monitorReport = getMonitorReport(monitorFilter, reportRate, previousReportTimes[reportRateIndex] - , - beginReportTime); - MonitorEvent monitorEvent = new MonitorEvent(peerGroup.getPeerGroupID(), monitorReport); - - monitorListener.processMonitorReport(monitorEvent); - } - } catch (Throwable e) { - e.printStackTrace(); - // Fix-Me: Where should we report an uncaught exception in one of our listeners? - } - } - } - - for (int rateIndex = 0; rateIndex < supportedReportRates.length; rateIndex++) { - if (isEvenPulseForRateIndex(rateIndex)) { - if (filtersPerRate[rateIndex] != 0) { - previousReportTimes[rateIndex] = beginReportTime; - } else { - previousReportTimes[rateIndex] = NO_PRIOR_REPORT; - } - } - } - - for (Enumeration e = serviceMonitorPulseInfos.elements(); e.hasMoreElements();) { - ServiceMonitorPulseInfo serviceMonitorPulseInfo = e.nextElement(); - int servicePulseRateIndex = serviceMonitorPulseInfo.getPulseRateIndex(); - - if ((serviceMonitorPulseInfo.serviceMonitor instanceof ServiceMonitorImpl) - && isEvenPulseForRateIndex(servicePulseRateIndex)) { - ((ServiceMonitorImpl) serviceMonitorPulseInfo.serviceMonitor).endPulse(serviceMonitorPulseInfo); - } - } - } - - boolean isEvenPulseForRateIndex(int pulseRateIndex) { - if (pulseRateIndex < 0 || pulseRateIndex > pulsesPerRate.length) { - return false; - } - return ((pulseNumber % pulsesPerRate[pulseRateIndex]) == 0); - } - - private void createReportThread() { - reportThread = new Thread(new Runnable() { - public void run() { - mainLoop: - while (isRunning) { - synchronized (MonitorManager.this) { // no new listeners while reporting - while (pulseRate == NOT_PULSING) { - try { - MonitorManager.this.wait(); - } catch (InterruptedException e) { - continue mainLoop; - } - } - - while (pulseRate != NOT_PULSING) { - if (Thread.interrupted()) { - continue mainLoop; - } - - long now = System.currentTimeMillis(); - - try { - long waitTime = nextPulseTime - now; - - if (waitTime > 0) { - MonitorManager.this.wait(nextPulseTime - now); - } - - pulseNumber += pulsesPerRate[pulseRateIndex]; - generateReports(); - nextPulseTime += pulseRate; - } catch (InterruptedException e) { - if (pulseRateIndex == NOT_PULSING) { - continue mainLoop; - } - } catch (Exception ex) { - // don't die forever on exceptions!! - ex.printStackTrace(); // fix-me: report this - } - } - } - } - } - }, "Meter-Monitor-Report"); - - reportThread.setDaemon(true); - reportThread.start(); - } - - public synchronized void destroy() { - isRunning = false; - reportThread.interrupt(); - - for (Enumeration e = serviceMonitorPulseInfos.elements(); e.hasMoreElements();) { - ServiceMonitorPulseInfo serviceMonitorPulseInfo = e.nextElement(); - ServiceMonitor serviceMonitor = serviceMonitorPulseInfo.serviceMonitor; - - serviceMonitor.destroy(); - } - } - - /** - * DO NOT USE THIS FIELD: It will be deprecated when MonitorManager becomes a - * FULL FLEDGED SERVICE - */ - - private static Hashtable monitorManagers = new Hashtable(); - - /** - * DO NOT USE THIS METHOD: It will be deprecated when MonitorManager becomes a - * FULL FLEDGED SERVICE - */ - - public static MonitorManager registerMonitorManager(PeerGroup peerGroup) throws JxtaException { - PeerGroupID peerGroupID = peerGroup.getPeerGroupID(); - MonitorManager monitorManager = monitorManagers.get(peerGroupID); - - if (monitorManager == null) { - boolean includeTransports = true; - ModuleImplAdvertisement moduleImplAdvertisement = MonitorResources.getReferenceAllPurposeMonitorServiceImplAdvertisement( - includeTransports); - - monitorManager = (MonitorManager) peerGroup.loadModule(MonitorResources.refMonitorServiceSpecID - , - moduleImplAdvertisement); - monitorManagers.put(peerGroupID, monitorManager); - - // FIXME jice@jxta.org - 20021103 : this - // monitorManager is not a real group service: - // it is being loadModule()'d by another as a - // result, it holds a counted reference to the - // group. Idealy, we'd need the groupAPI to - // offer a means to loadModule() without - // making a counted reference, so that group - // services can loadModule() things without - // preventing group termination. This could be - // achieved elegantly by making this only - // behaviour available through a weak - // GroupInterface. So it would be enough to - // obtain a weak interface from one's group - // and then use its loadmodule method rather - // than that of the strong group interface. - // However that's a bit too big a change to be - // decided without more carefull - // consideration. Instead, we just simulate - // it for now: we give to the monitor manager - // the real group reference after loadModule - // is done, and it discards the strong - // interface object that was passed to its - // init routine. - - monitorManager.setPeerGroup(peerGroup); - } - return monitorManager; - } - - /** - * DO NOT USE THIS METHOD: It will be deprecated when MonitorManager becomes a - * FULL FLEDGED SERVICE - */ - - public static void unregisterMonitorManager(PeerGroup peerGroup) { - PeerGroupID peerGroupID = peerGroup.getPeerGroupID(); - - monitorManagers.remove(peerGroupID); - } - - public static ServiceMonitor getServiceMonitor(PeerGroup peerGroup, ModuleClassID serviceClassID) { - try { - PeerGroupID peerGroupID = peerGroup.getPeerGroupID(); - MonitorManager monitorManager = monitorManagers.get(peerGroupID); - - return monitorManager.getServiceMonitor(serviceClassID); - } catch (Exception e) { // Fix-Me: This is a bit sloppy - throw new RuntimeException("Unable to find MonitorManager or MonitorService"); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ServiceMonitorImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ServiceMonitorImpl.java deleted file mode 100644 index 509bc0cb..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ServiceMonitorImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.meter; - - -import net.jxta.meter.ServiceMonitor; - - -public interface ServiceMonitorImpl extends ServiceMonitor { - public void init(MonitorManager monitorManager); - - public void resetPulseRate(ServiceMonitorPulseInfo info, int oldPulseRateIndex); - - public void beginPulse(ServiceMonitorPulseInfo pulseInfo); - - public void endPulse(ServiceMonitorPulseInfo pulseInfo); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ServiceMonitorPulseInfo.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ServiceMonitorPulseInfo.java deleted file mode 100644 index a574e119..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ServiceMonitorPulseInfo.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.meter; - - -import net.jxta.meter.*; -import java.util.*; - - -public class ServiceMonitorPulseInfo { - public static final int NOT_PULSING = MonitorManager.NOT_PULSING; - - private MonitorManager monitorManager; - ServiceMonitor serviceMonitor; - private LinkedList registeredServiceMonitorFilters = new LinkedList(); - private int pulseRateIndex = NOT_PULSING; // quickestReportRateIndex registered for this service - private long pulseRate = NOT_PULSING; // quickestReportRate registered for this service - private int filtersPerRate[]; - private boolean pulsing; - - private class RegisteredServiceMonitorFilter { - ServiceMonitorFilter serviceMonitorFilter; - int reportRateIndex; - - RegisteredServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter, int reportRateIndex) { - this.serviceMonitorFilter = serviceMonitorFilter; - this.reportRateIndex = reportRateIndex; - } - } - - public ServiceMonitorPulseInfo() {} - - ServiceMonitorPulseInfo(MonitorManager monitorManager, ServiceMonitor serviceMonitor) { - this.monitorManager = monitorManager; - this.serviceMonitor = serviceMonitor; - filtersPerRate = new int[monitorManager.getReportRatesCount()]; - } - - public ServiceMonitor getServiceMonitor() { - return serviceMonitor; - } - - public int getPulseRateIndex() { - return pulseRateIndex; - } - - public long getPulseRate() { - return pulseRate; - } - - public boolean isPulsing() { - return pulsing; - } - - public boolean isEvenPulseForRateIndex(int pulseRateIndex) { - return monitorManager.isEvenPulseForRateIndex(pulseRateIndex); - } - - public boolean isRegisteredFilterForRate(int pulseRateIndex) { - return (filtersPerRate[pulseRateIndex] != 0); - } - - void registerServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter, int reportRateIndex, long reportRate) { - RegisteredServiceMonitorFilter registeredServiceMonitorFilter = new RegisteredServiceMonitorFilter(serviceMonitorFilter - , - reportRateIndex); - - registeredServiceMonitorFilters.add(registeredServiceMonitorFilter); - - filtersPerRate[reportRateIndex]++; - - if ((pulseRateIndex == NOT_PULSING) || (reportRateIndex < pulseRateIndex)) { - int oldPulseRateIndex = pulseRateIndex; - - pulseRateIndex = reportRateIndex; - pulseRate = reportRate; - pulsing = true; - if (serviceMonitor instanceof ServiceMonitorImpl) { - ((ServiceMonitorImpl) serviceMonitor).resetPulseRate(this, oldPulseRateIndex); - } - } - - boolean newRate = (filtersPerRate[reportRateIndex] == 1); - - serviceMonitor.serviceMonitorFilterRegistered(serviceMonitorFilter, reportRateIndex, reportRate, newRate); - } - - boolean deregisterServiceMonitorFilter(ServiceMonitorFilter serviceMonitorFilter, int reportRateIndex, long reportRate) { - boolean removed = false; - - for (Iterator i = registeredServiceMonitorFilters.iterator(); i.hasNext();) { - RegisteredServiceMonitorFilter registeredMonitorFilter = i.next(); - - if ((registeredMonitorFilter.serviceMonitorFilter == serviceMonitorFilter) - && (registeredMonitorFilter.reportRateIndex == reportRateIndex)) { - i.remove(); - removed = true; - break; - } - } - - if (!removed) { // Fix-Me: This should never happen if Monitor Manager works properly. - return false; - } - - filtersPerRate[reportRateIndex]--; - - serviceMonitor.serviceMonitorFilterDeregistered(serviceMonitorFilter, reportRateIndex, reportRate - , - filtersPerRate[reportRateIndex] == 0); - - if ((filtersPerRate[reportRateIndex] == 0) && (reportRateIndex == pulseRateIndex)) { - // pulseRateSlowing Down - int newPulseRateIndex = NOT_PULSING; - - for (int i = pulseRateIndex; i < filtersPerRate.length; i++) { - if (filtersPerRate[i] != 0) { - newPulseRateIndex = i; - break; - } - } - - int oldPulserRateIndex = pulseRateIndex; - - pulseRateIndex = newPulseRateIndex; - - if (newPulseRateIndex != NOT_PULSING) { - pulseRate = monitorManager.getReportRate(pulseRateIndex); - pulsing = true; - } else { - pulseRate = NOT_PULSING; - pulsing = false; - } - - if (serviceMonitor instanceof ServiceMonitorImpl) { - ((ServiceMonitorImpl) serviceMonitor).resetPulseRate(this, oldPulserRateIndex); - } - } - return removed; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ServiceMonitorResource.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ServiceMonitorResource.java deleted file mode 100644 index db5075de..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/meter/ServiceMonitorResource.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.meter; - - -import net.jxta.exception.JxtaException; -import net.jxta.meter.ServiceMonitor; -import net.jxta.platform.ModuleClassID; -import net.jxta.service.Service; - - -public interface ServiceMonitorResource extends Service { - public ServiceMonitor getServiceMonitor(ModuleClassID moduleClassID) throws JxtaException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/monitor.properties b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/monitor.properties deleted file mode 100644 index 479d94a4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/monitor.properties +++ /dev/null @@ -1,64 +0,0 @@ - -net.meter.standardEndpoint=Endpoint, \ - urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000080106, \ - net.jxta.impl.endpoint.endpointMeter.EndpointServiceMonitor, \ - net.jxta.impl.endpoint.endpointMeter.EndpointServiceMonitorFilter, \ - net.jxta.impl.endpoint.endpointMeter.EndpointServiceMetric, \ - urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000080106 - -net.meter.standardTransport=Transport, \ - urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000080106, \ - net.jxta.impl.endpoint.transportMeter.TransportServiceMonitor, \ - net.jxta.impl.endpoint.transportMeter.TransportServiceMonitorFilter, \ - net.jxta.impl.endpoint.transportMeter.TransportServiceMetric, \ - urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE0000000A0106 \ - urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000090106 \ - urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE0000000B0106 - -#net.meter.standardPipe=Pipe, \ -# urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000040106, -# net.jxta.impl.pipe.pipeMeter.PipeServiceMonitor, \ -# net.jxta.impl.pipe.pipeMeter.PipeServiceMonitorFilter, \ -# net.jxta.impl.resolver.pipeMeter.PipeServiceMetric, \ -# urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000040106 -# - -net.meter.standardResolver=Resolver, \ - urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000020106, \ - net.jxta.impl.resolver.resolverMeter.ResolverServiceMonitor, \ - net.jxta.impl.resolver.resolverMeter.ResolverServiceMonitorFilter, \ - net.jxta.impl.resolver.resolverMeter.ResolverServiceMetric, \ - urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000020106 - -net.meter.standardRendezvous=Rendezvous, \ - urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000060106, \ - net.jxta.impl.rendezvous.rendezvousMeter.RendezvousServiceMonitor, \ - net.jxta.impl.rendezvous.rendezvousMeter.RendezvousServiceMonitorFilter, \ - net.jxta.impl.rendezvous.rendezvousMeter.RendezvousServiceMetric, \ - urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000060106 - -#net.meter.standardProxy=Proxy, \ -# net.jxta.impl.endpoint.ProxyMeter.ProxyServiceMonitor, \ -# net.jxta.impl.endpoint.ProxyMeter.ProxyServiceMonitorFilter, \ -# net.jxta.impl.endpoint.ProxyMeter.RendezvousServiceMetric, \ -# urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE0000000E0106 -# -#net.meter.standardDiscovery=Discovery, \ -# net.jxta.impl.discovery.discoveryMeter.DiscoveryServiceMonitor, \ -# net.jxta.impl.discovery.discoveryMeter.DiscoveryServiceMonitorFilter, \ -# net.jxta.impl.discovery.discoveryMeter.DiscoveryServiceMetric, \ -# urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000030106 -# -#net.meter.standardMembership=Membership, \ -# net.jxta.impl.membership.membershipMeter.MembershipServiceMonitor, \ -# net.jxta.impl.membership.membershipMeter.MembershipServiceMonitorFilter, \ -# net.jxta.impl.membership.membershipMeter.MembershipServiceMetric, \ -# urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000050106 -# -#net.meter.standardEndpoint=PeerInfo, \ -# net.jxta.impl.peer.peerInfoMeter.PeerInfoServiceMonitor, \ -# net.jxta.impl.peer.peerInfoMeter.PeerInfoServiceMonitorFilter, \ -# net.jxta.impl.peer.peerInfoMeter.PeerInfoServiceMetric, \ -# urn:jxta:uuid-DEADBEEFDEAFBABAFEEDBABE000000070106 -# - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/overview.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/overview.html deleted file mode 100644 index c249f030..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/overview.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - These packages provide the reference implementation of the JXTA Protocols - using Java Standard Edition 5.0. The JSE reference implementation is - divided into two parts: - The JSE Standard JXTA API - and, this package, the JSE JXTA Reference Implementation. - -

            Additional optional packages which are useful for developers building - JXTA applications can be found in the JXTA JSE Extensions. - - -

            Important Note: Applications and services are very - strongly encouraged to not import classes or interfaces from these - implementation packages. Specificially do not import from - net.jxta.impl.*. The content of these packages may change - significantly (including removal) from release to release with no advance - notice. - - @see JXTA Protocols Specification - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoHandler.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoHandler.java deleted file mode 100644 index 965e4a42..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoHandler.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.peer; - - -import net.jxta.peer.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.protocol.*; - - -interface PeerInfoHandler { - public void processRequest(int queryId, PeerID requestSourceID, PeerInfoQueryMessage peerInfoQueryMessage, Element requestElement, PeerInfoMessenger peerInfoMessenger); - public void processResponse(int queryId, PeerInfoResponseMessage peerInfoResponseMessage, Element responseElement, PeerInfoMessenger peerInfoMessenger); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoMessenger.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoMessenger.java deleted file mode 100644 index 0772e798..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoMessenger.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.peer; - - -import net.jxta.peer.*; -import net.jxta.util.documentSerializable.*; - - -interface PeerInfoMessenger { - public void sendPeerInfoRequest(int queryID, PeerID destinationPeerID, String peerInfoHandler, DocumentSerializable request); - public void sendPeerInfoResponse(int queryId, PeerID destinationPeerID, String peerInfoHandler, DocumentSerializable response); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoServiceImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoServiceImpl.java deleted file mode 100644 index f9ddfeff..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoServiceImpl.java +++ /dev/null @@ -1,560 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.peer; - - -import java.util.Hashtable; -import java.util.Random; -import java.io.StringReader; -import java.net.URI; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.service.Service; -import net.jxta.endpoint.EndpointService; -import net.jxta.resolver.ResolverService; -import net.jxta.resolver.QueryHandler; -import net.jxta.document.Advertisement; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.document.MimeMediaType; -import net.jxta.document.Element; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.protocol.ResolverQueryMsg; -import net.jxta.protocol.ResolverResponseMsg; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerInfoQueryMessage; -import net.jxta.protocol.PeerInfoResponseMessage; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peer.PeerInfoService; -import net.jxta.credential.Credential; -import net.jxta.membership.MembershipService; -import net.jxta.impl.protocol.ResolverQuery; -import net.jxta.impl.protocol.ResolverResponse; -import net.jxta.impl.protocol.PeerInfoQueryMsg; -import net.jxta.impl.protocol.PeerInfoResponseMsg; -import net.jxta.exception.JxtaException; -import net.jxta.exception.PeerGroupException; - -import net.jxta.meter.*; -import net.jxta.impl.meter.*; -import net.jxta.peer.*; -import net.jxta.platform.*; -import net.jxta.util.documentSerializable.*; - - -/** - * Peer Info provides a mechanism to obtain information about peers. - * - */ - -public class PeerInfoServiceImpl implements PeerInfoService { - - private final static Logger LOG = Logger.getLogger(PeerInfoServiceImpl.class.getName()); - - /** - * Time in milli seconds since midnight, January 1, 1970 UTC and when this - * peer was started. - */ - private long startTime = 0; - - private ResolverService resolver = null; - private PeerGroup group = null; - private EndpointService endpoint = null; - private PeerID localPeerId = null; - private ModuleImplAdvertisement implAdvertisement = null; - private String resolverHandlerName = null; - private MembershipService membership = null; - private Credential credential = null; - private StructuredDocument credentialDoc = null; - private MonitorManager monitorManager; - private Hashtable peerInfoHandlers = new Hashtable(); - private PipQueryHandler pipQueryHandler = new PipQueryHandler(); - private RemoteMonitorPeerInfoHandler remoteMonitorPeerInfoHandler; - private PeerInfoMessenger resolverServicePeerInfoMessenger = new ResolverServicePeerInfoMessenger(); - - private int nextQueryId = 1000; - private static final Random rand = new Random(); - - // This static package public hashtable of registered PeerInfoServiceImpls - // allows us to do Peergroup Monitoring via an IP Bridge to the PIP - // See the documentation on the JXTA Monitor - static Hashtable peerInfoServices = new Hashtable(); - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement impl) throws PeerGroupException { - this.group = group; - - implAdvertisement = (ModuleImplAdvertisement) impl; - localPeerId = group.getPeerID(); - resolverHandlerName = assignedID.toString(); - - // Fix-Me: When MonitorManager is a true Service, this should be moved to startApp() - try { - if (MeterBuildSettings.METERING) { - monitorManager = MonitorManager.registerMonitorManager(group); - } - // FIXME This will become a service lookup when MonitorService is a real service - } catch (JxtaException e) { - throw new PeerGroupException("Unable to load MonitorManager", e); - } - - // record start time at end of successful init - startTime = System.currentTimeMillis(); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring PeerInfo Service : " + assignedID); - - configInfo.append("\n\tImplementation:"); - configInfo.append("\n\t\tImpl Description: "); - configInfo.append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - configInfo.append("\n\tGroup Params:"); - configInfo.append("\n\t\tGroup: ").append(group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID: ").append(group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID: ").append(group.getPeerID()); - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] arg) { - - resolver = group.getResolverService(); - - if (null == resolver) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a resolver service"); - } - - return START_AGAIN_STALLED; - } - - /* Fix-Me: When MonitorService is a true service, this should be moved here from init() - try { - if (MeterBuildSettings.METERING) - monitorManager = MonitorManager.registerMonitorManager(group); - // FIXME : This will become a service lookup when MonitorService is a real service - } catch (JxtaException e) { - return -1; // Fix-Me: This is related to the initialization sequence work on the dev list on load order - } - */ - - // remoteMonitorPeerInfoHandler = new RemoteMonitorPeerInfoHandler(group, this); - // peerInfoHandlers.put(RemoteMonitorPeerInfoHandler.MONITOR_HANDLER_NAME, remoteMonitorPeerInfoHandler); - - resolver = group.getResolverService(); - resolver.registerHandler(resolverHandlerName, pipQueryHandler); - - peerInfoServices.put(group, this); - - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - public void stopApp() { - - peerInfoServices.remove(group); - resolver.unregisterHandler(resolverHandlerName); - resolver = null; - - // peerInfoHandlers.remove(RemoteMonitorPeerInfoHandler.MONITOR_HANDLER_NAME); - // remoteMonitorPeerInfoHandler.stop(); - - if (MeterBuildSettings.METERING) { - MonitorManager.unregisterMonitorManager(group); - } - - group = null; - } - - /** - * {@inheritDoc} - */ - public Service getInterface() { - return new PeerInfoServiceInterface(this); - } - - /** - * {@inheritDoc} - */ - public Advertisement getImplAdvertisement() { - return implAdvertisement; - } - - PeerInfoHandler getPeerInfoHandler(String name) { - return (PeerInfoHandler) peerInfoHandlers.get(name); - } - - int getNextQueryId() { - int id = 0; - - synchronized (rand) { - id = rand.nextInt(Integer.MAX_VALUE); - } - return id; - } - - /** - * Returns the group to which this service is attached. - * - * @return PeerGroup the group - */ - public PeerGroup getGroup() { - return group; - } - - /** - * {@inheritDoc} - */ - public boolean isLocalMonitoringAvailable() { - return MeterBuildSettings.METERING; - } - - /** - * {@inheritDoc} - */ - public boolean isLocalMonitoringAvailable(ModuleClassID moduleClassID) { - return MeterBuildSettings.METERING && monitorManager.isLocalMonitoringAvailable(moduleClassID); - } - - /** - * {@inheritDoc} - */ - public long[] getSupportedReportRates() { - return MonitorManager.getReportRates(); - } - - /** - * {@inheritDoc} - */ - public boolean isSupportedReportRate(long reportRate) { - return monitorManager.isSupportedReportRate(reportRate); - } - - /** - * {@inheritDoc} - */ - public long getBestReportRate(long desiredReportRate) { - return monitorManager.getBestReportRate(desiredReportRate); - } - - /** - * {@inheritDoc} - */ - public PeerMonitorInfo getPeerMonitorInfo() { - if (monitorManager != null) { - return monitorManager.getPeerMonitorInfo(); - } else { - return PeerMonitorInfo.NO_PEER_MONITOR_INFO; - } - } - - /** - * {@inheritDoc} - */ - public void getPeerMonitorInfo(final PeerID peerID, PeerMonitorInfoListener peerMonitorInfoListener, long timeout) throws MonitorException { - remoteMonitorPeerInfoHandler.getPeerMonitorInfo(peerID, peerMonitorInfoListener, timeout, resolverServicePeerInfoMessenger); - } - - /** - * {@inheritDoc} - */ - public MonitorReport getCumulativeMonitorReport(MonitorFilter monitorFilter) throws MonitorException { - if (MeterBuildSettings.METERING) { - throw new MonitorException(MonitorException.METERING_NOT_SUPPORTED, "Local Monitoring not Available"); - } - return monitorManager.getCumulativeMonitorReport(monitorFilter); - - } - - /** - * {@inheritDoc} - */ - public void getCumulativeMonitorReport(PeerID peerID, MonitorFilter monitorFilter, MonitorListener monitorListener, long timeout) throws MonitorException { - remoteMonitorPeerInfoHandler.getCumulativeMonitorReport(peerID, monitorFilter, monitorListener, timeout - , - resolverServicePeerInfoMessenger); - } - - /** - * {@inheritDoc} - */ - public long addMonitorListener(MonitorFilter monitorFilter, long reportRate, boolean includeCumulative, MonitorListener monitorListener) throws MonitorException { - if (!MeterBuildSettings.METERING) { - throw new MonitorException(MonitorException.METERING_NOT_SUPPORTED, "Local Monitoring not Available"); - } - - return monitorManager.addMonitorListener(monitorFilter, reportRate, includeCumulative, monitorListener); - } - - /** - * {@inheritDoc} - */ - public void addRemoteMonitorListener(PeerID peerID, MonitorFilter monitorFilter, long reportRate, boolean includeCumulative, MonitorListener monitorListener, long lease, long timeout) throws MonitorException { - remoteMonitorPeerInfoHandler.addRemoteMonitorListener(peerID, monitorFilter, reportRate, includeCumulative - , - monitorListener, lease, timeout, resolverServicePeerInfoMessenger); - } - - /** - * {@inheritDoc} - */ - public boolean removeMonitorListener(MonitorListener monitorListener) throws MonitorException { - - int numRemoved = monitorManager.removeMonitorListener(monitorListener); - - return numRemoved > 0; - } - - /** - * {@inheritDoc} - */ - public void removeRemoteMonitorListener(PeerID peerID, MonitorListener monitorListener, long timeout) throws MonitorException { - remoteMonitorPeerInfoHandler.removeRemoteMonitorListener(peerID, monitorListener, timeout - , - resolverServicePeerInfoMessenger); - } - - /** - * {@inheritDoc} - */ - public void removeRemoteMonitorListener(MonitorListener monitorListener, long timeout) throws MonitorException { - remoteMonitorPeerInfoHandler.removeRemoteMonitorListener(monitorListener, timeout, resolverServicePeerInfoMessenger); - } - - class PipQueryHandler implements QueryHandler { - - /** - * {@inheritDoc} - */ - public int processQuery(ResolverQueryMsg query) { - int queryId = query.getQueryId(); - PeerID requestSourceID = null; - - try { - requestSourceID = (PeerID) IDFactory.fromURI(new URI(query.getSrc())); - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "PeerInfoService.processQuery got a bad query, not valid src", e); - } - return ResolverService.OK; - } - - XMLDocument doc = null; - - try { - doc = (XMLDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, new StringReader(query.getQuery())); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "PeerInfoService.processQuery got a bad adv", e); - } - return ResolverService.OK; - } - - PeerInfoQueryMessage pipquery = new PeerInfoQueryMsg(doc); - - Element requestElement = pipquery.getRequest(); - String queryType = (String) requestElement.getKey(); - - if (queryType != null) { - PeerInfoHandler peerInfoHandler = getPeerInfoHandler(queryType); - - if (peerInfoHandler != null) { - peerInfoHandler.processRequest(queryId, requestSourceID, pipquery, requestElement - , - resolverServicePeerInfoMessenger); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No registered PeerInfoHandler for this type of request"); - } - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No request PeerInfoQueryMessage Request Element found"); - } - } - - return ResolverService.OK; - } - - /** - * {@inheritDoc} - */ - public void processResponse(ResolverResponseMsg response) { - - int queryId = response.getQueryId(); - - PeerInfoResponseMessage resp = null; - - try { - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8 - , - new StringReader(response.getResponse())); - - resp = new PeerInfoResponseMsg(doc); - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "PeerInfoService.processResponse got a bad adv", e); - } - return; - } - - Element responseElement = resp.getResponse(); - String responseType = (String) responseElement.getKey(); - - if (responseType != null) { - PeerInfoHandler peerInfoHandler = getPeerInfoHandler(responseType); - - if (peerInfoHandler != null) { - peerInfoHandler.processResponse(queryId, resp, responseElement, resolverServicePeerInfoMessenger); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No registered PeerInfoHandler for this type of response"); - } - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No request PeerInfoResponseMessage Response Element found"); - } - } - } - } - - - private class ResolverServicePeerInfoMessenger implements PeerInfoMessenger { - - /** - * {@inheritDoc} - */ - public void sendPeerInfoResponse(int queryId, PeerID destinationPeerID, String peerInfoHandler, DocumentSerializable response) { - try { - PeerInfoResponseMessage peerInfoResponseMessage = new PeerInfoResponseMsg(); - - peerInfoResponseMessage.setSourcePid(destinationPeerID); - peerInfoResponseMessage.setTargetPid(localPeerId); - - long now = System.currentTimeMillis(); - - peerInfoResponseMessage.setUptime(now - startTime); - peerInfoResponseMessage.setTimestamp(now); - - Element responseElement = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, peerInfoHandler); - - response.serializeTo(responseElement); - - peerInfoResponseMessage.setResponse(responseElement); - - XMLDocument doc = (XMLDocument) peerInfoResponseMessage.getDocument(MimeMediaType.XMLUTF8); - String peerInfoResponse = doc.toString(); - - ResolverResponse resolverResponse = new ResolverResponse(resolverHandlerName, credentialDoc, queryId - , - peerInfoResponse); - - resolver.sendResponse(destinationPeerID.toString(), resolverResponse); - } catch (JxtaException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure building document", e); - } - } - } - - /** - * {@inheritDoc} - */ - public void sendPeerInfoRequest(int queryID, PeerID destinationPeerID, String peerInfoHandler, DocumentSerializable request) { - try { - PeerInfoQueryMsg peerInfoQueryMsg = new PeerInfoQueryMsg(); - - peerInfoQueryMsg.setSourcePid(localPeerId); - peerInfoQueryMsg.setTargetPid(destinationPeerID); - - Element requestElement = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, peerInfoHandler); - - request.serializeTo(requestElement); - - peerInfoQueryMsg.setRequest(requestElement); - - XMLDocument doc = (XMLDocument) peerInfoQueryMsg.getDocument(MimeMediaType.XMLUTF8); - String peerInfoRequest = doc.toString(); - - ResolverQuery resolverQuery = new ResolverQuery(resolverHandlerName, credentialDoc, localPeerId.toString() - , - peerInfoRequest, queryID); - - resolver.sendQuery(destinationPeerID.toString(), resolverQuery); - } catch (JxtaException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure to build resolver query", e); - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoServiceInterface.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoServiceInterface.java deleted file mode 100644 index 5f5c8751..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/PeerInfoServiceInterface.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peer; - - -import java.io.IOException; -import java.util.Enumeration; -import net.jxta.document.Advertisement; -import net.jxta.service.Service; -import net.jxta.id.ID; -import net.jxta.peer.PeerInfoService; -import net.jxta.peer.PeerInfoListener; -import net.jxta.peer.PeerInfoEvent; -import net.jxta.peergroup.PeerGroup; -import net.jxta.exception.PeerGroupException; -import net.jxta.protocol.PeerInfoResponseMessage; -import net.jxta.impl.peer.PeerInfoServiceImpl; -import net.jxta.peer.*; -import net.jxta.meter.*; -import net.jxta.platform.*; - - -/** - * PeerInfoServiceInterface provides a pure interface object that permits - * interaction with the actual PeerInfoService implementation without giving - * access to the real object. - */ -public class PeerInfoServiceInterface implements PeerInfoService { - - private PeerInfoService impl; - - /** - * {@inheritDoc} - * Since THIS is already such an - * object, it returns itself. FIXME: it is kind of absurd to have this - * method part of the interface but we do not want to define two levels - * of Service interface just for that. - * - */ - public Service getInterface() { - return this; - } - - /** - * {@inheritDoc} - * - */ - public Advertisement getImplAdvertisement() { - return impl.getImplAdvertisement(); - } - - /** - * Only authorized constructor - * - *@param theRealThing - */ - public PeerInfoServiceInterface(PeerInfoService theRealThing) { - impl = theRealThing; - } - - /** - * {@inheritDoc} - *

            Initialize the application FIXME: This is meaningless for the - * interface object; it is there only to satisfy the requirements of - * the interface that we implement. Ultimately, the API should define - * two levels of interfaces: one for the real service implementation - * and one for the interface object. Right now it feels a bit heavy to - * so that since the only different between the two would be init() and - * may-be getName(). - * - */ - public void init(PeerGroup pg, ID assignedID, Advertisement impl) {} - - /** - * {@inheritDoc} - *

            This is here for temporary class hierarchy reasons. it is ALWAYS - * ignored. By definition, the interface object protects the real - * object's start/stop methods from being called - * - */ - public int startApp(String[] arg) { - return 0; - } - - /** - * {@inheritDoc} - *

            This is here for temporary class hierarchy reasons. it is ALWAYS - * ignored. By definition, the interface object protects the real - * object's start/stop methods from being called This request is - * currently ignored. - */ - public void stopApp() {} - - public boolean isLocalMonitoringAvailable() { - return (impl.isLocalMonitoringAvailable()); - } - - public boolean isLocalMonitoringAvailable(ModuleClassID moduleClassID) { - return (impl.isLocalMonitoringAvailable(moduleClassID)); - } - - public long[] getSupportedReportRates() { - return impl.getSupportedReportRates(); - } - - public boolean isSupportedReportRate(long reportRate) { - return impl.isSupportedReportRate(reportRate); - } - - public long getBestReportRate(long desiredReportRate) { - return impl.getBestReportRate(desiredReportRate); - } - - public PeerMonitorInfo getPeerMonitorInfo() { - return impl.getPeerMonitorInfo(); - } - - public void getPeerMonitorInfo(PeerID peerID, PeerMonitorInfoListener peerMonitorInfoListener, long timeout) throws MonitorException { - impl.getPeerMonitorInfo(peerID, peerMonitorInfoListener, timeout); - } - - public MonitorReport getCumulativeMonitorReport(MonitorFilter monitorFilter) throws MonitorException { - return impl.getCumulativeMonitorReport(monitorFilter); - } - - public void getCumulativeMonitorReport(PeerID peerID, MonitorFilter monitorFilter, MonitorListener monitorListener, long timeout) throws MonitorException { - impl.getCumulativeMonitorReport(peerID, monitorFilter, monitorListener, timeout); - } - - public long addMonitorListener(MonitorFilter monitorFilter, long reportRate, boolean includeCumulative, MonitorListener monitorListener) throws MonitorException { - return impl.addMonitorListener(monitorFilter, reportRate, includeCumulative, monitorListener); - } - - public void addRemoteMonitorListener(PeerID peerID, MonitorFilter monitorFilter, long reportRate, boolean includeCumulative, MonitorListener monitorListener, long lease, long timeout) throws MonitorException { - impl.addRemoteMonitorListener(peerID, monitorFilter, reportRate, includeCumulative, monitorListener, lease, timeout); - } - - public boolean removeMonitorListener(MonitorListener monitorListener) throws MonitorException { - return impl.removeMonitorListener(monitorListener); - } - - public void removeRemoteMonitorListener(PeerID peerID, MonitorListener monitorListener, long timeout) throws MonitorException { - impl.removeRemoteMonitorListener(peerID, monitorListener, timeout); - } - - public void removeRemoteMonitorListener(MonitorListener monitorListener, long timeout) throws MonitorException { - impl.removeRemoteMonitorListener(monitorListener, timeout); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/RemoteMonitorPeerInfoHandler.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/RemoteMonitorPeerInfoHandler.java deleted file mode 100644 index a92d4857..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/RemoteMonitorPeerInfoHandler.java +++ /dev/null @@ -1,638 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peer; - -import java.util.Enumeration; -import java.util.Iterator; -import java.util.Hashtable; -import java.util.Random; -import java.util.Timer; -import java.util.TimerTask; -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.document.Element; -import net.jxta.protocol.PeerInfoQueryMessage; -import net.jxta.protocol.PeerInfoResponseMessage; -import net.jxta.peergroup.PeerGroup; -import net.jxta.exception.PeerGroupException; -import net.jxta.peer.PeerInfoService; -import net.jxta.peergroup.PeerGroupID; - -import net.jxta.meter.MonitorEvent; -import net.jxta.meter.MonitorException; -import net.jxta.meter.MonitorFilter; -import net.jxta.meter.MonitorFilterException; -import net.jxta.meter.MonitorListener; -import net.jxta.meter.MonitorReport; -import net.jxta.meter.MonitorResources; -import net.jxta.meter.PeerMonitorInfo; -import net.jxta.meter.PeerMonitorInfoEvent; -import net.jxta.meter.PeerMonitorInfoListener; -import net.jxta.meter.ServiceMonitorFilter; -import net.jxta.peer.PeerID; -import net.jxta.util.documentSerializable.DocumentSerializableUtilities; -import net.jxta.util.documentSerializable.DocumentSerializationException; -import net.jxta.impl.util.TimerThreadNamer; - -class RemoteMonitorPeerInfoHandler implements PeerInfoHandler { - public static final String MONITOR_HANDLER_NAME = "Monitor"; - public static final int MAX_LEASE = 5 * 60 * 1000; // 5 minutes - public static final int MIN_LEASE = 60 * 1000; // 1 minute - - private static final Random rand = new Random(); - private final static Logger LOG = Logger.getLogger(RemoteMonitorPeerInfoHandler.class.getName()); - - private Hashtable requestInfos = new Hashtable(); - private Hashtable leaseInfos = new Hashtable(); - private Hashtable timeouts = new Hashtable(); - private PeerGroup peerGroup; - private PeerInfoServiceImpl peerInfoServiceImpl; - private Timer timer = new Timer(true); - - RemoteMonitorPeerInfoHandler(PeerGroup peerGroup, PeerInfoServiceImpl peerInfoServiceImpl) { - this.peerGroup = peerGroup; - this.peerInfoServiceImpl = peerInfoServiceImpl; - timer.schedule(new TimerThreadNamer("RemoteMonitorPeerInfo timer for " + peerGroup.getPeerGroupID()), 0); - } - - public void stop() { - timer.cancel(); - } - - private int getNextLeaseId() { - int id; - synchronized (rand) { - id = rand.nextInt(Integer.MAX_VALUE); - } - return id; - } - - private class RequestInfo { - long requestTime = System.currentTimeMillis(); - PeerID peerId; - int queryId; - int origRequestId; - MonitorListener monitorListener; - PeerMonitorInfoListener peerMonitorInfoListener; - long timeout; - long validUntil; - boolean responseReceived = false; - int leaseId; // other guys leaseId. - long requestedLease; - PeerInfoMessenger peerInfoMessenger; - RequestInfo(PeerID peerId, int queryId, MonitorListener monitorListener, long timeout, PeerInfoMessenger peerInfoMessenger) { - this(peerId, queryId, timeout, peerInfoMessenger); - this.monitorListener = monitorListener; - } - - RequestInfo(PeerID peerId, int queryId, PeerMonitorInfoListener peerMonitorInfoListener, long timeout, PeerInfoMessenger peerInfoMessenger) { - this(peerId, queryId, timeout, peerInfoMessenger); - this.peerMonitorInfoListener = peerMonitorInfoListener; - } - - RequestInfo(PeerID peerId, int queryId, long timeout, PeerInfoMessenger peerInfoMessenger) { - this.peerId = peerId; - this.queryId = queryId; - this.timeout = timeout; - this.peerInfoMessenger = peerInfoMessenger; - this.validUntil = System.currentTimeMillis() + timeout; - } - } - - - private class LeaseInfo { - int leaseId; - PeerID peerID; // Peer that requested the lease - int queryId; // The other guy's query Id - MonitorListener monitorListener; - long validUntil; - boolean listenerAddedToWorldGroup = false; - PeerGroup worldGroup; - PeerInfoMessenger peerInfoMessenger; - LeaseInfo(int leaseId, PeerID peerID, int queryId, MonitorListener monitorListener, long leaseLength, PeerInfoMessenger peerInfoMessenger) { - this.leaseId = leaseId; - this.peerID = peerID; - this.queryId = queryId; - this.monitorListener = monitorListener; - this.peerInfoMessenger = peerInfoMessenger; - validUntil = System.currentTimeMillis() + leaseLength; - } - - } - - public void getPeerMonitorInfo(final PeerID peerID, PeerMonitorInfoListener peerMonitorInfoListener, long timeout, PeerInfoMessenger peerInfoMessenger) throws MonitorException { - int queryId = peerInfoServiceImpl.getNextQueryId(); - - RemoteMonitorQuery remoteMonitorQuery = RemoteMonitorQuery.createPeerMonitorInfoQuery(); - peerInfoMessenger.sendPeerInfoRequest(queryId, peerID, MONITOR_HANDLER_NAME, remoteMonitorQuery); - final RequestInfo requestInfo = new RequestInfo(peerID, queryId, peerMonitorInfoListener, timeout, peerInfoMessenger); - requestInfos.put(queryId, requestInfo); - timer.schedule(new TimerTask() { - @Override - public void run() { - if (!requestInfo.responseReceived) { - PeerMonitorInfoEvent peerMonitorInfoEvent = new PeerMonitorInfoEvent(peerID, null); - - requestInfo.peerMonitorInfoListener.peerMonitorInfoNotReceived(peerMonitorInfoEvent); - requestInfos.remove(requestInfo.queryId); - } - } - }, timeout); - } - - public void getCumulativeMonitorReport(PeerID peerID, MonitorFilter monitorFilter, MonitorListener monitorListener, long timeout, PeerInfoMessenger peerInfoMessenger) throws MonitorException { - int queryId = peerInfoServiceImpl.getNextQueryId(); - RemoteMonitorQuery remoteMonitorQuery = RemoteMonitorQuery.createGetCumulativeReportQuery(monitorFilter); - peerInfoMessenger.sendPeerInfoRequest(queryId, peerID, MONITOR_HANDLER_NAME, remoteMonitorQuery); - final RequestInfo requestInfo = new RequestInfo(peerID, queryId, monitorListener, timeout, peerInfoMessenger); - requestInfos.put(queryId, requestInfo); - timer.schedule(new TimerTask() { - @Override - public void run() { - if (!requestInfo.responseReceived) { - requestInfos.remove(requestInfo.queryId); - } - } - }, timeout); - } - - public void addRemoteMonitorListener(PeerID peerID, MonitorFilter monitorFilter, long reportRate, boolean includeCumulative, MonitorListener monitorListener, long lease, long timeout, PeerInfoMessenger peerInfoMessenger) throws MonitorException { - int queryId = peerInfoServiceImpl.getNextQueryId(); - RemoteMonitorQuery remoteMonitorQuery = RemoteMonitorQuery.createRegisterMonitorQuery(includeCumulative, monitorFilter, reportRate, lease); - peerInfoMessenger.sendPeerInfoRequest(queryId, peerID, MONITOR_HANDLER_NAME, remoteMonitorQuery); - final RequestInfo requestInfo = new RequestInfo(peerID, queryId, monitorListener, timeout, peerInfoMessenger); - requestInfo.requestedLease = lease; - requestInfos.put(queryId, requestInfo); - timer.schedule(new TimerTask() { - @Override - public void run() { - if (!requestInfo.responseReceived) { - MonitorEvent monitorEvent = MonitorEvent.createFailureEvent(MonitorEvent.TIMEOUT, requestInfo.peerId, - requestInfo.queryId); - - requestInfo.monitorListener.monitorRequestFailed(monitorEvent); - requestInfos.remove(requestInfo.queryId); - } - } - }, timeout); - scheduleTimeout(requestInfo); - } - - public void removeRemoteMonitorListener(PeerID peerID, MonitorListener monitorListener, long timeout, PeerInfoMessenger peerInfoMessenger) throws MonitorException { - int queryId = peerInfoServiceImpl.getNextQueryId(); - - RequestInfo oldRequestInfo = null; - for (Enumeration e = requestInfos.elements(); e.hasMoreElements();) { - RequestInfo ri = e.nextElement(); - - if (ri.monitorListener == monitorListener) { - oldRequestInfo = ri; - break; - } - } - - if (oldRequestInfo != null) { - RemoteMonitorQuery remoteMonitorQuery = RemoteMonitorQuery.createRemoveMonitorListenerQuery(oldRequestInfo.leaseId); - peerInfoMessenger.sendPeerInfoRequest(queryId, peerID, MONITOR_HANDLER_NAME, remoteMonitorQuery); - final RequestInfo requestInfo = new RequestInfo(peerID, queryId, monitorListener, timeout, peerInfoMessenger); - requestInfo.origRequestId = oldRequestInfo.queryId; - requestInfos.put(queryId, requestInfo); - } - - final RequestInfo requestInfo = oldRequestInfo; - timer.schedule(new TimerTask() { - - @Override - public void run() { - requestInfos.remove(new Integer(requestInfo.queryId)); - } - }, timeout); - } - - public void removeRemoteMonitorListener(MonitorListener monitorListener, long timeout, PeerInfoMessenger peerInfoMessenger) throws MonitorException { - for (Enumeration e = requestInfos.elements(); e.hasMoreElements();) { - RequestInfo requestInfo = e.nextElement(); - - if (requestInfo.monitorListener == monitorListener) { - removeRemoteMonitorListener(requestInfo.peerId, monitorListener, timeout, peerInfoMessenger); - } - } - } - - public void processRequest(int queryId, PeerID requestSourceID, PeerInfoQueryMessage peerInfoQueryMessage, Element requestElement, PeerInfoMessenger peerInfoMessenger) { - try { - RemoteMonitorQuery remoteMonitorQuery = (RemoteMonitorQuery) DocumentSerializableUtilities.getDocumentSerializable(requestElement, RemoteMonitorQuery.class); - - if (remoteMonitorQuery.isRegisterMonitorQuery()) { - handleRegisterMonitorQuery(queryId, requestSourceID, remoteMonitorQuery, peerInfoMessenger); - - } else if (remoteMonitorQuery.isCumulativeReportQuery()) { - handleCumulativeReportQuery(queryId, requestSourceID, remoteMonitorQuery.getMonitorFilter(), peerInfoMessenger); - - } else if (remoteMonitorQuery.isRemoveMonitorQuery()) { - handleRemoveMonitorQuery(queryId, requestSourceID, remoteMonitorQuery, peerInfoMessenger); - - } else if (remoteMonitorQuery.isPeerMonitorInfoQuery()) { - handlePeerMonitorInfoQuery(queryId, requestSourceID, peerInfoMessenger); - - } else if (remoteMonitorQuery.isLeaseRenewal()) { - handleLeaseRenewalQuery(queryId, requestSourceID, remoteMonitorQuery, peerInfoMessenger); - - } - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Monitor failed in processQuery", e); - } - } - } - - public void processResponse(int queryId, PeerInfoResponseMessage peerInfoResponseMessage, Element responseElement, PeerInfoMessenger peerInfoMessenger) { - - RemoteMonitorResponse remoteMonitorResponse; - - try { - remoteMonitorResponse = (RemoteMonitorResponse) DocumentSerializableUtilities.getDocumentSerializable(responseElement, RemoteMonitorResponse.class); - RequestInfo requestInfo = requestInfos.get(new Integer(queryId)); - - if (requestInfo != null) { - requestInfo.responseReceived = true; - - resetTimeout(requestInfo); - if (remoteMonitorResponse.isMonitorRegistered()) { - int leaseId = remoteMonitorResponse.getLeaseId(); - long leaseLength = remoteMonitorResponse.getLease(); - - requestInfo.leaseId = leaseId; - scheduleLeaseRenewal(requestInfo, leaseLength); - - } else if (remoteMonitorResponse.isMonitorRemoved()) { - requestInfos.remove(new Integer(requestInfo.origRequestId)); - requestInfos.remove(new Integer(queryId)); - - } else if (remoteMonitorResponse.isCumulativeReport() || remoteMonitorResponse.isMonitorReport()) { - MonitorReport monitorReport = remoteMonitorResponse.getMonitorReport(); - MonitorEvent monitorEvent = MonitorEvent.createRemoteMonitorReportEvent(requestInfo.peerId, requestInfo.queryId, monitorReport); - requestInfo.monitorListener.processMonitorReport(monitorEvent); - } else if (remoteMonitorResponse.isInvalidFilter()) { - MonitorEvent monitorEvent = MonitorEvent.createFailureEvent(MonitorEvent.INVALID_MONITOR_FILTER, requestInfo.peerId, requestInfo.queryId); - requestInfo.monitorListener.monitorRequestFailed(monitorEvent); - requestInfos.remove(new Integer(queryId)); - } else if (remoteMonitorResponse.isInvalidReportRate()) { - MonitorEvent monitorEvent = MonitorEvent.createFailureEvent(MonitorEvent.INVALID_REPORT_RATE, requestInfo.peerId, requestInfo.queryId); - requestInfo.monitorListener.monitorRequestFailed(monitorEvent); - requestInfos.remove(new Integer(queryId)); - } else if (remoteMonitorResponse.isMeteringNotSupported()) { - MonitorEvent monitorEvent = MonitorEvent.createFailureEvent(MonitorEvent.REFUSED, requestInfo.peerId, requestInfo.queryId); - requestInfo.monitorListener.monitorRequestFailed(monitorEvent); - requestInfos.remove(new Integer(queryId)); - } else if (remoteMonitorResponse.isRequestDenied()) { - MonitorEvent monitorEvent = MonitorEvent.createFailureEvent(MonitorEvent.REFUSED, requestInfo.peerId, requestInfo.queryId); - requestInfo.monitorListener.monitorRequestFailed(monitorEvent); - } else if (remoteMonitorResponse.isPeerMonitorInfo()) { - PeerMonitorInfoEvent peerMonitorInfoEvent = new PeerMonitorInfoEvent(requestInfo.peerId, remoteMonitorResponse.getPeerMonitorInfo()); - requestInfo.peerMonitorInfoListener.peerMonitorInfoReceived(peerMonitorInfoEvent); - requestInfos.remove(new Integer(queryId)); - } else if (remoteMonitorResponse.isLeaseRenewed()) { - long lease = remoteMonitorResponse.getLease(); - int origRequestId = requestInfo.origRequestId; - RequestInfo origRequest = requestInfos.get(new Integer(origRequestId)); - scheduleLeaseRenewal(origRequest, lease); - requestInfos.remove(new Integer(queryId)); - } - } - } catch (DocumentSerializationException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Document Serialization Failed", e); - } - } - } - - private void resetTimeout(RequestInfo requestInfo) { - timeouts.put(requestInfo.queryId, requestInfo.timeout + System.currentTimeMillis()); - } - - private long getTimeout(int queryId) { - return timeouts.get(queryId); - } - - private void scheduleTimeout(final RequestInfo requestInfo) { - final int queryId = requestInfo.queryId; - - timer.schedule( - new TimerTask() { - @Override - public void run() { - if (requestInfos.containsKey(new Integer(queryId))) { - try { - if (System.currentTimeMillis() > getTimeout(queryId)) { - MonitorEvent monitorEvent = MonitorEvent.createFailureEvent(MonitorEvent.TIMEOUT, requestInfo.peerId, queryId); - requestInfo.monitorListener.monitorRequestFailed(monitorEvent); - } - } catch (Exception e) { - //ignored - } - } else { - cancel(); - } - } - }, requestInfo.timeout, requestInfo.timeout); - } - - private void scheduleLeaseRenewal(RequestInfo requestInfo, long leaseLength) { - long roundTrip = requestInfo.requestTime - System.currentTimeMillis(); - long renewTime = leaseLength - roundTrip - 30 * 1000L; // 30s comfort - // zone. - final int queryId = requestInfo.queryId; - - if (renewTime > MIN_LEASE) { - timer.schedule(new TimerTask() { - - @Override - public void run() { - try { - renewLease(queryId); - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Lease Renewal Failed", e); - } - } - } - }, renewTime); - } - } - - private void handleRegisterMonitorQuery(final int queryId, final PeerID requestSourceID, RemoteMonitorQuery remoteMonitorQuery, final PeerInfoMessenger peerInfoMessenger) { - MonitorFilter monitorFilter = remoteMonitorQuery.getMonitorFilter(); - long lease = remoteMonitorQuery.getLease(); - long reportRate = remoteMonitorQuery.getReportRate(); - boolean includeCumulative = remoteMonitorQuery.isIncludeCumulative(); - - MonitorListener monitorListener = new MonitorListener() { - - public void processMonitorReport(MonitorEvent monitorEvent) { - MonitorReport monitorReport = monitorEvent.getMonitorReport(); - try { - RemoteMonitorResponse remoteMonitorResponse = RemoteMonitorResponse.createMonitorReportResponse(queryId, monitorReport); - peerInfoMessenger.sendPeerInfoResponse(queryId, requestSourceID, MONITOR_HANDLER_NAME, remoteMonitorResponse); - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(e.toString()); - } - } - } - - public void monitorReportingCancelled(MonitorEvent monitorEvent) { - throw new RuntimeException("METHOD NOT IMPLEMENTED"); - } - - public void monitorRequestFailed(MonitorEvent monitorEvent) { - throw new RuntimeException("METHOD NOT IMPLEMENTED"); - } - }; - - int leaseId = getNextLeaseId(); - final LeaseInfo leaseInfo = new LeaseInfo(leaseId, requestSourceID, queryId, monitorListener, lease, peerInfoMessenger); - long leaseTime = getLeaseTime(lease); - - setupLeaseTimeout(leaseInfo.leaseId, leaseTime); - - try { - /* - * Currently we can neither ask peers in the netgroup for transport - * metrics, nor discover peers in the world group. Therefore we're - * asking peers in the netgroup to send TransportMetrics, but that - * peer is actually attaching the MonitorFilter to it's WorldGroup - * peer. - */ - for (Iterator i = monitorFilter.getServiceMonitorFilters(); i.hasNext();) { - ServiceMonitorFilter serviceMonitorFilter = (ServiceMonitorFilter) i.next(); - - if (serviceMonitorFilter.getModuleClassID().equals(MonitorResources.transportServiceMonitorClassID)) { - try { - MonitorFilter worldGroupFilter = new MonitorFilter("worldGroupFilter"); - - worldGroupFilter.addServiceMonitorFilter(serviceMonitorFilter); - i.remove(); - PeerGroup worldGroup = peerGroup.newGroup(PeerGroupID.worldPeerGroupID); - PeerInfoService worldService = worldGroup.getPeerInfoService(); - - worldService.addMonitorListener(worldGroupFilter, remoteMonitorQuery.getReportRate(), includeCumulative, - monitorListener); - leaseInfo.listenerAddedToWorldGroup = true; - leaseInfo.worldGroup = worldGroup; - } catch (PeerGroupException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(e.toString()); - } - } - } - } - if (monitorFilter.getServiceMonitorFilterCount() > 0) { - peerInfoServiceImpl.addMonitorListener(monitorFilter, reportRate, includeCumulative, monitorListener); - } - leaseInfos.put(leaseId, leaseInfo); - RemoteMonitorResponse remoteMonitorResponse = RemoteMonitorResponse.createMonitorRegisteredResponse(queryId, leaseId, leaseTime); - peerInfoMessenger.sendPeerInfoResponse(queryId, requestSourceID, MONITOR_HANDLER_NAME, remoteMonitorResponse); - } catch (MonitorFilterException e) { - RemoteMonitorResponse remoteMonitorResponse = RemoteMonitorResponse.createInvalidFilterResponse(queryId); - - peerInfoMessenger.sendPeerInfoResponse(queryId, requestSourceID, MONITOR_HANDLER_NAME, remoteMonitorResponse); - } catch (MonitorException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(e.toString()); - } - } - } - - private void handleRemoveMonitorQuery(int queryId, PeerID requestSourceID, RemoteMonitorQuery remoteMonitorQuery, PeerInfoMessenger peerInfoMessenger) { - try { - int leaseId = remoteMonitorQuery.getLeaseId(); - LeaseInfo leaseInfo = leaseInfos.get(new Integer(leaseId)); - - if (leaseInfo != null) { - MonitorListener monitorListener = leaseInfo.monitorListener; - - peerInfoServiceImpl.removeMonitorListener(monitorListener); - if (leaseInfo.listenerAddedToWorldGroup) { - PeerInfoService peerInfoService = leaseInfo.worldGroup.getPeerInfoService(); - peerInfoService.removeMonitorListener(monitorListener); - } - - RemoteMonitorResponse remoteMonitorResponse = RemoteMonitorResponse.createMonitorRemovedResponse(queryId); - peerInfoMessenger.sendPeerInfoResponse(queryId, requestSourceID, MONITOR_HANDLER_NAME, remoteMonitorResponse); - } - } catch (MonitorException e) { - // Currently not thrown by MonitorManager.removeMonitorListener() - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(e.toString()); - } - } - } - - private void handleCumulativeReportQuery(int queryId, PeerID requestSourceID, MonitorFilter monitorFilter, PeerInfoMessenger peerInfoMessenger) throws MonitorException, DocumentSerializationException { - MonitorReport monitorReport = peerInfoServiceImpl.getCumulativeMonitorReport(monitorFilter); - RemoteMonitorResponse remoteMonitorResponse = RemoteMonitorResponse.createCumulativeReportResponse(queryId, monitorReport); - peerInfoMessenger.sendPeerInfoResponse(queryId, requestSourceID, MONITOR_HANDLER_NAME, remoteMonitorResponse); - } - - private void handlePeerMonitorInfoQuery(int queryId, PeerID requestSourceID, PeerInfoMessenger peerInfoMessenger) throws DocumentSerializationException { - // FIX-ME: - /* Asking the NetGroup Peer won't tell me if it supports transport - * monitoring or not, but asking the world group guy gives me - * everything I need because as currently implemented you can't turn - * monitoring on or off at the PeerGroup level, only the device level. - */ - try { - PeerGroup worldGroup = peerGroup.newGroup(PeerGroupID.worldPeerGroupID); - PeerInfoService worldService = worldGroup.getPeerInfoService(); - - PeerMonitorInfo peerMonitorInfo = worldService.getPeerMonitorInfo(); - RemoteMonitorResponse remoteMonitorResponse = RemoteMonitorResponse.createPeerMonitorInfoResponse(queryId, peerMonitorInfo); - peerInfoMessenger.sendPeerInfoResponse(queryId, requestSourceID, MONITOR_HANDLER_NAME, remoteMonitorResponse); - } catch (PeerGroupException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(e.toString()); - } - } - } - - private void handleLeaseRenewalQuery(int queryId, PeerID requestSourceID, RemoteMonitorQuery remoteMonitorQuery, PeerInfoMessenger peerInfoMessenger) throws DocumentSerializationException { - int leaseId = remoteMonitorQuery.getLeaseId(); - LeaseInfo leaseInfo = leaseInfos.get(new Integer(leaseId)); - - if (leaseInfo != null) { - long reqLease = remoteMonitorQuery.getLease(); - long lease = getLeaseTime(reqLease); - - leaseInfo.validUntil = System.currentTimeMillis() + lease; - setupLeaseTimeout(leaseInfo.leaseId, lease); - - RemoteMonitorResponse remoteMonitorResponse = RemoteMonitorResponse.createLeaseRenewedResponse(queryId, leaseInfo.leaseId, lease); - peerInfoMessenger.sendPeerInfoResponse(queryId, requestSourceID, MONITOR_HANDLER_NAME, remoteMonitorResponse); - } else { - RemoteMonitorResponse remoteMonitorResponse = RemoteMonitorResponse.createDeniedResponse(queryId); - peerInfoMessenger.sendPeerInfoResponse(queryId, requestSourceID, MONITOR_HANDLER_NAME, remoteMonitorResponse); - } - } - - long getLeaseTime(long requestedLease) { - long leaseTime = requestedLease < MAX_LEASE ? requestedLease : MAX_LEASE; - - leaseTime = leaseTime > MIN_LEASE ? leaseTime : MIN_LEASE; - return leaseTime; - } - - private void cancelLease(LeaseInfo leaseInfo) throws MonitorException, DocumentSerializationException { - if (leaseInfo.listenerAddedToWorldGroup) { - leaseInfo.worldGroup.getPeerInfoService().removeMonitorListener(leaseInfo.monitorListener); - } - - RemoteMonitorResponse remoteMonitorResponse = RemoteMonitorResponse.createLeaseEndedResponse(leaseInfo.queryId, leaseInfo.leaseId); - leaseInfo.peerInfoMessenger.sendPeerInfoResponse(leaseInfo.queryId, leaseInfo.peerID, MONITOR_HANDLER_NAME, remoteMonitorResponse); - } - - private void renewLease(int queryId) { - try { - RequestInfo requestInfo = requestInfos.get(new Integer(queryId)); - - if (requestInfo != null) { - int renewalQueryId = peerInfoServiceImpl.getNextQueryId(); - PeerID peerID = requestInfo.peerId; - long timeout = requestInfo.timeout; - - RemoteMonitorQuery remoteMonitorQuery = RemoteMonitorQuery.createLeaseRenewalQuery(requestInfo.leaseId, requestInfo.requestedLease); - - requestInfo.peerInfoMessenger.sendPeerInfoRequest(queryId, peerID, MONITOR_HANDLER_NAME, remoteMonitorQuery); - final RequestInfo renewalRequestInfo = new RequestInfo(peerID, queryId, timeout, requestInfo.peerInfoMessenger); - - renewalRequestInfo.requestedLease = requestInfo.requestedLease; - renewalRequestInfo.origRequestId = queryId; - requestInfos.put(renewalQueryId, renewalRequestInfo); - } - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "error while attempting Monitor lease renewal", e); - } - } - } - - private void setupLeaseTimeout(final int leaseId, long lease) { - - timer.schedule(new TimerTask() { - - @Override - public void run() { - LeaseInfo leaseInfo = leaseInfos.get(new Integer(leaseId)); - - if (leaseInfo != null) { - long currentTime = System.currentTimeMillis(); - - if (leaseInfo.validUntil <= currentTime) { - try { - cancelLease(leaseInfo); - } catch (Exception e) { - // ignored - } finally { - leaseInfos.remove(leaseInfo.queryId); - } - } - } - } - }, lease); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/RemoteMonitorQuery.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/RemoteMonitorQuery.java deleted file mode 100644 index dad252ec..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/RemoteMonitorQuery.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.peer; - - -import net.jxta.document.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.meter.*; - -import java.util.*; - - -public class RemoteMonitorQuery implements DocumentSerializable { - - public static final String CUMULATIVE_REPORT_REQUEST = "cumulativeReport"; - public static final String REGISTER_MONITOR_REQUEST = "registerMonitor"; - public static final String REMOVE_MONITOR_REQUEST = "removeMonitor"; - public static final String VALIDATE_FILTER_REQUEST = "validateFilter"; - public static final String VALIDATE_CUMULATIVE_FILTER_REQUEST = "validateCumulativeFilter"; - public static final String GET_MONITORING_CAPABILITIES_REQUEST = "remoteMonitoringCapabilities"; - public static final String PEER_MONITOR_INFO = "peerMonitorInfo"; - public static final String RENEW_LEASE = "renewLease"; - - private String requestType; - private MonitorFilter monitorFilter; - private boolean includeCumulative; - private long reportRate = -1; - private long lease = -1; - private int leaseId; - - public RemoteMonitorQuery() {} // for serialization code. - - private RemoteMonitorQuery(String requestType) { - this.requestType = requestType; - } - - public MonitorFilter getMonitorFilter() { - return monitorFilter; - } - - private String getRequestType() { - return requestType; - } - - public long getReportRate() { - return reportRate; - } - - public long getLease() { - return lease; - } - - public int getLeaseId() { - return leaseId; - } - - public boolean isIncludeCumulative() { - return includeCumulative; - } - - boolean isCumulativeReportQuery() { - return requestType.equals(CUMULATIVE_REPORT_REQUEST); - } - - boolean isRegisterMonitorQuery() { - return requestType.equals(REGISTER_MONITOR_REQUEST); - } - - boolean isRemoveMonitorQuery() { - return requestType.equals(REMOVE_MONITOR_REQUEST); - } - - boolean isValidateFilterRequest() { - return requestType.equals(VALIDATE_FILTER_REQUEST); - } - - boolean isValidateCumulativeFilterRequest() { - return requestType.equals(VALIDATE_CUMULATIVE_FILTER_REQUEST); - } - - boolean isPeerMonitorInfoQuery() { - return requestType.equals(PEER_MONITOR_INFO); - } - - boolean isLeaseRenewal() { - return requestType.equals(RENEW_LEASE); - } - - static RemoteMonitorQuery createGetCumulativeReportQuery(MonitorFilter monitorFilter) { - RemoteMonitorQuery remoteMonitorQuery = new RemoteMonitorQuery(CUMULATIVE_REPORT_REQUEST); - - remoteMonitorQuery.monitorFilter = monitorFilter; - return remoteMonitorQuery; - } - - static RemoteMonitorQuery createRegisterMonitorQuery(boolean includeCumulative, MonitorFilter monitorFilter, long reportRate, long lease) { - RemoteMonitorQuery remoteMonitorQuery = new RemoteMonitorQuery(REGISTER_MONITOR_REQUEST); - - remoteMonitorQuery.monitorFilter = monitorFilter; - remoteMonitorQuery.reportRate = reportRate; - remoteMonitorQuery.lease = lease; - remoteMonitorQuery.includeCumulative = includeCumulative; - return remoteMonitorQuery; - } - - static RemoteMonitorQuery createRemoveMonitorListenerQuery(int leaseId) { - RemoteMonitorQuery remoteMonitorQuery = new RemoteMonitorQuery(REMOVE_MONITOR_REQUEST); - - remoteMonitorQuery.leaseId = leaseId; - return remoteMonitorQuery; - } - - static RemoteMonitorQuery createPeerMonitorInfoQuery() { - RemoteMonitorQuery remoteMonitorQuery = new RemoteMonitorQuery(PEER_MONITOR_INFO); - - return remoteMonitorQuery; - } - - static RemoteMonitorQuery createLeaseRenewalQuery(int leaseId, long requestedLease) { - RemoteMonitorQuery remoteMonitorQuery = new RemoteMonitorQuery(RENEW_LEASE); - - remoteMonitorQuery.leaseId = leaseId; - remoteMonitorQuery.lease = requestedLease; - return remoteMonitorQuery; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - DocumentSerializableUtilities.addString(element, "requestType", requestType); - - if (monitorFilter != null) { - DocumentSerializableUtilities.addDocumentSerializable(element, "monitorFilter", monitorFilter); - } - - if (lease > 0) { - DocumentSerializableUtilities.addLong(element, "lease", lease); - } - - if (leaseId > -1) { - DocumentSerializableUtilities.addInt(element, "leaseId", leaseId); - } - - if (reportRate > 0) { - DocumentSerializableUtilities.addLong(element, "reportRate", reportRate); - } - - if (includeCumulative) { - DocumentSerializableUtilities.addBoolean(element, "includeCumulative", includeCumulative); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("requestType")) { - requestType = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("monitorFilter")) { - monitorFilter = (MonitorFilter) DocumentSerializableUtilities.getDocumentSerializable(childElement - , - MonitorFilter.class); - } else if (tagName.equals("lease")) { - lease = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("leaseId")) { - leaseId = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("reportRate")) { - reportRate = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("includeCumulative")) { - includeCumulative = DocumentSerializableUtilities.getBoolean(childElement); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/RemoteMonitorResponse.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/RemoteMonitorResponse.java deleted file mode 100644 index a1ebefe4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/RemoteMonitorResponse.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.peer; - - -import net.jxta.document.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.meter.*; -import java.util.*; - - -public class RemoteMonitorResponse implements DocumentSerializable { - public static final String MONITOR_REGISTERED = "monitorRegistered"; - public static final String MONITOR_REMOVED = "monitorGone"; - public static final String CUMULATIVE_REPORT_RESPONSE = "cumulativeReport"; - public static final String MONITOR_REPORT_RESPONSE = "monitorReport"; - public static final String INVALID_FILTER = "invalidFilter"; - public static final String INVALID_REPORT_RATE = "invalidReportRate"; - public static final String VALID_FILTER = "validFilter"; - public static final String SERVICE_NOT_SUPPORTED = "serviceNotSupported"; - public static final String METERING_NOT_SUPPORTED = "metereringNotSupported"; - public static final String METERING_SUPPORTED = "meteringSupported"; - public static final String METERING_REQUEST_DENIED = "meteringRequestDenied"; - public static final String PEER_MONITOR_INFO = "peerMonitorInfo"; - public static final String LEASE_ENDED = "leaseOver"; - public static final String LEASE_RENEWED = "leaseRenewed"; - - /* - ResponseCode: Not Supported - ResponseCode: Invalid Reporting Rate - Suggested Reporting Rate - ResponseCode: Invalid Filter - Suggested Filter - */ - - private String responseType; - private int requestId; - private int leaseId; - private MonitorReport monitorReport; - private boolean isCumulative; - private MonitorFilter monitorFilter; - private long lease = -1; - private PeerMonitorInfo peerMonitorInfo; - - private long reportRates[]; - private LinkedList supportedModuleClassIDs; - - public RemoteMonitorResponse() {} // for serialization. - - private RemoteMonitorResponse(String responseType, int requestId) { - this.responseType = responseType; - this.requestId = requestId; - } - - public long getLease() { - return lease; - } - - public boolean isCumulative() { - return isCumulative; - } - - public String getResponseType() { - return responseType; - } - - public int getRequestId() { - return requestId; - } - - public int getLeaseId() { - return leaseId; - } - - public MonitorReport getMonitorReport() { - return monitorReport; - } - - public MonitorFilter getMonitorFilter() { - return monitorFilter; - } - - public PeerMonitorInfo getPeerMonitorInfo() { - return peerMonitorInfo; - } - - public boolean isMonitorRegistered() { - return responseType.equals(MONITOR_REGISTERED); - } - - public boolean isMonitorRemoved() { - return responseType.equals(MONITOR_REMOVED); - } - - public boolean isCumulativeReport() { - return responseType.equals(CUMULATIVE_REPORT_RESPONSE); - } - - public boolean isMonitorReport() { - return responseType.equals(MONITOR_REPORT_RESPONSE); - } - - public boolean isValidFilter() { - return responseType.equals(VALID_FILTER); - } - - public boolean isInvalidFilter() { - return responseType.equals(INVALID_FILTER); - } - - public boolean isInvalidReportRate() { - return responseType.equals(INVALID_REPORT_RATE); - } - - public boolean isServiceNotSupported() { - return responseType.equals(SERVICE_NOT_SUPPORTED); - } - - public boolean isMeteringNotSupported() { - return responseType.equals(METERING_NOT_SUPPORTED); - } - - public boolean isMeteringSupported() { - return responseType.equals(METERING_SUPPORTED); - } - - public boolean isRequestDenied() { - return responseType.equals(METERING_REQUEST_DENIED); - } - - public boolean isPeerMonitorInfo() { - return responseType.equals(PEER_MONITOR_INFO); - } - - public boolean isLeaseRenewed() { - return responseType.equals(LEASE_RENEWED); - } - - public static RemoteMonitorResponse createMonitorRegisteredResponse(int requestId, int leaseId, long lease) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(MONITOR_REGISTERED, requestId); - - remoteMonitorResponse.leaseId = leaseId; - remoteMonitorResponse.lease = lease; - return remoteMonitorResponse; - } - - public static RemoteMonitorResponse createMonitorRemovedResponse(int requestId) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(MONITOR_REMOVED, requestId); - - return remoteMonitorResponse; - } - - public static RemoteMonitorResponse createLeaseEndedResponse(int requestId, int leaseId) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(LEASE_ENDED, requestId); - - remoteMonitorResponse.leaseId = leaseId; - return remoteMonitorResponse; - } - - public static RemoteMonitorResponse createCumulativeReportResponse(int requestId, MonitorReport monitorReport) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(CUMULATIVE_REPORT_RESPONSE, requestId); - - remoteMonitorResponse.monitorReport = monitorReport; - remoteMonitorResponse.isCumulative = true; - return remoteMonitorResponse; - } - - public static RemoteMonitorResponse createMonitorReportResponse(int requestId, MonitorReport monitorReport) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(MONITOR_REPORT_RESPONSE, requestId); - - remoteMonitorResponse.monitorReport = monitorReport; - remoteMonitorResponse.isCumulative = false; - return remoteMonitorResponse; - } - - public static RemoteMonitorResponse createInvalidReportRateResponse(int requestId) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(INVALID_REPORT_RATE, requestId); - - return remoteMonitorResponse; - } - - public static RemoteMonitorResponse createServiceNotSupportedResponse(int requestId) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(SERVICE_NOT_SUPPORTED, requestId); - - return remoteMonitorResponse; - } - - public static RemoteMonitorResponse createInvalidFilterResponse(int requestId) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(INVALID_FILTER, requestId); - - return remoteMonitorResponse; - } - - /* - public static RemoteMonitorResponse createValidFilterResponse(int requestId) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(VALID_FILTER, requestId); - return remoteMonitorResponse; - } - */ - public static RemoteMonitorResponse createDeniedResponse(int requestId) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(METERING_REQUEST_DENIED, requestId); - - return remoteMonitorResponse; - } - - public static RemoteMonitorResponse createPeerMonitorInfoResponse(int requestId, PeerMonitorInfo peerMonitorInfo) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(PEER_MONITOR_INFO, requestId); - - remoteMonitorResponse.peerMonitorInfo = peerMonitorInfo; - return remoteMonitorResponse; - } - - public static RemoteMonitorResponse createLeaseRenewedResponse(int requestId, int leaseId, long lease) { - RemoteMonitorResponse remoteMonitorResponse = new RemoteMonitorResponse(LEASE_RENEWED, requestId); - - remoteMonitorResponse.leaseId = leaseId; - remoteMonitorResponse.lease = lease; - return remoteMonitorResponse; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - DocumentSerializableUtilities.addString(element, "responseType", responseType); - DocumentSerializableUtilities.addInt(element, "requestId", requestId); - - if (monitorReport != null) { - DocumentSerializableUtilities.addDocumentSerializable(element, "monitorReport", monitorReport); - } - - if (monitorFilter != null) { - DocumentSerializableUtilities.addDocumentSerializable(element, "monitorFilter", monitorFilter); - } - - if (lease > 0) { - DocumentSerializableUtilities.addLong(element, "lease", lease); - } - - if (leaseId > -1) { - DocumentSerializableUtilities.addInt(element, "leaseId", leaseId); - } - - if (isCumulative) { - DocumentSerializableUtilities.addBoolean(element, "isCumulative", isCumulative); - } - - if (peerMonitorInfo != null) { - DocumentSerializableUtilities.addDocumentSerializable(element, "peerMonitorInfo", peerMonitorInfo); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("responseType")) { - responseType = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("requestId")) { - requestId = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("monitorReport")) { - monitorReport = (MonitorReport) DocumentSerializableUtilities.getDocumentSerializable(childElement - , - MonitorReport.class); - } else if (tagName.equals("monitorFilter")) { - monitorFilter = (MonitorFilter) DocumentSerializableUtilities.getDocumentSerializable(childElement - , - MonitorFilter.class); - } else if (tagName.equals("lease")) { - lease = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("leaseId")) { - leaseId = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("isCumulative")) { - isCumulative = DocumentSerializableUtilities.getBoolean(childElement); - } else if (tagName.equals("peerMonitorInfo")) { - peerMonitorInfo = (PeerMonitorInfo) DocumentSerializableUtilities.getDocumentSerializable(childElement - , - PeerMonitorInfo.class); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/package.html deleted file mode 100644 index 91b9a708..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peer/package.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - Provides definition for the standard JXTA Peer Info Service. - - @see JXTA Protocols Specification : Peer Info Protocol - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/AutomaticConfigurator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/AutomaticConfigurator.java deleted file mode 100644 index 9f6dee07..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/AutomaticConfigurator.java +++ /dev/null @@ -1,511 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.peergroup; - - -import java.net.InetAddress; -import java.net.URI; -import java.util.Enumeration; -import java.util.Iterator; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.TransportAdvertisement; - -import net.jxta.exception.ConfiguratorException; - -import net.jxta.impl.endpoint.IPUtils; -import net.jxta.impl.protocol.HTTPAdv; -import net.jxta.impl.protocol.PlatformConfig; -import net.jxta.impl.protocol.PSEConfigAdv; -import net.jxta.impl.protocol.RdvConfigAdv; -import net.jxta.impl.protocol.RelayConfigAdv; -import net.jxta.impl.protocol.TCPAdv; - - -/** - * A simple platform configurator. This implementation provides reasonable - * automatic configuration for edge peers on the JXTA public network. - *

            - * This implementation will read default values from several Java system - * properties as appropriate: - *

            - * jxta.peer.name -- The peer name to use. - * jxta.http.port -- The http port to use. - * jxta.tcp.port -- The tcp port to use. - * - * @see net.jxta.peergroup.Configurator - */ -public class AutomaticConfigurator extends NullConfigurator { - - /** - * Log4J logger - */ - private final static transient Logger LOG = Logger.getLogger(AutomaticConfigurator.class.getName()); - - /** - * Configures the platform using the specified directory. - * @param jxtaHome store home URI - * @throws net.jxta.exception.ConfiguratorException if a configuration error occurs - */ - public AutomaticConfigurator(URI jxtaHome) throws ConfiguratorException { - super(jxtaHome); - } - - /** - * {@inheritDoc} - */ - @Override - public PlatformConfig getPlatformConfig() throws ConfiguratorException { - super.getPlatformConfig(); - - boolean reconf; - - try { - reconf = buildPlatformConfig(); - } catch (RuntimeException serious) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Trouble while fixing PlatformConfig. Hope for the best.", serious); - } - - reconf = true; - } - - // See if we need a reconf - if (reconf) { - throw new IncompleteConfigurationException("Damaged platform configuration."); - } - - // Save the updated config. - save(); - - return advertisement; - } - - /** - * Makes sure a PlatformConfig is present and if not, creates one. - *

            - * Performs some checking of PlatformConfig values and will fix some - * minor configuration problems automatically. - * - * @return If true then manual reconfiguration (of some form) is required. - */ - private boolean buildPlatformConfig() { - - boolean reconf = false; - - if (advertisement == null) { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("New PlatformConfig Advertisement"); - } - advertisement = (PlatformConfig) AdvertisementFactory.newAdvertisement(PlatformConfig.getAdvertisementType()); - advertisement.setDescription("Platform Config Advertisement created by : " + AutomaticConfigurator.class.getName()); - } - - // Set the peer name - String peerName = advertisement.getName(); - - if ((null == peerName) || (0 == peerName.trim().length())) { - String jpn = System.getProperty("jxta.peer.name", ""); - - if (0 != jpn.trim().length()) { - advertisement.setName(jpn); - } - } - - // Check the HTTP Message Transport parameters. - XMLDocument http = (XMLDocument) advertisement.getServiceParam(PeerGroup.httpProtoClassID); - HTTPAdv httpAdv = null; - boolean httpEnabled = true; - - if (http != null) { - try { - httpEnabled = advertisement.isSvcEnabled(PeerGroup.httpProtoClassID); - - XMLElement param = null; - - Enumeration httpChilds = http.getChildren(TransportAdvertisement.getAdvertisementType()); - - // get the HTTPAdv from TransportAdv - if (httpChilds.hasMoreElements()) { - param = (XMLElement) httpChilds.nextElement(); - } - - if (null != param) { - httpAdv = (HTTPAdv) AdvertisementFactory.newAdvertisement(param); - - if (httpEnabled) { - // check if the interface address is still valid. - String intf = httpAdv.getInterfaceAddress(); - - if ((null != intf) && !isValidInetAddress(intf)) { - reconf = true; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Reconfig requested - invalid interface address"); - } - } - } - } - } catch (RuntimeException advTrouble) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "HTTP advertisement corrupted", advTrouble); - } - - httpAdv = null; - } - } - - if (httpAdv == null) { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("HTTP advertisement missing, making a new one."); - } - - int port = 0; - // get the port from a property - String httpPort = System.getProperty("jxta.http.port"); - - if (httpPort != null) { - try { - int propertyPort = Integer.parseInt(httpPort); - - if ((propertyPort < 65536) && (propertyPort >= 0)) { - port = propertyPort; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Property \'jxta.http.port\' is not a valid port number : " + propertyPort); - } - } - } catch (NumberFormatException ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Property \'jxta.http.port\' was not an integer : " + http); - } - } - } - - httpAdv = (HTTPAdv) AdvertisementFactory.newAdvertisement(HTTPAdv.getAdvertisementType()); - httpAdv.setProtocol("http"); - httpAdv.setPort(port); - httpAdv.setServerEnabled(false); - } - - // Create new param docs that contain the updated adv - http = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - XMLDocument httAdvDoc = (XMLDocument) httpAdv.getDocument(MimeMediaType.XMLUTF8); - - StructuredDocumentUtils.copyElements(http, http, httAdvDoc); - if (!httpEnabled) { - http.appendChild(http.createElement("isOff")); - } - advertisement.putServiceParam(PeerGroup.httpProtoClassID, http); - - // Check the TCP Message Transport parameters. - XMLDocument tcp = (XMLDocument) advertisement.getServiceParam(PeerGroup.tcpProtoClassID); - TCPAdv tcpAdv = null; - boolean tcpEnabled = true; - - if (tcp != null) { - try { - tcpEnabled = advertisement.isSvcEnabled(PeerGroup.tcpProtoClassID); - - XMLElement param = null; - - Enumeration tcpChilds = tcp.getChildren(TransportAdvertisement.getAdvertisementType()); - - // get the TransportAdv - if (tcpChilds.hasMoreElements()) { - param = (XMLElement) tcpChilds.nextElement(); - } - - if (null != param) { - tcpAdv = (TCPAdv) AdvertisementFactory.newAdvertisement(param); - - if (tcpEnabled) { - String intf = tcpAdv.getInterfaceAddress(); - - if ((null != intf) && !isValidInetAddress(intf)) { - reconf = true; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Reconfig requested - invalid interface address"); - } - } - } - } - } catch (RuntimeException advTrouble) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "TCP advertisement corrupted", advTrouble); - } - - tcpAdv = null; - } - } - - if (tcpAdv == null) { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("TCP advertisement missing, making a new one."); - } - - int port = 0; - // get the port from a property - String tcpPort = System.getProperty("jxta.tcp.port"); - - if (tcpPort != null) { - try { - int propertyPort = Integer.parseInt(tcpPort); - - if ((propertyPort < 65536) && (propertyPort >= 0)) { - port = propertyPort; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Property \'jxta.tcp.port\' is not a valid port number : " + propertyPort); - } - } - } catch (NumberFormatException ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Property \'jxta.tcp.port\' was not an integer : " + tcpPort); - } - } - } - - tcpAdv = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType()); - - tcpAdv.setProtocol("tcp"); - tcpAdv.setPort(port); - tcpAdv.setMulticastAddr("224.0.1.85"); - tcpAdv.setMulticastPort(1234); - tcpAdv.setMulticastSize(16384); - tcpAdv.setMulticastState(true); - } - - tcp = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - - StructuredDocumentUtils.copyElements(tcp, tcp, (XMLDocument) tcpAdv.getDocument(MimeMediaType.XMLUTF8)); - if (!tcpEnabled) { - tcp.appendChild(tcp.createElement("isOff")); - } - advertisement.putServiceParam(PeerGroup.tcpProtoClassID, tcp); - - // Check the relay config - RelayConfigAdv relayConfig = null; - - try { - XMLElement param = (XMLElement) advertisement.getServiceParam(PeerGroup.relayProtoClassID); - - if (param != null) { - // XXX 20041027 backwards compatibility - param.addAttribute("type", RelayConfigAdv.getAdvertisementType()); - - relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(param); - } - } catch (Exception failure) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Problem reading relay configuration", failure); - } - } - - if (null == relayConfig) { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Relay Config advertisement missing, making a new one."); - } - - // restore default values. - relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(RelayConfigAdv.getAdvertisementType()); - - // Enable relay if any transport doesn't support incoming. - if (!tcpAdv.isServerEnabled() || !httpAdv.isServerEnabled()) { - relayConfig.setClientEnabled(true); - } - } - - /* - if( (0 == relayConfig.getSeedingURIs().length) && (0 == relayConfig.getSeedRelays().length) && !relayConfig.isServerEnabled() ) { - // add the default relay seeding peer. - relayConfig.addSeedingURI( "http://rdv.jxtahosts.net/cgi-bin/relays.cgi?3" ); - } - */ - - XMLDocument relayDoc = (XMLDocument) relayConfig.getDocument(MimeMediaType.XMLUTF8); - - advertisement.putServiceParam(PeerGroup.relayProtoClassID, relayDoc); - - // Check Rendezvous Configuration - RdvConfigAdv rdvAdv = null; - - try { - XMLElement param = (XMLElement) advertisement.getServiceParam(PeerGroup.rendezvousClassID); - - if (param != null) { - // XXX 20041027 backwards compatibility - param.addAttribute("type", RdvConfigAdv.getAdvertisementType()); - - rdvAdv = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(param); - } - } catch (Exception failure) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Problem reading rendezvous configuration", failure); - } - } - - if (null == rdvAdv) { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Rdv Config advertisement missing, making a new one."); - } - - // restore default values. - rdvAdv = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType()); - } - - /* - if( (0 == rdvAdv.getSeedingURIs().length) && - (0 == rdvAdv.getSeedRendezvous().length) && - (RdvConfigAdv.RendezVousConfiguration.RENDEZVOUS != rdvAdv.getConfiguration()) && - (RdvConfigAdv.RendezVousConfiguration.AD_HOC != rdvAdv.getConfiguration()) && - !relayConfig.isClientEnabled() ) { - // add the default rendezvous seeding peer if we don't know of any rendezvous, aren't a rendezvous ourselves, aren't in ad-hoc mode or using a relay. - rdvAdv.addSeedingURI( "http://rdv.jxtahosts.net/cgi-bin/rendezvous.cgi?3" ); - } - */ - XMLDocument rdvDoc = (XMLDocument) rdvAdv.getDocument(MimeMediaType.XMLUTF8); - - advertisement.putServiceParam(PeerGroup.rendezvousClassID, rdvDoc); - - // if no proxy param section, disable it. - XMLDocument proxy = (XMLDocument) advertisement.getServiceParam(PeerGroup.proxyClassID); - - if (null == proxy) { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Proxy config advertisement missing, making a new one."); - } - - proxy = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - proxy.appendChild(proxy.createElement("isOff")); - advertisement.putServiceParam(PeerGroup.proxyClassID, proxy); - } - - // Check the PSE Configuration - PSEConfigAdv pseConfig = null; - - try { - XMLElement param = (XMLElement) advertisement.getServiceParam(PeerGroup.membershipClassID); - - if (param != null) { - // XXX 20041027 backwards compatibility - param.addAttribute("type", PSEConfigAdv.getAdvertisementType()); - - pseConfig = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(param); - } - } catch (Exception failure) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Problem reading pse configuration", failure); - } - } - - if (null == pseConfig) { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("PSE Config advertisement missing, making a new one."); - } - - // restore default values. - pseConfig = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType()); - XMLDocument pseDoc = (XMLDocument) pseConfig.getDocument(MimeMediaType.XMLUTF8); - - advertisement.putServiceParam(PeerGroup.membershipClassID, pseDoc); - } - - // If we did not modify anything of importance or see anything wrong, - // leave the adv alone. - - return reconf; - } - - private boolean isValidInetAddress(String address) { - boolean found = false; - boolean loopback; - - InetAddress[] ias; - - try { - ias = InetAddress.getAllByName(address); - } catch (java.net.UnknownHostException notfound) { - return false; - } - - for (Iterator la = IPUtils.getAllLocalAddresses(); la.hasNext() && !found;) { - for (InetAddress ia1 : ias) { - found |= ia1.equals(la.next()); - } - } - - loopback = true; - - for (InetAddress ia1 : ias) { - loopback &= ia1.isLoopbackAddress(); - } - - return found || loopback; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/Boot.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/Boot.java deleted file mode 100644 index d8f1fae3..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/Boot.java +++ /dev/null @@ -1,169 +0,0 @@ -/* -Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - - -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.NetworkManager; -import net.jxta.platform.NetworkConfigurator; - -import java.util.logging.Logger; - -import java.io.File; -import java.text.MessageFormat; -import java.util.Collections; - - -/** - * A default "main" for starting JXTA. - * - * @deprecated This code is in no-way dependent upon the implementation and - * should not have been located here. Developers are encouraged to copy this - * source to their own projects. Consider using alternative JXTA "main" - * See NetworkManager tutorial . - */ -@Deprecated -public class Boot { - - /** - * main - * - * @param args command line arguments - */ - public static void main(String args[]) { - // Name the main thread. For unknown reasons it usually has a boring name like "thread1" - Thread.currentThread().setName(Boot.class.getName() + ".main()"); - - try { - boolean server; - // Get the optional location of the directory we should use for cache. - String jxta_home = System.getProperty("JXTA_HOME"); - File home; - String instanceName; - - if (null != jxta_home) { - // Use the location from the older JXTA_HOME system property. - server = false; - instanceName = "BootCustom"; - home = new File(jxta_home); - } else { - // Use the location defined by the newer role convention. - server = args.length > 0 && ("-server".equalsIgnoreCase(args[0])); - - if (server) { - instanceName = "BootServer"; - } else { - instanceName = "BootEdge"; - } - - home = new File(new File(".cache"), instanceName); - } - - // If the home directory doesn't exist, create it. - if (!home.exists()) { - home.mkdirs(); - } - - NetworkManager manager; - - if (server) { - manager = new NetworkManager(NetworkManager.ConfigMode.SUPER, instanceName, home.toURI()); - - /* - NetworkConfigurator config = manager.getConfigurator(); - - //disable http - config.setHttpEnabled(false); - //disable seeding - config.setRelaySeedURIs(Collections.emptyList()); - config.setRendezvousSeedURIs(Collections.emptyList()); - */ - } else { - manager = new NetworkManager(NetworkManager.ConfigMode.EDGE, instanceName, home.toURI()); - } - // register a hook - // manager.registerShutdownHook(); - - System.out.println(MessageFormat.format("Starting the JXTA platform in mode : {0}", manager.getMode())); - long startTime = System.currentTimeMillis(); - - manager.startNetwork(); - System.out.println( - MessageFormat.format("Boot started in {0} millis, in mode : {1}", System.currentTimeMillis() - startTime - , - manager.getMode())); - - PeerGroup netPeerGroup = manager.getNetPeerGroup(); - - netPeerGroup.startApp(null); - - System.out.println(MessageFormat.format("Boot started in mode : {0}", manager.getMode())); - if (server) { - // Put this thread permanently to sleep so that JXTA keeps running. - Thread.sleep(Long.MAX_VALUE); - } - } catch (Throwable e) { - System.out.flush(); - // make sure output buffering doesn't wreck console display. - System.err.println("Uncaught Throwable caught by 'main':"); - e.printStackTrace(System.err); - System.exit(1); - } finally { - System.err.flush(); - System.out.flush(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/CompatibilityEquater.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/CompatibilityEquater.java deleted file mode 100644 index 72a2ac93..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/CompatibilityEquater.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - -import net.jxta.document.Element; - -public interface CompatibilityEquater { - - /** - * Evaluates if the given compatibility statement makes the module that - * bears it is lodable by this group. - * - * @param test the element to test - * @return boolean True if test is compatible with target. - */ - public boolean compatible(Element test); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/ConfigDialog.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/ConfigDialog.java deleted file mode 100644 index 285e3a84..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/ConfigDialog.java +++ /dev/null @@ -1,2022 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - -import java.awt.BorderLayout; -import java.awt.Button; -import java.awt.CardLayout; -import java.awt.Checkbox; -import java.awt.Choice; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Frame; -import java.awt.Graphics; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Insets; -import java.awt.Label; -import java.awt.Panel; -import java.awt.TextField; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.net.InetAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.TransportAdvertisement; - -import net.jxta.exception.JxtaError; -import net.jxta.exception.ConfiguratorException; - -import net.jxta.impl.endpoint.IPUtils; -import net.jxta.impl.membership.pse.PSEUtils; -import net.jxta.impl.protocol.HTTPAdv; -import net.jxta.impl.protocol.PSEConfigAdv; -import net.jxta.impl.protocol.PlatformConfig; -import net.jxta.impl.protocol.RdvConfigAdv; -import net.jxta.impl.protocol.RdvConfigAdv.RendezVousConfiguration; -import net.jxta.impl.protocol.RelayConfigAdv; -import net.jxta.impl.protocol.TCPAdv; - -/** - * The standard and much loved AWT Configuration dialog - */ -@SuppressWarnings("serial") -public class ConfigDialog extends Frame { - - static final GridBagConstraints stdConstr; - static final GridBagConstraints centerConstr; - static final GridBagConstraints centerLastConstr; - static final GridBagConstraints fillConstr; - static final GridBagConstraints fillInsetConstr; - - static { - stdConstr = new GridBagConstraints(); - stdConstr.gridwidth = GridBagConstraints.REMAINDER; - stdConstr.gridheight = 1; - stdConstr.gridx = 0; - stdConstr.gridy = GridBagConstraints.RELATIVE; - stdConstr.fill = GridBagConstraints.NONE; - stdConstr.weightx = 1; - stdConstr.anchor = GridBagConstraints.NORTHWEST; - stdConstr.insets = new Insets(0, 0, 0, 0); - - fillConstr = (GridBagConstraints) stdConstr.clone(); - fillConstr.fill = GridBagConstraints.HORIZONTAL; - - centerConstr = (GridBagConstraints) stdConstr.clone(); - centerConstr.anchor = GridBagConstraints.NORTH; - - centerLastConstr = (GridBagConstraints) centerConstr.clone(); - centerLastConstr.weighty = 1; - - fillInsetConstr = (GridBagConstraints) fillConstr.clone(); - - fillInsetConstr.insets = new Insets(5, 5, 5, 5); - } - - // A few widgets. - - /** - * Grid Bag layout panel - */ - static class PanelGBL extends Panel { - - protected Insets insets = new Insets(0, 0, 0, 0); - - GridBagLayout lay = new GridBagLayout(); - - private static final GridBagConstraints constrLabel = new GridBagConstraints(); - - static { - constrLabel.gridwidth = GridBagConstraints.REMAINDER; - constrLabel.gridheight = 1; - constrLabel.gridy = GridBagConstraints.RELATIVE; - constrLabel.weightx = 1; - constrLabel.weighty = 1; - constrLabel.anchor = GridBagConstraints.FIRST_LINE_START; - constrLabel.fill = GridBagConstraints.HORIZONTAL; - } - - public PanelGBL(String label) { - this(); - add(new Label(label, Label.LEFT), constrLabel); - } - - public PanelGBL() { - super(); - setLayout(lay); - } - - /** - * {@inheritDoc} - */ - @Override - public Insets getInsets() { - return insets; - } - } - - - /** - * A Grid Bag Panel with a border - */ - static class BorderPanelGBL extends PanelGBL { - - public static final int NONE = 0; - public static final int RAISED = 1; - public static final int LOWERED = 2; - public static final int GROOVE = 3; - public static final int BUMP = 4; - - int style = GROOVE; - String title; - int ascent = 0; - int descent = 0; - int leading = 0; - int titleWidth = 0; - - public BorderPanelGBL(String title) { - super(); - this.title = title; - } - - public BorderPanelGBL(String title, String advice) { - super(advice); - this.title = title; - } - - public BorderPanelGBL(String title, String advice, int s) { - super(advice); - this.title = title; - if ((s < NONE) && (s > BUMP)) { - return; - } - if ((s == RAISED) || (s == LOWERED)) { - this.title = null; - } - style = s; - } - - private void checkMetrics() { - Font font = getFont(); - - if ((title == null) || (font == null)) { - ascent = 2; - } else { - FontMetrics fmetrics = getFontMetrics(font); - - ascent = fmetrics.getAscent(); - descent = fmetrics.getDescent(); - leading = fmetrics.getLeading(); - titleWidth = fmetrics.stringWidth(title); - } - insets = new Insets(descent + ascent + leading + 2, 7, 7, 7); - } - - /** - * {@inheritDoc} - */ - @Override - public Insets getInsets() { - checkMetrics(); - return insets; - } - - private void paintLowered(Graphics g) { - checkMetrics(); - if (ascent == 0) { - return; - } - - Dimension d = getSize(); - - g.setColor(Color.black); - g.drawRect(1, ascent - 2, d.width - 4, d.height - ascent); - g.setColor(Color.white); - g.drawRect(2, ascent - 1, d.width - 4, d.height - ascent); - g.setColor(getBackground()); - g.drawRect(2, ascent - 1, d.width - 5, d.height - ascent - 1); - } - - private void paintRaised(Graphics g) { - checkMetrics(); - if (ascent == 0) { - return; - } - - Dimension d = getSize(); - - g.setColor(Color.white); - g.drawRect(1, ascent - 2, d.width - 4, d.height - ascent); - g.setColor(Color.black); - g.drawRect(2, ascent - 1, d.width - 4, d.height - ascent); - g.setColor(getBackground()); - g.drawRect(2, ascent - 1, d.width - 5, d.height - ascent - 1); - } - - private void paintGroove(Graphics g) { - checkMetrics(); - if (ascent == 0) { - return; - } - - Dimension d = getSize(); - - g.setColor(Color.black); - g.drawRect(1, ascent - 2, d.width - 4, d.height - ascent); - g.setColor(Color.white); - g.drawRect(2, ascent - 1, d.width - 4, d.height - ascent); - - g.setColor(Color.white); - g.clearRect(10, 0, titleWidth + 6, descent + ascent + leading + 1); - g.drawString(title, 12, ascent + 1); - g.setColor(Color.black); - g.drawString(title, 13, ascent + 2); - - // Work around a bug of at least the awt implem I'm using. - // A few wild pixels appear on that line during drawstring. - g.clearRect(0, 0, d.width, 1); - } - - private void paintBump(Graphics g) { - checkMetrics(); - if (ascent == 0) { - return; - } - - Dimension d = getSize(); - - g.setColor(Color.white); - g.drawRect(1, ascent - 2, d.width - 4, d.height - ascent); - g.setColor(Color.black); - g.drawRect(2, ascent - 1, d.width - 4, d.height - ascent); - - g.setColor(Color.white); - g.clearRect(10, 0, titleWidth + 6, descent + ascent + leading + 1); - g.drawString(title, 12, ascent + 1); - g.setColor(Color.black); - g.drawString(title, 13, ascent + 2); - - // Work around a bug of at least the awt implem I'm using. - // A few wild pixels appear on that line during drawstring. - g.clearRect(0, 0, d.width, 1); - } - - /** - * {@inheritDoc} - */ - @Override - public void paint(Graphics g) { - switch (style) { - case GROOVE: - paintGroove(g); - break; - - case BUMP: - paintBump(g); - break; - - case RAISED: - paintRaised(g); - break; - - case LOWERED: - paintLowered(g); - break; - - default: - } - super.paint(g); - } - } - - - /** - * Panel implementing paged tabs. - */ - static class PagesPanel extends Panel implements ActionListener { - private final CardLayout layout; - private final Panel pages; - private final Panel buttons; - - public PagesPanel() { - super(new BorderLayout()); - layout = new CardLayout(); - pages = new Panel(layout); - buttons = new Panel(new FlowLayout(FlowLayout.LEFT, 0, 0)); - - add(pages, BorderLayout.CENTER); - add(buttons, BorderLayout.NORTH); - } - - /** - * {@inheritDoc} - */ - public void actionPerformed(ActionEvent e) { - layout.show(pages, e.getActionCommand()); - } - - public PanelGBL addPage(String buttonName, String comment) { - BorderPanelGBL p = new BorderPanelGBL(buttonName, comment, BorderPanelGBL.RAISED); - - pages.add(p, buttonName); - Button b = new Button(buttonName); - - buttons.add(b); - b.addActionListener(this); - return p; - } - - public void showPage(String pageName) { - layout.show(pages, pageName); - } - } - - - /** - * Allows for entry of a host address and port number. Besides the host - * address and port number text fields there are two optional features: - *

            - *

              - *
            • A checkbox with annotation to enable/disable the control.
            • - *
            • A label for the address.
            • - *
            - */ - static class HostPortPanel extends Panel implements ItemListener { - - private final Checkbox useMe; - - private Label addressLabel = null; - - private final TextField host; - private final TextField port; - - HostPortPanel(String checkLabel, String addrLabel, String defaultHost, String defaultPort, boolean defaultState) { - - super(new GridBagLayout()); - - useMe = new Checkbox(checkLabel, defaultState); - host = new TextField(defaultHost, 25); - port = new TextField(defaultPort, 6); - - GridBagConstraints constraints = new GridBagConstraints(); - - constraints.weightx = 1.0; - constraints.weighty = 1.0; - - constraints.gridx = 0; - constraints.gridy = 0; - constraints.gridwidth = (null == addrLabel) ? 2 : 3; - constraints.anchor = GridBagConstraints.FIRST_LINE_START; - - if (null != checkLabel) { - add(useMe, constraints); - // if check label and addr label then use 2 lines. - if (null != addrLabel) { - constraints.gridy++; - constraints.gridx = 0; - constraints.anchor = GridBagConstraints.LAST_LINE_START; - } else { - constraints.gridx++; - constraints.gridx = GridBagConstraints.RELATIVE; - } - } - - if (null != addrLabel) { - constraints.gridwidth = 1; - addressLabel = new Label(addrLabel, Label.RIGHT); - add(addressLabel, constraints); - } - - constraints.gridx = GridBagConstraints.RELATIVE; - - add(host, constraints); - add(port, constraints); - - setState(defaultState); - useMe.addItemListener(this); - } - - /** - * {@inheritDoc} - */ - public void itemStateChanged(ItemEvent e) { - setState(useMe.getState()); - } - - /** - * {@inheritDoc} - */ - public boolean getState() { - return useMe.getState() && isEnabled(); - } - - /** - * {@inheritDoc} - */ - @Override - public void setEnabled(boolean enabling) { - super.setEnabled(enabling); - - useMe.setEnabled(enabling); - - if (null != addressLabel) { - addressLabel.setEnabled(useMe.getState()); - } - - host.setEnabled(useMe.getState()); - port.setEnabled(useMe.getState()); - } - - /** - * {@inheritDoc} - */ - public void setState(boolean state) { - useMe.setState(state); // sometimes redundant but not always. - - if (null != addressLabel) { - addressLabel.setEnabled(state); - } - - host.setEnabled(state); - port.setEnabled(state); - } - - /** - * Returns the value of the host field - * - * @return the value of the hot field - */ - public String getHost() { - return host.getText().trim(); - } - - /** - * Returns the value of the port field - * - * @return the value of the port field - */ - public String getPort() { - return port.getText().trim(); - } - } - - - /** - * A list of URIs - */ - static class HostListPanel extends Panel implements ActionListener { - - private final String purpose; - private final TextField host; - private final TextField port; - private final java.awt.List list; - private final Label listLabel; - - private final Button insert; - private final Button remove; - - public HostListPanel(String purpose, String lstLabel, boolean defaultState, boolean showPort) { - - super(new GridBagLayout()); - this.purpose = purpose; - - host = new TextField("", showPort ? 25 : 30); - if (showPort) { - port = new TextField("", 5); - } else { - port = null; - } - insert = new Button("+"); - remove = new Button("-"); - - list = new java.awt.List(2, true); - listLabel = new Label(lstLabel); - - GridBagConstraints c1 = new GridBagConstraints(); - - c1.gridx = 0; - c1.gridy = 0; - c1.anchor = GridBagConstraints.FIRST_LINE_START; - c1.fill = GridBagConstraints.NONE; - add(listLabel, c1); - - c1.gridx = 0; - c1.gridy++; - if (!showPort) { - c1.gridwidth = 2; - } - c1.weightx = 2.0; - c1.anchor = GridBagConstraints.LINE_START; - c1.fill = GridBagConstraints.HORIZONTAL; - add(host, c1); - - if (showPort) { - c1.weightx = 0.0; - c1.gridx = 1; - c1.anchor = GridBagConstraints.LINE_END; - c1.fill = GridBagConstraints.NONE; - add(port, c1); - } - - c1.gridx = 0; - c1.gridy++; - c1.gridwidth = 1; - c1.weightx = 2.0; - c1.anchor = GridBagConstraints.LAST_LINE_START; - c1.fill = GridBagConstraints.HORIZONTAL; - add(list, c1); - - Panel p2 = new Panel(new GridLayout(2, 1, 1, 1)); - - p2.add(insert); - p2.add(remove); - - c1.gridx++; - c1.weightx = 0.0; - c1.anchor = GridBagConstraints.LAST_LINE_END; - c1.fill = GridBagConstraints.NONE; - c1.insets = new Insets(0, 4, 0, 1); - add(p2, c1); - - host.addActionListener(this); - insert.addActionListener(this); - remove.addActionListener(this); - list.addActionListener(this); - - setEnabled(defaultState); - } - - /** - * {@inheritDoc} - */ - @Override - public void setEnabled(boolean state) { - super.setEnabled(state); - - listLabel.setEnabled(state); - host.setEnabled(state); - if (null != port) { - port.setEnabled(state); - } - list.setEnabled(state); - insert.setEnabled(state); - remove.setEnabled(state); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isEnabled() { - return listLabel.isEnabled(); - } - - /** - * {@inheritDoc} - */ - public void actionPerformed(ActionEvent e) { - if ((insert == e.getSource()) || (host == e.getSource())) { - StringBuilder addHost = new StringBuilder(host.getText()); - - if (null != port) { - String portText = port.getText().trim(); - - if (portText.length() > 0) { - // if( !verifyPort( "Host port", portText, false ) ) { - // return; - // } - addHost.append(':'); - addHost.append(portText); - } - } - if (addItem(addHost.toString())) { - host.setText(""); - host.setCaretPosition(0); - if (null != port) { - port.setText(""); - port.setCaretPosition(0); - } - } - return; - } - - if (e.getSource() == remove) { - int[] sel = list.getSelectedIndexes(); - int i = sel.length; - - while (i-- > 0) { - list.remove(sel[i]); - } - - return; - } - - // double click on a host in the list - if (e.getSource() == list) { - String cmd = e.getActionCommand(); - - if (null != port) { - int colonAt = cmd.lastIndexOf(':'); - String newHost = cmd.substring(0, colonAt); - String newPort = cmd.substring(colonAt + 1); - - host.setText(newHost); - host.setCaretPosition(newHost.length()); - port.setText(newPort); - port.setCaretPosition(newHost.length()); - } else { - host.setText(cmd); - host.setCaretPosition(cmd.length()); - } - } - } - - public boolean addItem(String item) { - String hostURI = item.trim(); - - if (0 == hostURI.trim().length()) { - return false; - } - - // See if it is "really" a URI. - try { - new URI(hostURI); - } catch (URISyntaxException failed) { - return false; - } - - try { - while (true) { - try { - list.remove(hostURI); - } catch (IllegalArgumentException notThere) { - break; - } - } - - list.add(hostURI); - } catch (Exception e) { - return false; - } - - return true; - } - - public String getPurpose() { - return purpose; - } - - public String[] getItems() { - return list.getItems(); - } - } - - - /** - * An interface and port selection panel. - */ - static class IfAddrPanel extends Panel implements ItemListener { - private final Checkbox manual; - - private final CardLayout addrLayout; - - private final Panel addrPanel; - private final TextField interfaceAddr; - private final TextField localPort; - - private final Choice ips; - - public IfAddrPanel(String defaultInterfaceAddr, String defaultPort) { - - super(new FlowLayout(FlowLayout.LEADING, 0, 0)); - - ips = new Choice(); - boolean modeManual = false; - - ips.add("Any/All Local Addresses"); - - try { - Iterator allIntf = IPUtils.getAllLocalAddresses(); - boolean sawValid = false; - - while (allIntf.hasNext()) { - InetAddress anAddr = allIntf.next(); - - if (IPUtils.LOOPBACK.equals(anAddr)) { - continue; - } - - ips.add(IPUtils.getHostAddress(anAddr)); - sawValid = true; - } - - if (!sawValid) { - modeManual = true; - } - - // if an address was previously configured, switch to manual - // if we do not find any interface, switch to manual too. - if (defaultInterfaceAddr != null) { - InetAddress defaultIntf = InetAddress.getByName(defaultInterfaceAddr); - - if (!IPUtils.ANYADDRESS.equals(defaultIntf)) { - modeManual = true; - - // However, if this address is in the automatic list, - // switch back to automatic and select it. - allIntf = IPUtils.getAllLocalAddresses(); - - while (allIntf.hasNext()) { - InetAddress anAddr = allIntf.next(); - - if (defaultIntf.equals(anAddr)) { - modeManual = false; - ips.select(defaultInterfaceAddr); - } - } - } - } - } catch (Exception e) { - modeManual = true; - } - - manual = new Checkbox("Manual", null, modeManual); - add(manual); - manual.addItemListener(this); - - addrLayout = new CardLayout(); - addrPanel = new Panel(addrLayout); - - Panel autoPanel = new Panel(new FlowLayout(FlowLayout.LEADING)); - - autoPanel.add(ips); - - Panel manPanel = new Panel(new FlowLayout(FlowLayout.LEADING)); - - interfaceAddr = new TextField(defaultInterfaceAddr, 20); - manPanel.add(interfaceAddr); - - addrPanel.add(manPanel, "man"); - addrPanel.add(autoPanel, "auto"); - - add(addrPanel); - - localPort = new TextField(defaultPort, 6); - add(localPort); - - setManual(modeManual); - } - - /** - * {@inheritDoc} - */ - private void setManual(boolean manMode) { - addrLayout.show(addrPanel, manMode ? "man" : "auto"); - - this.validate(); - } - - /** - * {@inheritDoc} - */ - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - - manual.setEnabled(enabled); - ips.setEnabled(enabled); - interfaceAddr.setEnabled(enabled); - localPort.setEnabled(enabled); - } - - /** - * {@inheritDoc} - */ - public void itemStateChanged(ItemEvent e) { - if (e.getSource() == manual) { - setManual(manual.getState()); - } - } - - public String getAddress() { - if (manual.getState()) { - return interfaceAddr.getText().trim(); - } else { - return ips.getSelectedItem().trim(); - } - } - - public String getPort() { - return localPort.getText().trim(); - } - - public String getMode() { - return manual.getState() ? "manual" : "auto"; - } - - } - - - static final class IPTptPanel extends BorderPanelGBL implements ItemListener { - - enum TransportType { - TYPE_HTTP, TYPE_TCP - } - - - ; - - private final Checkbox useMe; - private final Checkbox pubAddrOnly; - private final Checkbox multicast; - private final Checkbox clientEnabled; - - private final IfAddrPanel ifAddr; - private final HostPortPanel publicAddr; - - public IPTptPanel(TransportType type, boolean defaultState, String name, String defaultInterfaceAddr, String defaultPort, boolean clientState, boolean serverState, String defaultPublicAddr, String defaultPublicPort, boolean pubAddrOnlyState) { - this(type, defaultState, name, defaultInterfaceAddr, defaultPort, clientState, serverState, defaultPublicAddr - , - defaultPublicPort, pubAddrOnlyState, false); - } - - public IPTptPanel(TransportType type, boolean defaultState, String name, String defaultInterfaceAddr, String defaultPort, boolean clientState, boolean serverState, String defaultPublicAddr, String defaultPublicPort, boolean pubAddrOnlyState, boolean multicastState) { - - super(name); - - ifAddr = new IfAddrPanel(defaultInterfaceAddr, defaultPort); - - useMe = new Checkbox("Enabled", null, defaultState); - - if (type == TransportType.TYPE_TCP) { - multicast = new Checkbox("Multicast", null, multicastState); - } else { - multicast = null; - } - - clientEnabled = new Checkbox("Enable Outgoing connections", null, clientState); - - pubAddrOnly = new Checkbox("Hide private addresses", null, pubAddrOnlyState); - - publicAddr = new HostPortPanel("Enable Incoming Connections", "(Optional) Public address", defaultPublicAddr - , - defaultPublicPort, serverState); - - GridBagConstraints constraints = new GridBagConstraints(); - - constraints.weightx = 1.0; - constraints.weighty = 1.0; - - constraints.gridx = 0; - constraints.gridy = 1; - constraints.anchor = GridBagConstraints.FIRST_LINE_START; - add(useMe, constraints); - - if (type == TransportType.TYPE_TCP) { - constraints.anchor = GridBagConstraints.FIRST_LINE_END; - add(multicast, constraints); - } - - constraints.gridx = 0; - constraints.gridy++; - constraints.anchor = GridBagConstraints.LINE_START; - add(ifAddr, constraints); - - constraints.gridx = 0; - constraints.gridy++; - - constraints.anchor = GridBagConstraints.LINE_START; - add(clientEnabled, constraints); - - constraints.anchor = GridBagConstraints.EAST; - add(pubAddrOnly, constraints); - - constraints.gridx = 0; - constraints.gridy++; - - constraints.anchor = GridBagConstraints.LINE_START; - add(publicAddr, constraints); - publicAddr.setState(serverState); - - setState(defaultState); - useMe.addItemListener(this); - } - - /** - * {@inheritDoc} - */ - public void setState(boolean state) { - useMe.setState(state); - ifAddr.setEnabled(state); - publicAddr.setEnabled(state); - if (multicast != null) { - multicast.setEnabled(state); - } - clientEnabled.setEnabled(state); - pubAddrOnly.setEnabled(state); - } - - /** - * {@inheritDoc} - */ - public void itemStateChanged(ItemEvent e) { - setState(useMe.getState()); - } - - public String getInterfaceAddress() { - return ifAddr.getAddress().trim(); - } - - public String getConfigMode() { - return ifAddr.getMode(); - } - - public boolean getPubAddrOnly() { - return pubAddrOnly.getState(); - } - - public void setPubAddrOnly(boolean state) { - pubAddrOnly.setState(state); - } - } - - - /** - * Manages Peer Identity configuration - */ - final class IdPanel extends Panel implements ActionListener { - - private final TextField peerName; - private final TextField passwd; - private final TextField vpasswd; - - public IdPanel(String defaultPeerName, boolean needSecurityConfig) { - - super(new GridBagLayout()); - - peerName = new TextField(defaultPeerName, 20); - - GridBagConstraints constraints = new GridBagConstraints(); - - constraints.gridx = 0; - constraints.gridy = 0; - constraints.anchor = GridBagConstraints.FIRST_LINE_END; - add(new Label("Peer Name", Label.RIGHT), constraints); - - constraints.gridx++; - constraints.anchor = GridBagConstraints.FIRST_LINE_START; - add(peerName, constraints); - - if (needSecurityConfig) { - passwd = new TextField("", 20); - vpasswd = new TextField("", 20); - passwd.setEchoChar('*'); - vpasswd.setEchoChar('*'); - - constraints.gridx = 0; - constraints.gridy++; - constraints.anchor = GridBagConstraints.LINE_END; - add(new Label("Password", Label.RIGHT), constraints); - - constraints.gridx++; - constraints.anchor = GridBagConstraints.LINE_START; - add(passwd, constraints); - - constraints.gridx = 0; - constraints.gridy++; - constraints.anchor = GridBagConstraints.LINE_END; - add(new Label("Verify Password", Label.RIGHT), constraints); - - constraints.gridx++; - constraints.anchor = GridBagConstraints.LINE_START; - add(vpasswd, constraints); - } else { - passwd = null; - vpasswd = null; - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getName() { - return peerName.getText().trim(); - } - - public String getPassword() { - return passwd.getText(); - } - - public String getVerifyPassword() { - return vpasswd.getText(); - } - - public void clearPasswords() { - passwd.setText(""); - vpasswd.setText(""); - } - - /** - * {@inheritDoc} - */ - public void actionPerformed(ActionEvent e) { - } - } - - - /** - * Manages Service Enabling - */ - final static class EnablingPanel extends BorderPanelGBL { - - private final Checkbox isRelay; - private final Checkbox isRendezvous; - private final Checkbox isJxmeProxy; - - EnablingPanel(boolean actAsRelay, boolean actAsRendezvous, boolean actAsJxmeProxy) { - super("Services Settings"); - - isRelay = new Checkbox("Act as a Relay", null, actAsRelay); - isRendezvous = new Checkbox("Act as a Rendezvous", null, actAsRendezvous); - isJxmeProxy = new Checkbox("Act as a JXME proxy", null, actAsJxmeProxy); - - add(isRelay, stdConstr); - add(isRendezvous, stdConstr); - add(isJxmeProxy, stdConstr); - } - } - - - /** - * Manages Rendezvous service options - */ - final static class RdvPanel extends BorderPanelGBL implements ItemListener { - - private final Checkbox useRdv; - private final Checkbox useOnlySeeds; - private final HostListPanel seeding; - private final HostListPanel seeds; - - RdvPanel(boolean useARdv, boolean onlySeeds) { - super("Rendezvous Settings"); - - useRdv = new Checkbox("Use a rendezvous", null, useARdv); - useOnlySeeds = new Checkbox("Use only configured seeds", null, onlySeeds); - seeds = new HostListPanel("Seeds", "Rendezvous seed peers", true, false); - seeding = new HostListPanel("Seeding", "Rendezvous seeding URIs", true, false); - - GridBagConstraints c1 = new GridBagConstraints(); - - c1.gridx = 0; - c1.gridy = 0; - c1.anchor = GridBagConstraints.LINE_START; - add(useRdv, c1); - useRdv.addItemListener(this); - - c1.gridx++; - c1.anchor = GridBagConstraints.LINE_END; - add(useOnlySeeds, c1); - - c1.gridx = 0; - c1.gridy++; - c1.gridwidth = 2; - c1.weightx = 1.0; - c1.fill = GridBagConstraints.HORIZONTAL; - c1.anchor = GridBagConstraints.LINE_START; - add(seeding, c1); - - c1.gridy++; - add(seeds, c1); - } - - /** - * {@inheritDoc} - */ - public void itemStateChanged(ItemEvent e) { - seeds.setEnabled(useRdv.getState()); - seeding.setEnabled(useRdv.getState()); - useOnlySeeds.setEnabled(useRdv.getState()); - } - } - - - /** - * Manages relay service parameters - */ - final static class RelayPanel extends BorderPanelGBL implements ItemListener { - - private final Checkbox useRelay; - private final Checkbox useOnlySeeds; - private final HostListPanel seeding; - private final HostListPanel seeds; - - public RelayPanel(boolean useARelay, boolean onlySeeds) { - - super("Relay Settings"); - - useRelay = new Checkbox("Use a relay", null, useARelay); - useOnlySeeds = new Checkbox("Use only configured seeds", null, onlySeeds); - useOnlySeeds.setEnabled(useARelay); - seeds = new HostListPanel("Seeds", "Relay seed peers", useARelay, false); - seeding = new HostListPanel("Seeding", "Relay seeding URIs", useARelay, false); - - GridBagConstraints c1 = new GridBagConstraints(); - - c1.gridx = 0; - c1.gridy = 0; - c1.anchor = GridBagConstraints.LINE_START; - add(useRelay, c1); - useRelay.addItemListener(this); - - c1.gridx++; - c1.anchor = GridBagConstraints.LINE_END; - add(useOnlySeeds, c1); - - c1.gridx = 0; - c1.gridy++; - c1.gridwidth = 2; - c1.weightx = 1.0; - c1.fill = GridBagConstraints.HORIZONTAL; - c1.anchor = GridBagConstraints.LINE_START; - add(seeding, c1); - - c1.gridy++; - add(seeds, c1); - } - - /** - * {@inheritDoc} - */ - public void itemStateChanged(ItemEvent e) { - seeds.setEnabled(useRelay.getState()); - seeding.setEnabled(useRelay.getState()); - useOnlySeeds.setEnabled(useRelay.getState()); - } - } - - private final PlatformConfig configAdv; - - private final Label helpLabel; - private final IdPanel idPanel; - private final EnablingPanel enablingPanel; - private final IPTptPanel tcpPanel; - private final IPTptPanel httpPanel; - private final RdvPanel rdvPanel; - private final RelayPanel relayPanel; - - private final Button ok; - private final Button cancel; - private final PagesPanel pages = new PagesPanel(); - - boolean done = false; - boolean canceled = false; - - String tcpMulticastAddr; - int tcpMulticastPort; - int tcpMulticastLength; - - public ConfigDialog(PlatformConfig configAdv) throws ConfiguratorException { - super("JXTA Configurator"); - - this.configAdv = configAdv; - - // Identity settings - String peerName = configAdv.getName(); - - if ((null == peerName) || (0 == peerName.trim().length())) { - peerName = ""; - } - - // Security settings - boolean needSecurityConfig = true; - - // If security is already in place, then the security info is not shown. - XMLElement param = (XMLElement) configAdv.getServiceParam(PeerGroup.membershipClassID); - - if (param != null) { - Advertisement adv = null; - - try { - adv = AdvertisementFactory.newAdvertisement(param); - } catch (NoSuchElementException notAnAdv) { - ; // that's ok. - } catch (IllegalArgumentException badAdv) { - ; // that's ok. - } - - if (adv instanceof PSEConfigAdv) { - PSEConfigAdv pseConfig = (PSEConfigAdv) adv; - - // no certificate? That means we need to make one. - needSecurityConfig = (null == pseConfig.getCertificate()); - } - } - - // JXME Proxy Settings - boolean isJxmeProxy = false; - - try { - param = (XMLElement) configAdv.getServiceParam(PeerGroup.proxyClassID); - - if (param != null && configAdv.isSvcEnabled(PeerGroup.proxyClassID)) { - isJxmeProxy = true; - } - } catch (Exception nobigdeal) { - nobigdeal.printStackTrace(); - } - - int index; - - // TCP Settings - boolean tcpEnabled; - boolean clientDefaultT; - boolean serverDefaultT; - String defaultInterfaceAddressT; - String defaultPortT; - String defaultServerNameT; - String defaultServerPortT; - boolean multicastEnabledT; - boolean noPublicAddressesT; - - try { - param = (XMLElement) configAdv.getServiceParam(PeerGroup.tcpProtoClassID); - - tcpEnabled = configAdv.isSvcEnabled(PeerGroup.tcpProtoClassID); - - Enumeration tcpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType()); - - // get the TransportAdv from either TransportAdv or tcpAdv - if (tcpChilds.hasMoreElements()) { - param = tcpChilds.nextElement(); - } else { - throw new IllegalStateException("Missing TCP Advertisment"); - } - - TCPAdv tcpAdv = (TCPAdv) AdvertisementFactory.newAdvertisement(param); - - clientDefaultT = tcpAdv.isClientEnabled(); - serverDefaultT = tcpAdv.isServerEnabled(); - - defaultInterfaceAddressT = tcpAdv.getInterfaceAddress(); - - if ((null == defaultInterfaceAddressT) || (0 == defaultInterfaceAddressT.trim().length())) { - defaultInterfaceAddressT = null; - } - - defaultPortT = Integer.toString(tcpAdv.getPort()); - if ((defaultPortT == null) || (0 == defaultPortT.trim().length())) { - defaultPortT = "9701"; - } - - defaultServerNameT = tcpAdv.getServer(); - - if ((null == defaultServerNameT) || (0 == defaultServerNameT.trim().length())) { - defaultServerNameT = ""; - } - - if (defaultServerNameT != null && (index = defaultServerNameT.lastIndexOf(":")) != -1) { - if ((0 == index) || (index == defaultServerNameT.length())) { - throw new IllegalArgumentException("Bad TCP server name . Cannot proceed."); - } - defaultServerPortT = defaultServerNameT.substring(index + 1); - defaultServerNameT = defaultServerNameT.substring(0, index); - } else { - defaultServerNameT = ""; - defaultServerPortT = "9701"; - } - - noPublicAddressesT = tcpAdv.getPublicAddressOnly(); - multicastEnabledT = tcpAdv.getMulticastState(); - - // we will just pass these to save. - tcpMulticastAddr = tcpAdv.getMulticastAddr(); - tcpMulticastPort = tcpAdv.getMulticastPort(); - tcpMulticastLength = tcpAdv.getMulticastSize(); - } catch (Exception failure) { - throw new ConfiguratorException("Broken Platform Config. Cannot proceed.", failure); - } - - // HTTP Settings - boolean httpEnabled; - boolean clientDefaultH; - boolean serverDefaultH; - String defaultInterfaceAddressH; - String defaultPortH; - String defaultServerNameH; - String defaultServerPortH; - boolean noPublicAddressesH; - - try { - param = (XMLElement) configAdv.getServiceParam(PeerGroup.httpProtoClassID); - - httpEnabled = configAdv.isSvcEnabled(PeerGroup.httpProtoClassID); - - Enumeration httpChilds = param.getChildren(TransportAdvertisement.getAdvertisementType()); - - // get the TransportAdv from either TransportAdv - if (httpChilds.hasMoreElements()) { - param = httpChilds.nextElement(); - } else { - throw new IllegalStateException("Missing HTTP Advertisment"); - } - - // Read-in the adv as it is now. - HTTPAdv httpAdv = (HTTPAdv) AdvertisementFactory.newAdvertisement(param); - - clientDefaultH = httpAdv.isClientEnabled(); - serverDefaultH = httpAdv.isServerEnabled(); - - defaultInterfaceAddressH = httpAdv.getInterfaceAddress(); - - if ((null == defaultInterfaceAddressH) || (0 == defaultInterfaceAddressH.trim().length())) { - defaultInterfaceAddressH = null; - } - - defaultPortH = Integer.toString(httpAdv.getPort()); - - if ((defaultPortH == null) || (0 == defaultPortH.trim().length())) { - defaultPortH = "9700"; - } - - defaultServerNameH = httpAdv.getServer(); - - if ((null != defaultServerNameH) && (0 == defaultServerNameH.trim().length())) { - defaultServerNameH = ""; - } - - defaultServerPortH = "9700"; - - if (defaultServerNameH != null && (index = defaultServerNameH.lastIndexOf(":")) != -1) { - if ((0 == index) || (index == defaultServerNameH.length())) { - throw new IllegalArgumentException("Bad HTTP server name. Cannot proceed."); - } - defaultServerPortH = defaultServerNameH.substring(index + 1); - defaultServerNameH = defaultServerNameH.substring(0, index); - } else { - defaultServerNameH = ""; - defaultServerPortH = "9700"; - } - - noPublicAddressesH = httpAdv.getPublicAddressOnly(); - } catch (Exception failure) { - throw new ConfiguratorException("Broken Platform Config. Cannot proceed.", failure); - } - - // Rendezvous Settings - boolean isRendezvous; - boolean isAdhoc; - boolean onlySeeds; - List seedRdvs = new ArrayList(); - List seedingRdvs = new ArrayList(); - - try { - RdvConfigAdv rdvConfigAdv; - - param = (XMLElement) configAdv.getServiceParam(PeerGroup.rendezvousClassID); - - rdvConfigAdv = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(param); - - isRendezvous = (RendezVousConfiguration.RENDEZVOUS == rdvConfigAdv.getConfiguration()); - - isAdhoc = (RendezVousConfiguration.AD_HOC == rdvConfigAdv.getConfiguration()); - - onlySeeds = rdvConfigAdv.getUseOnlySeeds(); - - for (URI uri : Arrays.asList(rdvConfigAdv.getSeedRendezvous())) { - seedRdvs.add(uri.toString()); - } - - for (URI uri1 : Arrays.asList(rdvConfigAdv.getSeedingURIs())) { - seedingRdvs.add(uri1.toString()); - } - } catch (Exception failure) { - throw new ConfiguratorException("Broken Platform Config. Cannot proceed.", failure); - } - - // Relay Settings - boolean isRelay; - boolean useRelay; - boolean useOnlySeedRelays; - List seedRelays = new ArrayList(); - List seedingRelays = new ArrayList(); - - try { - param = (XMLElement) configAdv.getServiceParam(PeerGroup.relayProtoClassID); - - RelayConfigAdv relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement(param); - - isRelay = relayConfig.isServerEnabled(); - - useRelay = relayConfig.isClientEnabled(); - - useOnlySeedRelays = relayConfig.getUseOnlySeeds(); - - for (EndpointAddress endpointAddress : Arrays.asList(relayConfig.getSeedRelays())) { - seedRelays.add(endpointAddress.toString()); - } - - for (URI uri : Arrays.asList(relayConfig.getSeedingURIs())) { - seedingRelays.add(uri.toString()); - } - } catch (Exception failure) { - throw new ConfiguratorException("Broken Platform Config. Cannot proceed.", failure); - } - - // BEGIN BUILDING UI - - GridBagLayout layout = new GridBagLayout(); - - setLayout(layout); - - addWindowListener(new WindowAdapter() { - - @Override - public void windowClosing(WindowEvent e) { - beCanceled(); - } - }); - - helpLabel = new Label("See \"http://jxta-jxse.dev.java.net/confighelp.html\" for config help", Label.CENTER); - helpLabel.setBackground(new Color(220, 220, 220)); - helpLabel.setForeground(Color.black); - - helpLabel.addMouseListener(new MouseAdapter() { - - @Override - public void mouseClicked(MouseEvent e) { - helpLabel.setForeground(Color.black); - helpLabel.setText("See \"http://jxta-jxse.dev.java.net/confighelp.html\" for config help"); - } - }); - - idPanel = new IdPanel(peerName, needSecurityConfig); - - enablingPanel = new EnablingPanel(isRelay, isRendezvous, isJxmeProxy); - - tcpPanel = new IPTptPanel(IPTptPanel.TransportType.TYPE_TCP, tcpEnabled, "TCP Settings", defaultInterfaceAddressT, - defaultPortT, clientDefaultT, serverDefaultT, defaultServerNameT, defaultServerPortT, noPublicAddressesT, - multicastEnabledT); - - httpPanel = new IPTptPanel(IPTptPanel.TransportType.TYPE_HTTP, httpEnabled, "HTTP Settings", defaultInterfaceAddressH, - defaultPortH, clientDefaultH, serverDefaultH, defaultServerNameH, defaultServerPortH, noPublicAddressesH); - - rdvPanel = new RdvPanel(!isAdhoc, onlySeeds); - - // add the relays - - for (Object seedRdv : seedRdvs) { - rdvPanel.seeds.addItem((String) seedRdv); - } - - for (Object seedingRdv : seedingRdvs) { - rdvPanel.seeding.addItem((String) seedingRdv); - } - - relayPanel = new RelayPanel(useRelay, useOnlySeedRelays); - - // add the relays - for (Object seedRelay : seedRelays) { - relayPanel.seeds.addItem((String) seedRelay); - } - - for (Object seedingRelay : seedingRelays) { - relayPanel.seeding.addItem((String) seedingRelay); - } - - ok = new Button(" OK "); - - ok.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - if (verifyInput()) { - if (saveValues()) { - beDone(); - } else { - beCanceled(); - } - } - } - }); - - cancel = new Button("Cancel"); - cancel.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - beCanceled(); - } - }); - - Panel okPanel = new Panel(); - - okPanel.add(ok); - okPanel.add(cancel); - - // build basic panel - Panel basicsPanel = pages.addPage("Basic", "Basic settings"); - - GridBagConstraints centerWConstr = (GridBagConstraints) centerConstr.clone(); - - centerWConstr.weighty = 1; - - basicsPanel.add(idPanel, centerWConstr); - - // build Advanced panel - Panel advancedPanel = pages.addPage("Advanced", "Experienced Users Only"); - - advancedPanel.add(enablingPanel, fillInsetConstr); - advancedPanel.add(tcpPanel, fillInsetConstr); - advancedPanel.add(httpPanel, fillInsetConstr); - - Panel proxyRdvRelayPanel = pages.addPage("Rendezvous/Relays", "Experienced Users Only"); - - proxyRdvRelayPanel.add(rdvPanel, fillInsetConstr); - proxyRdvRelayPanel.add(relayPanel, fillInsetConstr); - - add(helpLabel, fillConstr); - add(pages, fillInsetConstr); - add(okPanel, centerLastConstr); - - pack(); - setVisible(true); - } - - public synchronized boolean untilDone() { - try { - while (!done) { - wait(); - } - } catch (InterruptedException e) { - Thread.interrupted(); - } - - if (canceled) { - throw new JxtaError("Canceled during configuration"); - } - return (done); - } - - private synchronized boolean beDone() { - done = true; - notify(); - dispose(); - - return canceled; - } - - private synchronized boolean beCanceled() { - canceled = true; - done = true; - notify(); - dispose(); - - return canceled; - } - - private boolean verifyPort(String portName, String ports, boolean dynamicok) { - int p1; - - if ((null == ports) || (0 == ports.trim().length())) { - ports = "0"; - } - - try { - p1 = Integer.parseInt(ports); - } catch (Exception ex) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText(portName + " port number must be an integer: " + ports); - return false; - } - if ((p1 > 65535) || (p1 < (dynamicok ? 0 : 1))) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText( - portName + " port number must be an integer between " + (dynamicok ? "0" : "1") + " and 65535, found " + p1); - return false; - } - return true; - } - - private boolean verifyAddr(String proto, boolean serverOn, String localPort, String publicAddress, String publicPort) { - - // if a public name is specified, check its port. - if (serverOn && (publicAddress.length() > 0)) { - if (!verifyPort(proto + " local", localPort, false)) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Dynamic tcp port selection not supported when server public address is specified."); - pages.showPage("Advanced"); - return false; - } - - if (!verifyPort(proto + " public", publicPort, false)) { - pages.showPage("Advanced"); - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Dynamic tcp port selection not supported for server public address."); - return false; - } - } else if (!verifyPort(proto + " local", localPort, true)) { - pages.showPage("Advanced"); - return false; - } - - return true; - } - - private boolean verifyInput() { - - if (0 == idPanel.getName().trim().length()) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("A peer name is required."); - pages.showPage("Basic"); - return false; - } - - // Verify security parameters if we are not initialized - // Password and principal - if (null != idPanel.passwd) { - String passwd = idPanel.getPassword(); - String vpasswd = idPanel.getVerifyPassword(); - - // Verify password - // must be at least 8 chars a la unix - if (passwd.length() < 8) { - // Clear password text boxes - idPanel.clearPasswords(); - - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Passwords must be at least 8 characters"); - pages.showPage("Basic"); - return false; - } - - // must be identical - if (!passwd.equals(vpasswd)) { - // Clear password text boxes - idPanel.clearPasswords(); - - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Password does not match Verify Password"); - pages.showPage("Basic"); - return false; - } - } - - // make sure *some* transport is enabled. - if ((!(httpPanel.useMe.getState())) && (!(tcpPanel.useMe.getState()))) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("At least one of TCP or HTTP must be enabled."); - pages.showPage("Advanced"); - return false; - } - - // http settings - if (httpPanel.useMe.getState()) { - // make sure at least incoming or outgoing enabled. - if (!httpPanel.clientEnabled.getState() && !httpPanel.publicAddr.getState()) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Must enable incoming and/or outcoming to enable HTTP"); - pages.showPage("Advanced"); - return false; - } - - // Check the http port fields. - boolean valid = verifyAddr("HTTP", httpPanel.publicAddr.getState(), httpPanel.ifAddr.getPort(), - httpPanel.publicAddr.getHost(), httpPanel.publicAddr.getPort()); - - if (!valid) { - return false; - } - } - - // tcp settings - if (tcpPanel.useMe.getState()) { - // make sure at least incoming or outgoing enabled. - if (!tcpPanel.clientEnabled.getState() && !tcpPanel.publicAddr.getState() && !tcpPanel.multicast.getState()) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Must enable at least one of incoming, outcoming or multicast to enable TCP"); - pages.showPage("Advanced"); - return false; - } - - // Check the tcp port fields. - boolean valid = verifyAddr("TCP", tcpPanel.publicAddr.getState(), tcpPanel.ifAddr.getPort(), - tcpPanel.publicAddr.getHost(), tcpPanel.publicAddr.getPort()); - - if (!valid) { - return false; - } - } - - if (!relayPanel.useRelay.getState() && (!httpPanel.useMe.getState() || !httpPanel.publicAddr.getState()) - && (!tcpPanel.useMe.getState() || !tcpPanel.publicAddr.getState())) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Must use Relay if incoming not enabled for TCP and/or HTTP"); - pages.showPage("Relay/Rendezvous"); - return false; - } - - if (enablingPanel.isRelay.getState() && (!httpPanel.useMe.getState() || !httpPanel.publicAddr.getState()) - && (!tcpPanel.useMe.getState() || !tcpPanel.publicAddr.getState())) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Must enable incoming for TCP and/or HTTP to enable Relay"); - pages.showPage("Advanced"); - return false; - } - - if (enablingPanel.isRendezvous.getState() && (!httpPanel.useMe.getState() || !httpPanel.publicAddr.getState()) - && (!tcpPanel.useMe.getState() || !tcpPanel.publicAddr.getState())) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Must enable incoming for TCP and/or HTTP to enable Rendezvous"); - pages.showPage("Advanced"); - return false; - } - - // if use only seeds is specified then at least one seed must be - // provided. - if (rdvPanel.useOnlySeeds.getState()) { - String[] rdvAddrs = rdvPanel.seeds.getItems(); - - String[] rdvSeedAddrs = rdvPanel.seeding.getItems(); - - if ((rdvAddrs.length == 0) && (rdvSeedAddrs.length == 0)) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Must provide at least one seed rendezvous"); - pages.showPage("Rendezvous/Relays"); - return false; - } - } - - // if relay is to be used, make sure we have atleast one relay - // addr for the enabled transport(s) - if (relayPanel.useRelay.getState()) { - String[] relayaddrs = relayPanel.seeds.getItems(); - - String[] relaySeedaddrs = relayPanel.seeding.getItems(); - - if ((relayaddrs.length == 0) && (relaySeedaddrs.length == 0)) { - helpLabel.setForeground(Color.red.darker()); - helpLabel.setText("Must provide at least one seed Relay address"); - pages.showPage("Rendezvous/Relays"); - return false; - } - } - - return true; - } - - /* - * Updates the PlatformConfig Advertisement - */ - private boolean saveValues() { - try { - // set the peer name - configAdv.setName(idPanel.getName()); - - // Save the http config - HTTPAdv httpAdv = (HTTPAdv) AdvertisementFactory.newAdvertisement(HTTPAdv.getAdvertisementType()); - - httpAdv.setConfigMode(httpPanel.getConfigMode()); - - String chosenIntf = httpPanel.getInterfaceAddress(); - - if (chosenIntf.startsWith("A")) { - httpAdv.setInterfaceAddress(null); - } else { - httpAdv.setInterfaceAddress(chosenIntf); - } - - httpAdv.setPort(Integer.parseInt(httpPanel.ifAddr.getPort())); - - httpAdv.setClientEnabled(httpPanel.clientEnabled.getState()); - - httpAdv.setServerEnabled(httpPanel.publicAddr.getState()); - - // If there's nothing interesting inthere, do not save it. - if (0 == httpPanel.publicAddr.getHost().trim().length()) { - httpAdv.setServer(null); - } else { - httpAdv.setServer(httpPanel.publicAddr.getHost() + ":" + httpPanel.publicAddr.getPort()); - } - - httpAdv.setPublicAddressOnly(httpPanel.getPubAddrOnly()); - - configAdv.putServiceParam(PeerGroup.httpProtoClassID, wrapParm(httpAdv, httpPanel.useMe.getState())); - - // Save tcp configuration - TCPAdv tcpAdv = (TCPAdv) AdvertisementFactory.newAdvertisement(TCPAdv.getAdvertisementType()); - - tcpAdv.setConfigMode(tcpPanel.getConfigMode()); - - chosenIntf = tcpPanel.getInterfaceAddress(); - if (chosenIntf.startsWith("A")) { - tcpAdv.setInterfaceAddress(null); - } else { - tcpAdv.setInterfaceAddress(chosenIntf); - } - - try { - int theTcpPort = Integer.parseInt(tcpPanel.ifAddr.getPort()); - - tcpAdv.setPort(theTcpPort); - if (0 == theTcpPort) { - tcpAdv.setStartPort(0); - tcpAdv.setEndPort(0); - } - } catch (NumberFormatException ignored) { - /* verifyInput already checked it */ - } - - tcpAdv.setClientEnabled(tcpPanel.clientEnabled.getState()); - - tcpAdv.setServerEnabled(tcpPanel.publicAddr.getState()); - - if (0 == tcpPanel.publicAddr.getHost().trim().length()) { - tcpAdv.setServer(null); - } else { - tcpAdv.setServer(tcpPanel.publicAddr.getHost() + ":" + tcpPanel.publicAddr.getPort()); - } - - tcpAdv.setMulticastState(tcpPanel.multicast.getState()); - tcpAdv.setMulticastAddr(tcpMulticastAddr); - tcpAdv.setMulticastPort(tcpMulticastPort); - tcpAdv.setMulticastSize(tcpMulticastLength); - - tcpAdv.setPublicAddressOnly(tcpPanel.getPubAddrOnly()); - - configAdv.putServiceParam(PeerGroup.tcpProtoClassID, wrapParm(tcpAdv, tcpPanel.useMe.getState())); - - // save the proxy service settings - XMLDocument proxy = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - - if (!enablingPanel.isJxmeProxy.getState()) { - proxy.appendChild(proxy.createElement("isOff")); - } - - configAdv.putServiceParam(PeerGroup.proxyClassID, proxy); - - // Save the Rendezvous Configuration - RdvConfigAdv rdvConf = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType()); - - rdvConf.setConfiguration( - enablingPanel.isRendezvous.getState() ? RendezVousConfiguration.RENDEZVOUS : - rdvPanel.useRdv.getState() ? RendezVousConfiguration.EDGE : RendezVousConfiguration.AD_HOC); - rdvConf.setUseOnlySeeds(rdvPanel.useOnlySeeds.getState()); - - for (String s2 : Arrays.asList(rdvPanel.seeds.getItems())) { - rdvConf.addSeedRendezvous(s2); - } - - for (String s3 : Arrays.asList(rdvPanel.seeding.getItems())) { - rdvConf.addSeedingURI(s3); - } - - XMLDocument rdvDoc = (XMLDocument) rdvConf.getDocument(MimeMediaType.XMLUTF8); - - configAdv.putServiceParam(PeerGroup.rendezvousClassID, rdvDoc); - - // save the relay settings - RelayConfigAdv relayConfig = (RelayConfigAdv) AdvertisementFactory.newAdvertisement( - RelayConfigAdv.getAdvertisementType()); - - relayConfig.setServerEnabled(enablingPanel.isRelay.getState()); - relayConfig.setClientEnabled(relayPanel.useRelay.getState()); - - for (String s : Arrays.asList(relayPanel.seeds.getItems())) { - relayConfig.addSeedRelay(s); - } - - for (String s1 : Arrays.asList(relayPanel.seeding.getItems())) { - relayConfig.addSeedingURI(s1); - } - - relayConfig.setUseOnlySeeds(relayPanel.useOnlySeeds.getState()); - - XMLDocument relayDoc = (XMLDocument) relayConfig.getDocument(MimeMediaType.XMLUTF8); - - // check if the relay service should be disabled completely - boolean relayDisabled = (!enablingPanel.isRelay.getState() && !relayPanel.useRelay.getState()); - - if (relayDisabled) { - relayDoc.appendChild(relayDoc.createElement("isOff")); - } - - configAdv.putServiceParam(PeerGroup.relayProtoClassID, relayDoc); - - // Save the security configuration parameters - // If we initialized security - // Otherwise they come from the security login dialog - if (null != idPanel.passwd) { - PSEConfigAdv pseConf = (PSEConfigAdv) AdvertisementFactory.newAdvertisement(PSEConfigAdv.getAdvertisementType()); - - PSEUtils.IssuerInfo info = PSEUtils.genCert(idPanel.getName(), null); - - pseConf.setCertificate(info.cert); - pseConf.setPrivateKey(info.subjectPkey, idPanel.getPassword().toCharArray()); - - XMLDocument pseDoc = (XMLDocument) pseConf.getDocument(MimeMediaType.XMLUTF8); - - configAdv.putServiceParam(PeerGroup.membershipClassID, pseDoc); - } - } catch (Throwable bad) { - bad.printStackTrace(); - return false; - } - - return true; - } - - private XMLDocument wrapParm(Advertisement srcAdv, boolean enabled) { - try { - XMLDocument advDoc = (XMLDocument) srcAdv.getDocument(MimeMediaType.XMLUTF8); - - XMLDocument doc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - - StructuredDocumentUtils.copyElements(doc, doc, advDoc); - if (!enabled) { - doc.appendChild(doc.createElement("isOff")); - } - - return doc; - } catch (Throwable ez1) { - ez1.printStackTrace(); - return null; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/DefaultConfigurator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/DefaultConfigurator.java deleted file mode 100644 index ed74338c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/DefaultConfigurator.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.XMLDocument; -import net.jxta.exception.ConfiguratorException; -import net.jxta.exception.JxtaError; -import net.jxta.impl.protocol.PSEConfigAdv; -import net.jxta.impl.protocol.PlatformConfig; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URI; -import java.util.NoSuchElementException; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This implementation provides the ability to reconfigure a JXTA PlatformConfig - * via an AWT based dialog. This is the original JXTA configuration mechanism. - */ -public class DefaultConfigurator extends AutomaticConfigurator { - - /** - * logger - */ - private final static transient Logger LOG = Logger.getLogger(DefaultConfigurator.class.getName()); - - /** - * Configures the platform using the specified directory. - * - * @param jxtaHome store home URI - * @throws net.jxta.exception.ConfiguratorException - * if a configuration error occurs - */ - public DefaultConfigurator(URI jxtaHome) throws ConfiguratorException { - super(jxtaHome); - } - - /** - * {@inheritDoc} - *

            - *

            Kinda hackish in that we don't really do anything if home is not a file. - */ - @Override - public boolean isReconfigure() { - if (!"file".equalsIgnoreCase(jxtaHome.getScheme())) { - return false; - } - - File jxtaHomeDir = new File(jxtaHome); - try { - boolean forceReconfig; - File file = new File(jxtaHomeDir, "reconf"); - forceReconfig = file.exists(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("force reconfig : " + forceReconfig); - } - - return forceReconfig; - } catch (Exception ex1) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not check \'reconf\' file. Assuming it exists.", ex1); - } - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Reconfig required - error getting \'reconf\' file"); - } - return true; - } - } - - /** - * {@inheritDoc} - */ - @Override - public void setReconfigure(boolean reconfigure) { - if (!"file".equalsIgnoreCase(jxtaHome.getScheme())) { - return; - } - - File jxtaHomeDir = new File(jxtaHome); - File f = new File(jxtaHomeDir, "reconf"); - - if (reconfigure) { - try { - f.createNewFile(); - } catch (IOException ex1) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not create \'reconf\' file", ex1); - LOG.severe("Create the file \'reconf\' by hand before retrying."); - } - } - } else { - try { - f.delete(); - } catch (Exception ex1) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not remove \'reconf\' file", ex1); - LOG.severe("Delete the file \'reconf\' by hand before retrying."); - } - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public PlatformConfig getPlatformConfig() throws ConfiguratorException { - boolean needsConfig = isReconfigure(); - - if (needsConfig && Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Reconfig requested - Forced reconfigure"); - } - - try { - super.getPlatformConfig(); - - // Automatic configuration doesn't do any security config. We use - // this fact to decide if we must do configuration. - XMLDocument security = (XMLDocument) advertisement.getServiceParam(PeerGroup.membershipClassID); - - if (null == security) { - needsConfig = true; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("Reconfig requested - No security info"); - } - } else { - Advertisement adv = null; - - try { - adv = AdvertisementFactory.newAdvertisement(security); - } catch (NoSuchElementException notAnAdv) {// that's ok. - } catch (IllegalArgumentException badAdv) {// that's ok. - } - - if (adv instanceof PSEConfigAdv) { - PSEConfigAdv pseConfig = (PSEConfigAdv) adv; - - // no certificate? That means we need to make one. - needsConfig |= (null == pseConfig.getCertificate()); - } else { - needsConfig = true; - } - } - } catch (IncompleteConfigurationException configBad) { - needsConfig = true; - } - - if (needsConfig) { - setReconfigure(true); - - try { - if (java.awt.EventQueue.isDispatchThread()) { - LOG.severe("The JXTA AWT Configuration Dialog cannot be run from the event dispatch thread. It\'s modal nature is fundamentally incompatible with running on the event dispatch thread. Either change to a different Configurator via PeerGroupFactory.setConfiguratorClass() or start JXTA from the application main Thread before starting your GUI via invokeLater()."); - // cruel but fair, the alternative is a UI deadlock. - System.exit(1); - } - ConfigDialog configUI = new ConfigDialog(advertisement); - - configUI.untilDone(); - setReconfigure(false); - } catch (Throwable t) { - if (t instanceof JxtaError) { - throw (JxtaError) t; - } - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not initialize graphical config dialog", t); - } - - BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); - - // clear any type-ahead - try { - while (in.ready()) { - in.readLine(); - } - } catch (Exception ignored) {// ignored - } - - System.err.flush(); - System.out.flush(); - System.out.println("The window-based configurator does not seem to be usable."); - System.out.print("Do you want to stop and edit the current configuration ? [no]: "); - System.out.flush(); - String answer = "no"; - - try { - answer = in.readLine(); - } catch (Exception ignored) {// ignored - } - - // this will cover all the cases of the answer yes, while - // allowing non-gui/batch type scripts to load the platform - // see platform issue #45 - - if ("yes".equalsIgnoreCase(answer)) { - save(); - System.out.println("Exiting; edit the file \"" + configFile.getPath() - + "\", remove the file \"reconf\", and then launch JXTA again."); - throw new JxtaError("Manual Configuration Requested"); - } else { - System.out.println("Attempting to continue using the current configuration."); - } - } - } - return advertisement; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/GenericPeerGroup.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/GenericPeerGroup.java deleted file mode 100644 index 33c259bd..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/GenericPeerGroup.java +++ /dev/null @@ -1,1720 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Executor; -import java.util.concurrent.ThreadPoolExecutor; -import net.jxta.access.AccessService; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Element; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointService; -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.ProtocolNotSupportedException; -import net.jxta.exception.ServiceNotFoundException; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.loader.RefJxtaLoader; -import net.jxta.impl.protocol.PSEConfigAdv; -import net.jxta.impl.protocol.PlatformConfig; -import net.jxta.impl.util.TimeUtils; -import net.jxta.logging.Logging; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peer.PeerInfoService; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.pipe.PipeService; -import net.jxta.platform.JxtaLoader; -import net.jxta.platform.Module; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.resolver.ResolverService; -import net.jxta.service.Service; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.lang.reflect.UndeclaredThrowableException; -import java.net.URI; -import java.net.URL; -import java.security.cert.Certificate; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Provides common services for most peer group implementations. - */ -public abstract class GenericPeerGroup implements PeerGroup { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(GenericPeerGroup.class.getName()); - - /** - * Holder for configuration parameters for groups in the process of being created. - */ - private final static Map group_configs = Collections.synchronizedMap(new HashMap()); - - /** - * The loader - use the getter and setter for modifying the ClassLoader for - * a security manager. - *

            - * This should eventually be group scoped rather than implementation - * scoped. We are currently allowing classes to loaded into contexts which - * they should not be known. - */ - private final static JxtaLoader loader = new RefJxtaLoader(new URL[0], new CompatibilityEquater() { - public boolean compatible(Element test) { - return StdPeerGroup.isCompatible(test); - } - }); - - /* - * Shortcuts to well known services. - */ - private EndpointService endpoint; - private ResolverService resolver; - private DiscoveryService discovery; - private PipeService pipe; - private MembershipService membership; - private RendezVousService rendezvous; - private PeerInfoService peerinfo; - private AccessService access; - - /** - * This peer's advertisement in this group. - */ - private final PeerAdvertisement peerAdvertisement; - - /** - * This group's advertisement. - */ - private PeerGroupAdvertisement peerGroupAdvertisement = null; - - /** - * This group's implAdvertisement. - */ - protected ModuleImplAdvertisement implAdvertisement = null; - - /** - * This peer's config advertisement. - */ - protected ConfigParams configAdvertisement = null; - - /** - * This service implements a group but, being a Service, it runs inside of - * some group. That's its home group. - *

            - * Exception: The platform peer group does not have a parent group. It - * has to be entirely self sufficient. - */ - protected PeerGroup parentGroup = null; - - /** - * The location of our store - */ - protected URI jxtaHome = null; - - /** - * The services that do the real work of the Peer Group. - */ - private final Map services = new HashMap(); - - /** - * {@code true} when we have decided to stop this group. - */ - private volatile boolean stopping = false; - - /** - * {@code true} when the PG adv has been published. - */ - private boolean published = false; // assume it hasn't - - /** - * Counts the number of times an interface to this group has been given out. - * This is decremented every time an interface object is GCed or - * its owner calls unref(). - * - *

            When it reaches zero, if it is time to tear-down the group instance; - * nomatter what the GC thinks. There are threads that need to be stopped - * before the group instance object ever becomes un-reachable. - */ - private int masterRefCount = 0; - - /** - * Is {@code true} when at least one interface object has been generated AFTER - * initComplete has become true. If true, the group stops when its ref - * count reaches zero. - */ - private boolean stopWhenUnreferenced = false; - - /** - * Is set to {@code true} when {@code init()} is completed enough that it - * makes sense to perform ref-counting. - */ - protected volatile boolean initComplete = false; - - /** - * The thread group in which threads created by this group or services of - * this group should live. The thread group is used primarily for debugging - * and classification purposes--we don't try to use any of the fancy (and - * mostly useless) ThreadGroup features. - */ - private ThreadGroup threadGroup = null; - - /** - * The minimum number of Threads our Executor will reserve. Once started - * these Threads will remain. - * - * todo convert these hardcoded settings into group config params. - */ - private final int COREPOOLSIZE = 5; - - - /** - * The number of seconds that Threads above {@code COREPOOLSIZE} will - * remain idle before terminating. - * - * todo convert these hardcoded settings into group config params. - */ - private final long KEEPALIVETIME = 15; - - - /** - * The intended upper bound on the number of threads we will allow our - * Executor to create. We will allow the pool to grow to twice this size if - * we run out of threads. - * - * todo convert these hardcoded settings into group config params. - */ - private final int MAXPOOLSIZE = 100; - - - /** - * Queue for tasks waiting to be run by our {@code Executor}. - */ - private BlockingQueue taskQueue; - - - /** - * The PeerGroup ThreadPool - */ - private ThreadPoolExecutor threadPool; - - /** - * The PeerGroup ScheduledExecutor - */ - private ScheduledThreadPoolExecutor scheduledExecutor; - - - /** - * {@inheritDoc} - *

            - * We do not want to count on the invoker to properly unreference the group - * object that we return; this call is often used in a loop and it is silly - * to increment and decrement ref-counts for references that are sure to - * live shorter than the referee. - *

            - * On the other hand it is dangerous for us to share our reference object to - * the parent group. That's where weak interface objects come in handy. We - * can safely make one and give it away. - */ - public PeerGroup getParentGroup() { - if (parentGroup == null) { - return null; - } - return parentGroup.getWeakInterface(); - } - - /** - * {@inheritDoc} - */ - public URI getStoreHome() { - return jxtaHome; - } - - /** - * Sets the root location for the store to be used by this peergroup. - *

            - * This should be set early in the peer group's life and then never - * changed. - * - * @param newHome The new store location. - */ - protected void setStoreHome(URI newHome) { - jxtaHome = newHome; - } - - /** - * {@inheritDoc} - */ - public static JxtaLoader getJxtaLoader() { - return loader; - } - - public GenericPeerGroup() { - // Start building our peer adv. - peerAdvertisement = (PeerAdvertisement) - AdvertisementFactory.newAdvertisement(PeerAdvertisement.getAdvertisementType()); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - if (!(target instanceof PeerGroup)) { - return false; - } - - PeerGroup targetAsPeerGroup = (PeerGroup) target; - - // both null or both non-null. - if ((null == parentGroup) && (null != targetAsPeerGroup.getParentGroup())) { - return false; - } - - if ((null != parentGroup) && (null == targetAsPeerGroup.getParentGroup())) { - return false; - } - - if ((null != parentGroup) && !parentGroup.equals(targetAsPeerGroup.getParentGroup())) { - return false; - } - - // and same peer ids. - return getPeerGroupID().equals(targetAsPeerGroup.getPeerGroupID()); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - // before init we must fail. - if ((null == peerAdvertisement) || (null == getPeerGroupID())) { - throw new IllegalStateException("PeerGroup not sufficiently initialized"); - } - - // XXX 20050907 bondolo including parentGroup would improve the hash. - return getPeerGroupID().hashCode(); - } - - /** - * {@inheritDoc} - *

            - * An implementation suitable for debugging. Don't try to parse - * this string! All of the information is available from other sources. - */ - @Override - public String toString() { - if (null == getPeerGroupID()) { - return super.toString(); - } - - StringBuilder result = new StringBuilder(); - - result.append(getPeerGroupID().toString()); - String peerGroupName = peerGroupAdvertisement.getName(); - - if (null != peerGroupName) { - result.append(" \""); - result.append(peerGroupName); - result.append('\"'); - } - - result.append('['); - result.append(masterRefCount); - result.append(']'); - - if (null != parentGroup) { - result.append(" / "); - result.append(parentGroup.toString()); - } - - return result.toString(); - } - - /** - * {@inheritDoc} - */ - public ThreadGroup getHomeThreadGroup() { - return threadGroup; - } - - /** - * Discover advertisements. - * - * @param discovery The discovery service to use. - * @param type the Discovery advertisement type. - * @param attr The attribute to search for or {@code null}. - * @param value The attribute value to match or {@code null}. - * @param seconds The number of seconds to search. - * @param thisClass The Advertisement class which the advertisement must - * match. - * @return a Collection of advertisements - */ - private Collection discoverSome(DiscoveryService discovery, int type, String attr, String value, int seconds, Class thisClass) { - long discoverUntil = TimeUtils.toAbsoluteTimeMillis(seconds * TimeUtils.ASECOND); - long lastRemoteAt = 0; // no previous remote discovery made. - - List results = new ArrayList(); - - try { - do { - Enumeration res = discovery.getLocalAdvertisements(type, attr, value); - - while (res.hasMoreElements()) { - Advertisement a = res.nextElement(); - - if (thisClass.isInstance(a)) { - results.add(a); - } - } - - if (!results.isEmpty()) { - break; - } - - if (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), lastRemoteAt) > (30 * TimeUtils.ASECOND)) { - discovery.getRemoteAdvertisements(null, type, attr, value, 20); - lastRemoteAt = TimeUtils.timeNow(); - } - - // snooze waiting for responses to come in. - Thread.sleep(1000); - } while (TimeUtils.timeNow() < discoverUntil); - } catch (Exception whatever) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure during discovery", whatever); - } - } - - return results; - } - - /** - * Discover an advertisement within the local peer group. - * - * @param type the Discovery advertisement type. - * @param attr The attribute to search for or {@code null}. - * @param value The attribute value to match or {@code null}. - * @param seconds The number of seconds to search. - * @param thisClass The Advertisement class which the advertisement must match. - * @return a Collection of advertisements - */ - private Advertisement discoverOne(int type, String attr, String value, int seconds, Class thisClass) { - Iterator res = discoverSome(discovery, type, attr, value, seconds, thisClass).iterator(); - - if (!res.hasNext()) { - return null; - } - return res.next(); - } - - /** - * Shortcuts to the standard basic services. - * - * @param mcid The Module Class ID of the service. - * @param service The service instance to set as the shortcut or - * {@code null} to clear the shortcut. - */ - private void setShortCut(ModuleClassID mcid, Service service) { - if (endpointClassID.equals(mcid)) { - endpoint = (EndpointService) service; - return; - } - if (resolverClassID.equals(mcid)) { - resolver = (ResolverService) service; - return; - } - if (discoveryClassID.equals(mcid)) { - discovery = (DiscoveryService) service; - return; - } - if (pipeClassID.equals(mcid)) { - pipe = (PipeService) service; - return; - } - if (membershipClassID.equals(mcid)) { - membership = (MembershipService) service; - return; - } - if (peerinfoClassID.equals(mcid)) { - peerinfo = (PeerInfoService) service; - return; - } - if (rendezvousClassID.equals(mcid)) { - rendezvous = (RendezVousService) service; - return; - } - if (accessClassID.equals(mcid)) { - access = (AccessService) service; - } - } - - /** - * Add a service to the collection of known services. - * - * @param mcid The Module Class ID of the service. - * @param service The service instance to set as the shortcut or - */ - protected synchronized void addService(ModuleClassID mcid, Service service) { - if (stopping) { - return; - } - - if (services.containsKey(mcid)) { - throw new IllegalStateException("Service" + mcid + " already registered."); - } - - services.put(mcid, service); - - setShortCut(mcid, service); - } - - /** - * {@inheritDoc} - */ - synchronized public Service lookupService(ID mcid) throws ServiceNotFoundException { - Service p = services.get(mcid); - - if (p == null) { - throw new ServiceNotFoundException("Not found: " + mcid.toString()); - } - - return p.getInterface(); - } - - /** - * {@inheritDoc} - *

            - * Group implementations do not have to support mapping. - * it would be nice to separate better Interfaces, so that - * Interface Objects can do things that the real service does - * not have to implement. - */ - public Service lookupService(ID mcid, int roleIndex) throws ServiceNotFoundException { - - // If the role number is != 0, it can't be honored: we - // do not have an explicit map. - - if (roleIndex != 0) { - throw new ServiceNotFoundException("Not found: " + mcid + "[" + roleIndex + "]"); - } - - return lookupService(mcid); - } - - /** - * {@inheritDoc} - */ - public Iterator getRoleMap(ID name) { - // No translation; use the given name in a singleton. - return Collections.singletonList(name).iterator(); - } - - /** - * check that all required core services are registered - * - * @throws ServiceNotFoundException If a required service was not found. - */ - protected void checkServices() throws ServiceNotFoundException { - Service ignored; - - ignored = lookupService(endpointClassID); - ignored = lookupService(resolverClassID); - ignored = lookupService(membershipClassID); - ignored = lookupService(accessClassID); - - /** - * ignored = lookupService(discoveryClassID); - * ignored = lookupService(pipeClassID); - * ignored = lookupService(rendezvousClassID); - * ignored = lookupService(peerinfoClassID); - */ - } - - /** - * Ask a group to unregister and unload a service - * - * @param mcid The service to be removed. - * @throws ServiceNotFoundException if service is not found - */ - protected synchronized void removeService(ModuleClassID mcid) throws ServiceNotFoundException { - setShortCut(mcid, null); - - Service p = services.remove(mcid); - - if (p == null) { - throw new ServiceNotFoundException("Not found: " + mcid.toString()); - } - - p.stopApp(); - - // service.terminate(); FIXME. We probably need a terminate() - // method. - // FIXME: [jice@jxta.org 20011013] to make sure the service is - // no-longer referenced, we should always return interfaces, and - // have a way to cut the reference to the real service in the - // interfaces. One way of doing that would be to have to levels - // of indirection: we should keep one and return references to it. - // when we want to cut the service loose, we should clear the - // reference from the interface that we own before letting it go. - // We need to study the consequences of doing that before implementing - // it. - } - - /** - * {@inheritDoc} - */ - public Module loadModule(ID assigned, Advertisement impl) throws ProtocolNotSupportedException, PeerGroupException { - return loadModule(assigned, (ModuleImplAdvertisement) impl, false); - } - - /** - * Load a Module from a ModuleImplAdv. - *

            - * Compatibility is checked and load is attempted. If compatible and - * loaded successfully, the resulting Module is initialized and returned. - * In most cases the other loadModule() method should be preferred, since - * unlike this one, it will seek many compatible implementation - * advertisements and try them all until one works. The home group of the new - * module (its' parent group if the new Module is a group) will be this group. - * - * @param assigned Id to be assigned to that module (usually its ClassID). - * @param implAdv An implementation advertisement for that module. - * @param privileged If {@code true} then the module is provided the true - * group obj instead of just an interface to the group object. This is - * normally used only for the group's defined services and applications. - * @return Module the module loaded and initialized. - * @throws ProtocolNotSupportedException The module is incompatible. - * @throws PeerGroupException The module could not be loaded or initialized - */ - protected Module loadModule(ID assigned, ModuleImplAdvertisement implAdv, boolean privileged) throws ProtocolNotSupportedException, PeerGroupException { - - Element compat = implAdv.getCompat(); - - if (null == compat) { - throw new IllegalArgumentException("No compatibility statement for : " + assigned); - } - - if (!compatible(compat)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Incompatible Module : " + assigned); - } - - throw new ProtocolNotSupportedException("Incompatible Module : " + assigned); - } - - Module newMod = null; - - if ((null != implAdv.getCode()) && (null != implAdv.getUri())) { - try { - // Good one. Try it. - Class clazz; - - try { - clazz = (Class) loader.findClass(implAdv.getModuleSpecID()); - } catch (ClassNotFoundException notLoaded) { - clazz = (Class) loader.defineClass(implAdv); - } - - if (null == clazz) { - throw new ClassNotFoundException("Cannot load class (" + implAdv.getCode() + ") : " + assigned); - } - - newMod = clazz.newInstance(); - - newMod.init(privileged ? this : (PeerGroup) getInterface(), assigned, implAdv); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info( "Loaded" + (privileged ? " privileged" : "") + - " module : " + implAdv.getDescription() + " (" + implAdv.getCode() + ")"); - } - } catch (Exception ex) { - try { - newMod.stopApp(); - } catch (Throwable ignored) { - // If this does not work, nothing needs to be done. - } - throw new PeerGroupException("Could not load module for : " + assigned + " (" + implAdv.getDescription() + ")", ex); - } - } else { - String error; - - if (null == implAdv.getCode()) { - error = "ModuleImpAdvertisement missing Code element"; - } else if (null == implAdv.getUri()) { - error = "ModuleImpAdvertisement missing URI element"; - } else { - error = "ModuleImpAdvertisement missing both Code and URI elements"; - } - throw new PeerGroupException("Can not load module : " + error + " for" + assigned); - } - - // Publish or renew the lease of this adv since we're using it. - try { - if (discovery != null) { - discovery.publish(implAdv, DEFAULT_LIFETIME, DEFAULT_EXPIRATION); - } - } catch (Exception ignored) {// ignored - } - - // If we reached this point we're done. - return newMod; - } - - /** - * {@inheritDoc} - */ - public Module loadModule(ID assigned, ModuleSpecID specID, int where) { - return loadModule(assigned, specID, where, false); - } - - /** - * Load a module from a ModuleSpecID - *

            - * Advertisement is sought, compatibility is checked on all candidates and - * load is attempted. The first one that is compatible and loads - * successfully is initialized and returned. - * - * @param assignedID Id to be assigned to that module (usually its ClassID). - * @param specID The specID of this module. - * @param where May be one of: {@code Here}, {@code FromParent}, or - * {@code Both}, meaning that the implementation advertisement will be - * searched in this group, its parent or both. As a general guideline, the - * implementation advertisements of a group should be searched in its - * prospective parent (that is Here), the implementation advertisements of a - * group standard service should be searched in the same group than where - * this group's advertisement was found (that is, FromParent), while - * applications may be sought more freely (Both). - * @param privileged If {@code true} then the module is provided the true - * group obj instead of just an interface to the group object. This is - * normally used only for the group's defined services and applications. - * @return Module the new module, or {@code null} if no usable implementation was found. - */ - protected Module loadModule(ID assignedID, ModuleSpecID specID, int where, boolean privileged) { - - List allModuleImplAdvs = new ArrayList(); - - ModuleImplAdvertisement loadedImplAdv = loader.findModuleImplAdvertisement(specID); - if(null != loadedImplAdv) { - // We already have a module defined for this spec id. Use that. - allModuleImplAdvs.add(loadedImplAdv); - } else { - // Search for a module to use. - boolean fromHere = (where == Here || where == Both); - boolean fromParent = (where == FromParent || where == Both); - - if (fromHere && (null != discovery)) { - Collection here = discoverSome(discovery, DiscoveryService.ADV, - "MSID", specID.toString(), 120, ModuleImplAdvertisement.class); - - allModuleImplAdvs.addAll(here); - } - - if (fromParent && (null != getParentGroup()) && (null != parentGroup.getDiscoveryService())) { - Collection parent = discoverSome(parentGroup.getDiscoveryService(), DiscoveryService.ADV, - "MSID", specID.toString(), 120, ModuleImplAdvertisement.class); - - allModuleImplAdvs.addAll(parent); - } - } - - Throwable recentFailure = null; - - for (Advertisement eachAdv : allModuleImplAdvs) { - if( !(eachAdv instanceof ModuleImplAdvertisement) ) { - continue; - } - - ModuleImplAdvertisement foundImpl = (ModuleImplAdvertisement) eachAdv; - - try { - // First check that the MSID is really the one we're looking for. - // It could have appeared somewhere else in the adv than where - // we're looking, and discovery doesn't know the difference. - if (!specID.equals(foundImpl.getModuleSpecID())) { - continue; - } - - Module newMod = loadModule(assignedID, foundImpl, privileged); - - // If we reach that point, the module is good. - return newMod; - } catch (ProtocolNotSupportedException failed) { - // Incompatible implementation. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Incompatbile impl adv"); - } - } catch (PeerGroupException failed) { - // Initialization failure. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Initialization failed", failed); - } - } catch (Throwable e) { - recentFailure = e; - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Not a usable impl adv: ", e); - } - } - } - - // Throw an exception if there was a recent failure. - if (null != recentFailure) { - if (recentFailure instanceof Error) { - throw (Error) recentFailure; - } else if (recentFailure instanceof RuntimeException) { - throw (RuntimeException) recentFailure; - } else { - throw new UndeclaredThrowableException(recentFailure); - } - } - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not find a loadable implementation for SpecID: " + specID); - } - - return null; - } - - /** - * {@inheritDoc} - */ - public ConfigParams getConfigAdvertisement() { - return configAdvertisement; - } - - /** - * Sets the configuration advertisement for this peer group. - * - * @param config The configuration advertisement which will be used for - * this peer group or {@code null} if no configuration advertisement is to - * be used. - */ - protected void setConfigAdvertisement(ConfigParams config) { - configAdvertisement = config; - } - - /** - * Adds configuration parameters for the specified group. The configuration - * parameters remain cached until either the specified group is started or - * the parameters are replaced. - * - * @param groupid The group for who's params are being provided. - * @param params The parameters to be provided to the peer group when it is - * created. - */ - public static void setGroupConfigAdvertisement(ID groupid, ConfigParams params) { - if( null != params) { - group_configs.put(groupid, params); - } else { - group_configs.remove(groupid); - } - } - - /* - * Now comes the implementation of the public API, including the - * API mandated by the Service interface. - */ - - /** - * {@inheritDoc} - *

            - * It is not recommended to overload this method. Instead, subclassers - * should overload either or both of - * {@link #initFirst(PeerGroup,ID,Advertisement)} and {@link #initLast()}. - * If this method is to be overloaded, the overloading method must - * invoke super.init. - *

            - * This method invokes initFirst - * with identical parameters. initLast does not take - * parameters since the relevant information can be obtained from the - * group following completion of the initFirst phase. - * The resulting values may be different from the parameters to - * initFirst since initFirst may - * be overLoaded and the overloading method may modify these parameters - * when calling super.initFirst. (See - * {@link net.jxta.impl.peergroup.Platform} for an example of such a case). - *

            - * Upon completion, the group object is marked as completely initialized - * in all cases. Once a group object is completely initialized, it becomes - * sensitive to reference counting. - *

            - * In the future this method may become final. - */ - public void init(PeerGroup homeGroup, ID assignedID, Advertisement impl) throws PeerGroupException { - try { - initFirst(homeGroup, assignedID, impl); - initLast(); - } finally { - // This must be done in all cases. - initComplete = true; - } - } - - /** - * Performs all initialization steps that need to be performed - * before any subclass initialization is performed. - *

            - * Classes that override this method should always call - * super.initFirst() before doing - * any of their own work. - * - * @param homeGroup The group that serves as a parent to this group. - * @param assignedID The unique ID assigned to this module. For - * group this is the group ID or null if a group ID - * has not yet been assigned. If null is passed, GenericPeerGroup - * will generate a new group ID. - * @param impl The ModuleImplAdvertisement which defines this - * group's implementation. - * @throws PeerGroupException if a group initialization error occurs - */ - protected void initFirst(PeerGroup homeGroup, ID assignedID, Advertisement impl) throws PeerGroupException { - - this.implAdvertisement = (ModuleImplAdvertisement) impl; - this.parentGroup = homeGroup; - - if (null != parentGroup) { - jxtaHome = parentGroup.getStoreHome(); - } - - // Set the peer configuration before we start. - if((null != assignedID) && (null == getConfigAdvertisement())) { - setConfigAdvertisement(group_configs.remove(assignedID)); - } - - try { - // FIXME 20030919 bondolo@jxta.org This setup doesnt give us any - // capability to use seed material or parent group. - if (null == assignedID) { - if ("cbid".equals(IDFactory.getDefaultIDFormat())) { - throw new IllegalStateException("Cannot generate group id for cbid group"); - } else { - assignedID = IDFactory.newPeerGroupID(); - } - } else { - if (parentGroup != null) { - DiscoveryService disco = parentGroup.getDiscoveryService(); - if (null != disco) { - Enumeration found = disco.getLocalAdvertisements(DiscoveryService.GROUP, "GID", assignedID.toString()); - if (found.hasMoreElements()) { - peerGroupAdvertisement = (PeerGroupAdvertisement) found.nextElement(); - } - } - } - } - - if (!(assignedID instanceof PeerGroupID)) { - throw new PeerGroupException("assignedID must be a peer group ID"); - } - - peerAdvertisement.setPeerGroupID((PeerGroupID) assignedID); - - // // make sure the parent group is the required group - // if (null != peerAdvertisement.getPeerGroupID().getParentPeerGroupID()) { - // if (null == parentGroup) { - // throw new PeerGroupException("Group requires parent group : " + peerAdvertisement.getPeerGroupID().getParentPeerGroupID()); - // } else if (!parentGroup.getPeerGroupID().equals(peerAdvertisement.getPeerGroupID().getParentPeerGroupID())) { - // throw new PeerGroupException("Group requires parent group : " + peerAdvertisement.getPeerGroupID().getParentPeerGroupID() + ". Provided parent was : " + parentGroup.getPeerGroupID()); - // } - // } - - // Do our part of the PeerAdv construction. - if ((configAdvertisement != null) && (configAdvertisement instanceof PlatformConfig)) { - PlatformConfig platformConfig = (PlatformConfig) configAdvertisement; - - // Normally there will be a peer ID and a peer name in the config. - PeerID configPID = platformConfig.getPeerID(); - - if ((null == configPID) || (ID.nullID == configPID)) { - if ("cbid".equals(IDFactory.getDefaultIDFormat())) { - // Get our peer-defined parameters in the configAdv - XMLElement param = (XMLElement) platformConfig.getServiceParam(PeerGroup.membershipClassID); - - if (null == param) { - throw new IllegalArgumentException(PSEConfigAdv.getAdvertisementType() + " could not be located"); - } - - Advertisement paramsAdv = null; - try { - paramsAdv = AdvertisementFactory.newAdvertisement(param); - } catch (NoSuchElementException noadv) {// ignored - } - if (!(paramsAdv instanceof PSEConfigAdv)) { - throw new IllegalArgumentException( - "Provided Advertisement was not a " + PSEConfigAdv.getAdvertisementType()); - } - - PSEConfigAdv config = (PSEConfigAdv) paramsAdv; - Certificate clientRoot = config.getCertificate(); - byte[] pub_der = clientRoot.getPublicKey().getEncoded(); - - platformConfig.setPeerID(IDFactory.newPeerID((PeerGroupID) assignedID, pub_der)); - } else { - platformConfig.setPeerID(IDFactory.newPeerID((PeerGroupID) assignedID)); - } - } - - peerAdvertisement.setPeerID(platformConfig.getPeerID()); - peerAdvertisement.setName(platformConfig.getName()); - peerAdvertisement.setDesc(platformConfig.getDesc()); - } else { - if (null == parentGroup) { - // If we did not get a valid peer id, we'll initialize it here. - peerAdvertisement.setPeerID(IDFactory.newPeerID((PeerGroupID) assignedID)); - } else { - // We're not the world peer group, which is the authoritative source of these values. - peerAdvertisement.setPeerID(parentGroup.getPeerAdvertisement().getPeerID()); - peerAdvertisement.setName(parentGroup.getPeerAdvertisement().getName()); - peerAdvertisement.setDesc(parentGroup.getPeerAdvertisement().getDesc()); - } - } - - if (peerGroupAdvertisement == null) { - // No existing gadv. OK then we're creating the group or we're - // the platform, it seems. Start a grp adv with the essentials - // that we know. - peerGroupAdvertisement = (PeerGroupAdvertisement) - AdvertisementFactory.newAdvertisement(PeerGroupAdvertisement.getAdvertisementType()); - - peerGroupAdvertisement.setPeerGroupID((PeerGroupID) assignedID); - peerGroupAdvertisement.setModuleSpecID(implAdvertisement.getModuleSpecID()); - } else { - published = true; - } - - // If we still do not have a config adv, make one with the minimal info in it. - // All groups but the Platform and the netPG are in that case. - // In theory a plain ConfigParams would be enough for subgroups. But for now - // GenericPeerGroup always has a full Platformconfig and there is no other concrete - // ConfigParams subclass. - if (configAdvertisement == null) { - PlatformConfig conf = (PlatformConfig) AdvertisementFactory.newAdvertisement(PlatformConfig.getAdvertisementType()); - - conf.setPeerID(peerAdvertisement.getPeerID()); - conf.setName(peerAdvertisement.getName()); - conf.setDesc(peerAdvertisement.getDesc()); - configAdvertisement = conf; - } - - // Merge service params with those specified by the group (if any). The only - // policy, right now, is to give peer params the precedence over group params. - Hashtable grpParams = peerGroupAdvertisement.getServiceParams(); - Enumeration keys = grpParams.keys(); - - while (keys.hasMoreElements()) { - ID key = (ID) keys.nextElement(); - Element e = (Element) grpParams.get(key); - - if (configAdvertisement.getServiceParam(key) == null) { - configAdvertisement.putServiceParam(key, e); - } - } - - /* - * Now seems like the right time to attempt to register the group. - * The only trouble is that it could cause the group to - * be used before all the services are initialized, but on the - * other hand, we do not want to let a redundant group go through - * it's service initialization because that would cause irreparable - * damage to the legitimate instance. There should be a synchro on - * on the get() and lookupService() routines. - */ - if (!globalRegistry.registerInstance((PeerGroupID) assignedID, this)) { - throw new PeerGroupException("Group already instantiated"); - } - } catch (Throwable any) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Group init failed", any); - } - - if (any instanceof Error) { - throw (Error) any; - } else if (any instanceof RuntimeException) { - throw (RuntimeException) any; - } else if (any instanceof PeerGroupException) { - throw (PeerGroupException) any; - } - - throw new PeerGroupException("Group init failed", any); - } - - ThreadGroup parentThreadGroup = (null != this.parentGroup) - ? parentGroup.getHomeThreadGroup() - : Thread.currentThread().getThreadGroup(); - - threadGroup = new ThreadGroup(parentThreadGroup, "Group " + peerGroupAdvertisement.getPeerGroupID()); - - taskQueue = new ArrayBlockingQueue(COREPOOLSIZE * 2); - threadPool = new ThreadPoolExecutor(COREPOOLSIZE, MAXPOOLSIZE, - KEEPALIVETIME, TimeUnit.SECONDS, - taskQueue, - new PeerGroupThreadFactory("Executor", getHomeThreadGroup()), - new CallerBlocksPolicy()); - - // Try to allow core threads to idle out. (Requires a 1.6 method) - try { - Method allowCoreThreadTimeOut = threadPool.getClass().getMethod("allowCoreThreadTimeOut", boolean.class); - - allowCoreThreadTimeOut.invoke(threadPool, Boolean.TRUE); - } catch(Throwable ohWell) { - // Our attempt failed. - if (Logging.SHOW_FINEST && LOG.isLoggable(Level.FINEST)) { - LOG.log(Level.FINEST, "Failed to enable 'allowCoreThreadTimeOut'", ohWell); - } - } - - scheduledExecutor = new ScheduledThreadPoolExecutor(1, - new PeerGroupThreadFactory("Scheduled Executor", getHomeThreadGroup())); - - /* - * The rest of construction and initialization are left to the - * group subclass, between here and the begining for initLast. - * That should include instanciating and setting the endpoint, and - * finally supplying it with endpoint protocols. - * That also includes instanciating the appropriate services - * and registering them. - * For an example, see the StdPeerGroup class. - */ - } - - /** - * Perform all initialization steps that need to be performed - * after any subclass initialization is performed. - *

            - * Classes that override this method should always call super.initLast - * after doing any of their own work. - * @throws PeerGroupException if a group initialization error occurs - */ - protected void initLast() throws PeerGroupException { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Group : " + getPeerGroupID()); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tModule Spec ID : ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tPeer Group ID : ").append(getPeerGroupID()); - configInfo.append("\n\t\tGroup Name : ").append(getPeerGroupName()); - configInfo.append("\n\t\tPeer ID in Group : ").append(getPeerID()); - configInfo.append("\n\tConfiguration :"); - if (null == parentGroup) { - configInfo.append("\n\t\tHome Group : (none)"); - } else { - configInfo.append("\n\t\tHome Group : \"").append(parentGroup.getPeerGroupName()).append("\" / ").append( - parentGroup.getPeerGroupID()); - } - configInfo.append("\n\t\tServices :"); - for (Map.Entry anEntry : services.entrySet()) { - ModuleClassID aMCID = anEntry.getKey(); - ModuleImplAdvertisement anImplAdv = (ModuleImplAdvertisement) anEntry.getValue().getImplAdvertisement(); - - configInfo.append("\n\t\t\t").append(aMCID).append("\t").append(anImplAdv.getDescription()); - } - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] arg) { - return Module.START_OK; - } - - /** - * {@inheritDoc} - *

            - * PeerGroupInterface's stopApp() does nothing. Only a real reference to the - * group object permits to stop it without going through ref counting. - */ - public void stopApp() { - stopping = true; - - Collection allServices = new ArrayList(services.keySet()); - - // Stop and remove all remaining services. - for (ModuleClassID aService : allServices) { - try { - removeService(aService); - } catch (Exception failure) { - LOG.log(Level.WARNING, "Failure shutting down service : " + aService, failure); - } - } - - if (!services.isEmpty()) { - LOG.warning(services.size() + " services could not be shut down during peer group stop."); - } - - // remove everything (just in case); - services.clear(); - - globalRegistry.unRegisterInstance(peerGroupAdvertisement.getPeerGroupID(), this); - - // Explicitly unreference our parent group in order to allow it - // to terminate if this group object was itself the last reference - // to it. - if (parentGroup != null) { - parentGroup.unref(); - parentGroup = null; - } - - // shutdown the threadpool - threadPool.shutdownNow(); - scheduledExecutor.shutdownNow(); - - // No longer initialized. - initComplete = false; - } - - /** - * {@inheritDoc} - *

            - * May be called by a module which has a direct reference to the group - * object and wants to notify its abandoning it. Has no effect on the real - * group object. - */ - public void unref() {} - - /** - * Called every time an interface object that refers to this group - * goes away, either by being finalized or by its unref() method being - * invoked explicitly. - */ - protected void decRefCount() { - synchronized (this) { - --masterRefCount; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - Throwable trace = new Throwable("Stack Trace"); - StackTraceElement elements[] = trace.getStackTrace(); - LOG.info("[" + getPeerGroupID() + "] GROUP REF COUNT DECCREMENTED TO: " + masterRefCount + " by\n\t" + elements[2]); - } - - if (masterRefCount != 0) { - return; - } - - if (!stopWhenUnreferenced) { - return; - } - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("[" + getPeerGroupID() + "] STOPPING UNREFERENCED GROUP"); - } - - stopApp(); - masterRefCount = Integer.MIN_VALUE; - } - - /* - * Implement the Service API so that we can make groups services when we - * decide to. - */ - - /** - * {@inheritDoc} - */ - public Service getInterface() { - synchronized (this) { - ++masterRefCount; - - if (masterRefCount < 1) { - throw new IllegalStateException("Group has been shutdown. getInterface() is not available"); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - Throwable trace = new Throwable("Stack Trace"); - StackTraceElement elements[] = trace.getStackTrace(); - - LOG.info("[" + getPeerGroupID() + "] GROUP REF COUNT INCREMENTED TO: " + masterRefCount + " by\n\t" + elements[2]); - } - - if (initComplete) { - // If init is complete the group can become sensitive to - // its ref count reaching zero. Before there could be - // transient references before there is a chance to give - // a permanent reference to the invoker of newGroup. - stopWhenUnreferenced = true; - } - } - - return new RefCountPeerGroupInterface(this); - } - - /** - * {@inheritDoc} - */ - public PeerGroup getWeakInterface() { - return new PeerGroupInterface(this); - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return implAdvertisement.clone(); - } - - /** - * {@inheritDoc} - */ - public void publishGroup(String name, String description) throws IOException { - - if (published) { - return; - } - - peerGroupAdvertisement.setName(name); - peerGroupAdvertisement.setDescription(description); - - if (parentGroup == null) { - return; - } - - DiscoveryService parentDiscovery = parentGroup.getDiscoveryService(); - - if (null == parentDiscovery) { - return; - } - - parentDiscovery.publish(peerGroupAdvertisement, DEFAULT_LIFETIME, DEFAULT_EXPIRATION); - published = true; - } - - /** - * {@inheritDoc} - */ - public PeerGroup newGroup(Advertisement pgAdv) throws PeerGroupException { - - PeerGroupAdvertisement adv = (PeerGroupAdvertisement) pgAdv; - PeerGroupID gid = adv.getPeerGroupID(); - - if ((gid == null) || ID.nullID.equals(gid)) { - throw new IllegalArgumentException("Advertisement did not contain a peer group ID"); - } - - PeerGroup theNewGroup = globalRegistry.lookupInstance(gid); - - if (theNewGroup != null) { - return theNewGroup; - } - - // We do not know if the grp adv had been previously published or not... Since it may contain information essential to - // the configuration of services, we need to make sure it is published localy, rather than letting the group publish - // itself after the fact. - - // FIXME jice@jxta.org 20040713 : The downside is that we're publishing the adv even before making sure that this group - // can really be instantiated. We're basically using the cm as a means to pass parameters to the module because it is a - // group. We have the same parameter issue with the config adv. Eventually we need to find a clean way of passing - // parameters specific to a certain types of module. - - try { - discovery.publish(adv, DEFAULT_LIFETIME, DEFAULT_EXPIRATION); - } catch (Exception any) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not publish the group advertisement: ", any); - } - } - - theNewGroup = (PeerGroup) loadModule(adv.getPeerGroupID(), adv.getModuleSpecID(), Here, false); - - if (theNewGroup == null) { - throw new PeerGroupException("Could not find group implementation with " + adv.getModuleSpecID()); - } - - return (PeerGroup) theNewGroup.getInterface(); - } - - /** - * {@inheritDoc} - */ - public PeerGroup newGroup(PeerGroupID gid, Advertisement impl, String name, String description) throws PeerGroupException { - PeerGroup theNewGroup = null; - - if (null != gid) { - theNewGroup = globalRegistry.lookupInstance(gid); - } - - if (theNewGroup != null) { - return theNewGroup; - } - - try { - theNewGroup = (PeerGroup) loadModule(gid, (ModuleImplAdvertisement) impl, false); - } catch (Throwable any) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Could not load group implementation", any); - } - - throw new PeerGroupException("Could not load group implementation", any); - } - - try { - // The group adv definitely needs to be published. - theNewGroup.publishGroup(name, description); - } catch (Exception any) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not publish group or implementation:", any); - } - } - return (PeerGroup) theNewGroup.getInterface(); - } - - /** - * {@inheritDoc} - */ - public PeerGroup newGroup(PeerGroupID gid) throws PeerGroupException { - - if ((gid == null) || ID.nullID.equals(gid)) { - throw new IllegalArgumentException("Invalid peer group ID"); - } - - PeerGroup result = globalRegistry.lookupInstance(gid); - - if (result != null) { - return result; - } - - PeerGroupAdvertisement adv; - - try { - adv = (PeerGroupAdvertisement) - discoverOne(DiscoveryService.GROUP, "GID", gid.toString(), 120, PeerGroupAdvertisement.class); - } catch (Throwable any) { - throw new PeerGroupException("Failed finding group advertisement for " + gid, any); - } - - if (adv == null) { - throw new PeerGroupException("Could not find group advertisement for group " + gid); - } - - return newGroup(adv); - } - - /** - * {@inheritDoc} - */ - public JxtaLoader getLoader() { - return loader; - } - - /** - * {@inheritDoc} - */ - public String getPeerName() { - // before init we must fail. - if (null == peerAdvertisement) { - throw new IllegalStateException("PeerGroup not sufficiently initialized"); - } - return peerAdvertisement.getName(); - } - - /** - * {@inheritDoc} - */ - public String getPeerGroupName() { - // before init we must fail. - if (null == peerGroupAdvertisement) { - throw new IllegalStateException("PeerGroup not sufficiently initialized"); - } - return peerGroupAdvertisement.getName(); - } - - /** - * {@inheritDoc} - */ - public PeerGroupID getPeerGroupID() { - // before init we must fail. - if (null == peerGroupAdvertisement) { - throw new IllegalStateException("PeerGroup not sufficiently initialized"); - } - - return peerGroupAdvertisement.getPeerGroupID(); - } - - /** - * {@inheritDoc} - */ - public PeerID getPeerID() { - // before init we must fail. - if (null == peerAdvertisement) { - throw new IllegalStateException("PeerGroup not sufficiently initialized"); - } - return peerAdvertisement.getPeerID(); - } - - /** - * {@inheritDoc} - */ - public PeerAdvertisement getPeerAdvertisement() { - return peerAdvertisement; - } - - /** - * {@inheritDoc} - */ - public PeerGroupAdvertisement getPeerGroupAdvertisement() { - return peerGroupAdvertisement; - } - - /** - * {@inheritDoc} - */ - public boolean isRendezvous() { - if (rendezvous == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Rendezvous service null"); - } - } - return (rendezvous != null) && rendezvous.isRendezVous(); - } - - /* - * shortcuts to the well-known services, in order to avoid calls to lookup. - */ - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - if (endpoint == null) { - return null; - } - return (EndpointService) endpoint.getInterface(); - } - - /** - * {@inheritDoc} - */ - public ResolverService getResolverService() { - if (resolver == null) { - return null; - } - return (ResolverService) resolver.getInterface(); - } - - /** - * {@inheritDoc} - */ - public DiscoveryService getDiscoveryService() { - if (discovery == null) { - return null; - } - return (DiscoveryService) discovery.getInterface(); - } - - /** - * {@inheritDoc} - */ - public PeerInfoService getPeerInfoService() { - if (peerinfo == null) { - return null; - } - return (PeerInfoService) peerinfo.getInterface(); - } - - /** - * {@inheritDoc} - */ - public MembershipService getMembershipService() { - if (membership == null) { - return null; - } - return (MembershipService) membership.getInterface(); - } - - /** - * {@inheritDoc} - */ - public PipeService getPipeService() { - if (pipe == null) { - return null; - } - return (PipeService) pipe.getInterface(); - } - - /** - * {@inheritDoc} - */ - public RendezVousService getRendezVousService() { - if (rendezvous == null) { - return null; - } - return (RendezVousService) rendezvous.getInterface(); - } - - /** - * {@inheritDoc} - */ - public AccessService getAccessService() { - if (access == null) { - return null; - } - return (AccessService) access.getInterface(); - } - - /** - * Returns the executor pool - * - * @return the executor pool - */ - public Executor getExecutor() { - return threadPool; - } - - /** - * Returns the scheduled executor. The - * - * @return the scheduled executor - */ - public ScheduledExecutorService getScheduledExecutor() { - // FIXME 20070815 bondolo We should return a proxy object to disable shutdown() - return scheduledExecutor; - } - - /** - * Our rejected execution handler which has the effect of pausing the - * caller until the task can be queued. - */ - private static class CallerBlocksPolicy implements RejectedExecutionHandler { - - private CallerBlocksPolicy() { - } - - /** - * {@inheritDoc} - */ - public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { - BlockingQueue queue = executor.getQueue(); - - while (!executor.isShutdown()) { - executor.purge(); - - try { - boolean pushed = queue.offer(runnable, 500, TimeUnit.MILLISECONDS); - - if (pushed) { - break; - } - } catch (InterruptedException woken) { - throw new RejectedExecutionException("Interrupted while attempting to enqueue", woken); - } - } - } - } - - /** - * Our thread factory that adds the threads to our thread group and names - * the thread to something recognizable. - */ - static class PeerGroupThreadFactory implements ThreadFactory { - final AtomicInteger threadNumber = new AtomicInteger(1); - final String name; - final ThreadGroup threadgroup; - - PeerGroupThreadFactory(String name, ThreadGroup threadgroup) { - this.name = name; - this.threadgroup = threadgroup; - } - - public Thread newThread(Runnable runnable) { - Thread thread = new Thread(threadgroup, runnable, name + " - " + threadNumber.getAndIncrement(), 0); - if(thread.isDaemon()) { - thread.setDaemon(false); - } - if (thread.getPriority() != Thread.NORM_PRIORITY) { - thread.setPriority(Thread.NORM_PRIORITY); - } - return thread; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/IncompleteConfigurationException.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/IncompleteConfigurationException.java deleted file mode 100644 index e08308b9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/IncompleteConfigurationException.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * IncompleteConfigurationException.java - * - * Created on September 13, 2005, 12:11 PM - * - * To change this template, choose Tools | Template Manager - * and open the template in the editor. - */ -package net.jxta.impl.peergroup; - -import net.jxta.exception.ConfiguratorException; - -import java.util.List; - -/** - * A configurator exception which is generated when intervention - */ -public class IncompleteConfigurationException extends ConfiguratorException { - - /** - * Constucts a {@link IncompleteConfigurationException} with no specified details. - */ - public IncompleteConfigurationException() { - super(); - } - - /** - * Constructs a {@link IncompleteConfigurationException} with the specified message. - * - * @param msg message - */ - public IncompleteConfigurationException(String msg) { - super(msg); - } - - /** - * Constructs a {@link IncompleteConfigurationException} with the specified {@link - * java.lang.Throwable cause}. - * - * @param ex cause - */ - public IncompleteConfigurationException(Throwable ex) { - super(ex); - } - - /** - * Constructs a {@link IncompleteConfigurationException} with the specified message and {@link - * java.lang.Throwable cause}. - * - * @param msg message - * @param ex cause - */ - public IncompleteConfigurationException(String msg, Throwable ex) { - super(msg, ex); - } - - /** - * Constructs a {@link IncompleteConfigurationException} with the specified {@link - * java.util.List} of {@link java.lang.Throwable causes}. - * - * @param ex causes - */ - public IncompleteConfigurationException(List ex) { - super(ex); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/NullConfigurator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/NullConfigurator.java deleted file mode 100644 index bc3f0a96..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/NullConfigurator.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.exception.ConfiguratorException; -import net.jxta.impl.protocol.PlatformConfig; -import net.jxta.logging.Logging; -import net.jxta.protocol.ConfigParams; - -import java.io.*; -import java.net.URI; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A minimal Platform Configurator. This implementation can load a - * configuration from an existing PlatformConfig file and also save a - * configuration to the PlatformConfig file. - *

            - * This configurator provides no explict validation of the PlatformConfig - * as it is read from the file (Some is done by the PlatformConfig class) and - * provides no mechanism for reconfiguration. The NullConfigurator provides a - * useful base implementation for extending your own Configurator and also - * provides the minimal implementation needed for applications which perform - * their own configuration. - */ -public class NullConfigurator implements PlatformConfigurator { - - /** - * logger - */ - private final static transient Logger LOG = Logger.getLogger(NullConfigurator.class.getName()); - - /** - * The location in which the configuration files will reside. - */ - protected final URI jxtaHome; - - /** - * The file in which contains the platform configurtation. - */ - protected final URI configFile; - - /** - * The platform config - */ - protected PlatformConfig advertisement = null; - - /** - * Constructor for the NullConfigurator - * - * @param homeRoot The location in which the configuration files will reside. - * @throws ConfiguratorException If there is a problem accessing the configuration information. - */ - public NullConfigurator(URI homeRoot) throws ConfiguratorException { - if (!homeRoot.isAbsolute()) { - throw new IllegalArgumentException("homeRoot must be an absoluteURI"); - } - - jxtaHome = homeRoot; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("JXTA_HOME = " + jxtaHome.toASCIIString()); - } - - if ("file".equalsIgnoreCase(jxtaHome.getScheme())) { - File jxtaHomeDir = new File(jxtaHome); - - if (jxtaHomeDir.exists() && !jxtaHomeDir.isDirectory()) { - throw new IllegalArgumentException("'" + jxtaHomeDir + "' is not a directory."); - } - - if (!jxtaHomeDir.exists()) { - if (!jxtaHomeDir.mkdirs()) { - throw new IllegalStateException("Could not create '" + jxtaHomeDir + "'."); - } - } - - configFile = new File(jxtaHomeDir, "PlatformConfig").toURI(); - } else { - configFile = jxtaHome.resolve("PlatformConfig"); - } - } - - /** - * @inheritDoc - */ - public PlatformConfig getPlatformConfig() throws ConfiguratorException { - advertisement = (PlatformConfig) load(); - - return advertisement; - } - - /** - * @inheritDoc - */ - public final void setPlatformConfig(PlatformConfig config) { - advertisement = config; - } - - /** - * @inheritDoc - */ - public ConfigParams getConfigParams() throws ConfiguratorException { - return getPlatformConfig(); - } - - /** - * @inheritDoc - */ - public void setConfigParams(ConfigParams cp) { - setPlatformConfig((PlatformConfig) cp); - } - - /** - * @inheritDoc - */ - public void setReconfigure(boolean reconfigure) {// This implementation doesn't do configuration so ignores this operation. - } - - /** - * @inheritDoc - */ - public boolean isReconfigure() { - return false; - } - - /** - * {@inheritDoc} - */ - public ConfigParams load() throws ConfiguratorException { - return load(configFile); - } - - /** - * Retrieves the persisted parameters associated with this configuration - * from the standard location. - * - * @param loadFile The location from which the configuration data should be - * loaded. - * @return The configuration parameters. - * @throws ConfiguratorException If there was a failure in retrieving the - * persisted parameters. This is normally a chained exception to the - * underlying cause. - * @deprecated Loading of existing configuration is best accomplished by use - * of specific constructors of the implementing configurator. This method - * complicates the state management of configuration parameters and may have - * unpredictable results depending upon the constructor and configuration - * set methods used prior to it's execution. - */ - @Deprecated - protected PlatformConfig load(URI loadFile) throws ConfiguratorException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Reading Platform Config from : " + loadFile); - } - - InputStream advStream = null; - - try { - advStream = loadFile.toURL().openStream(); - - XMLDocument xmlDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, advStream); - PlatformConfig result = (PlatformConfig) AdvertisementFactory.newAdvertisement(xmlDoc); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Recovered Platform Config from : " + loadFile); - } - - return result; - } catch (FileNotFoundException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Platform Config not found : " + loadFile); - } - - return null; - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to Recover \'" + loadFile + "\' due to : ", e); - } - - throw new ConfiguratorException("Failed to recover PlatformConfig", e); - } finally { - try { - if (advStream != null) { - advStream.close(); - } - advStream = null; - } catch (Exception ignored) {// ignored - } - } - } - - /** - * {@inheritDoc} - */ - public boolean save() throws ConfiguratorException { - return save(configFile); - } - - /** - * Persist the parameters associated with this configuration to the - * specified location. - * - * @param saveFile The location to which the configuration should be saved. - * @return true if the configuration was successfully saved - * otherwise false. If the parameters are not persisted then - * false/code> is returned. - * @throws ConfiguratorException If there was a failure in persisting the - * parameters. This is normally a chained exception to the underlying - * cause. - */ - protected boolean save(URI saveFile) throws ConfiguratorException { - - // Save the adv as input for future reconfiguration - OutputStream out = null; - - try { - XMLDocument aDoc = (XMLDocument) advertisement.getDocument(MimeMediaType.XMLUTF8); - - if ("file".equalsIgnoreCase(saveFile.getScheme())) { - out = new FileOutputStream(new File(saveFile)); - } else { - out = saveFile.toURL().openConnection().getOutputStream(); - } - - OutputStreamWriter os = new OutputStreamWriter(out, "UTF-8"); - - aDoc.sendToWriter(os); - os.flush(); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not save to : " + saveFile, e); - } - - throw new ConfiguratorException("Could not save to : " + saveFile, e); - } finally { - try { - if (null != out) { - out.close(); - } - } catch (Exception ignored) {// ignored - } - out = null; - } - return true; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/PeerGroupInterface.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/PeerGroupInterface.java deleted file mode 100644 index 08b83b46..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/PeerGroupInterface.java +++ /dev/null @@ -1,447 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - -import net.jxta.access.AccessService; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.Element; -import net.jxta.endpoint.EndpointService; -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.ProtocolNotSupportedException; -import net.jxta.exception.ServiceNotFoundException; -import net.jxta.id.ID; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peer.PeerInfoService; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.pipe.PipeService; -import net.jxta.platform.JxtaLoader; -import net.jxta.platform.Module; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.resolver.ResolverService; -import net.jxta.service.Service; -import java.util.logging.Logger; - -import java.io.IOException; -import java.net.URI; -import java.util.Iterator; - -/** - * PeerGroupInterface provides a pure interface object that permits interaction - * with the actual PeerGroup implementation without giving access to the real - * object. - *

            - * This class defines immutable objects. It has no control over the wrapped - * peer group object's life cycle. It serves to make weak PeerGroup interface - * object. - */ -class PeerGroupInterface implements PeerGroup { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(PeerGroupInterface.class.getName()); - - /** - * The peer group instance which backs this interface object. - */ - protected PeerGroup groupImpl; - - /** - * Constructs an interface object that front-ends a given GenericPeerGroup. - * @param theRealThing the real PeerGroup - */ - PeerGroupInterface(PeerGroup theRealThing) { - groupImpl = theRealThing; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object target) { - PeerGroup temp = groupImpl; - - if (null != temp) { - return temp.equals(target); - } else { - return super.equals(target); - } - } - - /** - * {@inheritDoc} - *

            - * An implementation suitable for debugging. Don't try to parse - * this string! All of the information is available from other sources. - */ - @Override - public String toString() { - PeerGroup temp = groupImpl; - - if (null != temp) { - return temp.toString(); - } else { - return super.toString(); - } - } - - /** - * {@inheritDoc} - *

            - * This is here for class hierarchy reasons. It is normaly ignored. By - * definition, the interface object protects the real object's start/stop - * methods from being called. - */ - - public void init(PeerGroup pg, ID assignedID, Advertisement impl) {} - - /** - * {@inheritDoc} - *

            - * This is here for class hierarchy reasons. It is normaly ignored. By - * definition, the interface object protects the real object's start/stop - * methods from being called. - */ - public int startApp(String[] arg) { - return 0; - } - - /** - * {@inheritDoc} - *

            - * This is here for class hierarchy reasons. It is normaly ignored. By - * definition, the interface object protects the real object's start/stop - * methods from being called. - */ - public void stopApp() {} - - /** - * {@inheritDoc} - */ - public Service getInterface() { - return this; - } - - /** - * {@inheritDoc} - */ - public PeerGroup getWeakInterface() { - return this; - } - - /** - * {@inheritDoc} - *

            - * Does nothing. - */ - public void unref() {} - - /** - * {@inheritDoc} - */ - public Advertisement getImplAdvertisement() { - return groupImpl.getImplAdvertisement(); - } - - /** - * {@inheritDoc} - */ - public ThreadGroup getHomeThreadGroup() { - return groupImpl.getHomeThreadGroup(); - } - - /** - * {@inheritDoc} - */ - public URI getStoreHome() { - return groupImpl.getStoreHome(); - } - - /** - * {@inheritDoc} - */ - public JxtaLoader getLoader() { - return groupImpl.getLoader(); - } - - /** - * {@inheritDoc} - */ - public boolean isRendezvous() { - return groupImpl.isRendezvous(); - } - - /** - * {@inheritDoc} - */ - public PeerGroupAdvertisement getPeerGroupAdvertisement() { - return groupImpl.getPeerGroupAdvertisement(); - } - - /** - * {@inheritDoc} - */ - public PeerAdvertisement getPeerAdvertisement() { - return groupImpl.getPeerAdvertisement(); - } - - /** - * {@inheritDoc} - */ - public Service lookupService(ID name) throws ServiceNotFoundException { - return groupImpl.lookupService(name); - } - - /** - * {@inheritDoc} - */ - public Service lookupService(ID name, int roleIndex) throws ServiceNotFoundException { - return groupImpl.lookupService(name, roleIndex); - } - - /** - * {@inheritDoc} - */ - public Iterator getRoleMap(ID name) { - return groupImpl.getRoleMap(name); - } - - /** - * {@inheritDoc} - */ - public boolean compatible(Element compat) { - return groupImpl.compatible(compat); - } - - /** - * {@inheritDoc} - *

            - * FIXME 20031103 jice Ideally, we'd need the groupAPI to offer a means to - * loadModule() without making a counted reference, so that group services - * can loadModule() things without preventing group termination. This could - * be achieved elegantly by making this the only behaviour available through - * a weak GroupInterface. So it would be enough to obtain a weak interface - * from one's group and then use its loadmodule method rather than that of - * the strong group reference. However, that's a bit too big a change to be - * decided without more careful consideration. - */ - public Module loadModule(ID assignedID, Advertisement impl) throws ProtocolNotSupportedException, PeerGroupException { - return groupImpl.loadModule(assignedID, impl); - } - - /** - * {@inheritDoc} - */ - public Module loadModule(ID assignedID, ModuleSpecID specID, int where) { - return groupImpl.loadModule(assignedID, specID, where); - } - - /** - * {@inheritDoc} - */ - public void publishGroup(String name, String description) throws IOException { - groupImpl.publishGroup(name, description); - } - - /* - * Valuable application helpers: Various methods to instantiate groups. - */ - - /** - * {@inheritDoc} - */ - public PeerGroup newGroup(Advertisement pgAdv) throws PeerGroupException { - return groupImpl.newGroup(pgAdv); - } - - /** - * {@inheritDoc} - */ - public PeerGroup newGroup(PeerGroupID gid, Advertisement impl, String name, String description) throws PeerGroupException { - return groupImpl.newGroup(gid, impl, name, description); - } - - /** - * {@inheritDoc} - */ - public PeerGroup newGroup(PeerGroupID gid) throws PeerGroupException { - return groupImpl.newGroup(gid); - } - - /* - * shortcuts to the well-known services, in order to avoid calls to lookup. - */ - - /** - * {@inheritDoc} - */ - public RendezVousService getRendezVousService() { - return groupImpl.getRendezVousService(); - } - - /** - * {@inheritDoc} - */ - public EndpointService getEndpointService() { - return groupImpl.getEndpointService(); - } - - /** - * {@inheritDoc} - */ - public ResolverService getResolverService() { - return groupImpl.getResolverService(); - } - - /** - * {@inheritDoc} - */ - public DiscoveryService getDiscoveryService() { - return groupImpl.getDiscoveryService(); - } - - /** - * {@inheritDoc} - */ - public PeerInfoService getPeerInfoService() { - return groupImpl.getPeerInfoService(); - } - - /** - * {@inheritDoc} - */ - public MembershipService getMembershipService() { - return groupImpl.getMembershipService(); - } - - /** - * {@inheritDoc} - */ - public PipeService getPipeService() { - return groupImpl.getPipeService(); - } - - /** - * {@inheritDoc} - */ - public AccessService getAccessService() { - return groupImpl.getAccessService(); - } - - /* - * A few convenience methods. This information is available from - * the peer and peergroup advertisement. - */ - - /** - * {@inheritDoc} - */ - public PeerGroupID getPeerGroupID() { - return groupImpl.getPeerGroupID(); - } - - /** - * {@inheritDoc} - */ - public PeerID getPeerID() { - return groupImpl.getPeerID(); - } - - /** - * {@inheritDoc} - */ - public String getPeerGroupName() { - return groupImpl.getPeerGroupName(); - } - - /** - * {@inheritDoc} - */ - public String getPeerName() { - return groupImpl.getPeerName(); - } - - /** - * {@inheritDoc} - */ - public ConfigParams getConfigAdvertisement() { - ConfigParams configAdvertisement = groupImpl.getConfigAdvertisement(); - - if (configAdvertisement == null) { - return null; - } - return configAdvertisement.clone(); - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getAllPurposePeerGroupImplAdvertisement() throws Exception { - return groupImpl.getAllPurposePeerGroupImplAdvertisement(); - } - - public PeerGroup getParentGroup() { - return groupImpl.getParentGroup(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/Platform.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/Platform.java deleted file mode 100644 index b35dacbf..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/Platform.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.exception.JxtaError; -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.ServiceNotFoundException; -import net.jxta.id.ID; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.platform.JxtaLoader; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; - -import net.jxta.impl.endpoint.cbjx.CbJxDefs; -import net.jxta.impl.endpoint.mcast.McastTransport; -import net.jxta.impl.membership.pse.PSEMembershipService; -import net.jxta.service.Service; - -/** - * Provides the implementation for the World PeerGroup. The World peer group - * differs from other peer groups in the following ways : - *

              - *
            • The World Peer Group has no parent. It is the primordial peer group. - *
            • - *
            • The World Peer Group provides the default definition for the Network - * Peer Group. Peers are free to use alternate implementations for the - * Network PeerGroup.
            • - *
            • The World Peer Group is initialized with configuration parameters and - * the store home location.
            • - *
            - */ -public class Platform extends StdPeerGroup { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(Platform.class.getName()); - - /** - * Create and populate the default module impl Advertisement for this class. - * - * @return The default module impl advertisement for this class. - */ - public static ModuleImplAdvertisement getDefaultModuleImplAdvertisement() { - ModuleImplAdvertisement implAdv = mkImplAdvBuiltin(PeerGroup.refPlatformSpecID, Platform.class.getName(), "Standard World PeerGroup Reference Implementation"); - - // Build the param section now. - StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv(); - - // Do the Services - - // "Core" Services - paramAdv.addService(PeerGroup.endpointClassID, PeerGroup.refEndpointSpecID); - paramAdv.addService(PeerGroup.resolverClassID, PeerGroup.refResolverSpecID); - paramAdv.addService(PeerGroup.membershipClassID, PeerGroup.refMembershipSpecID); - paramAdv.addService(PeerGroup.accessClassID, PeerGroup.refAccessSpecID); - - // "Standard" Services - - paramAdv.addService(PeerGroup.discoveryClassID, PeerGroup.refDiscoverySpecID); - paramAdv.addService(PeerGroup.rendezvousClassID, PeerGroup.refRendezvousSpecID); - paramAdv.addService(PeerGroup.peerinfoClassID, PeerGroup.refPeerinfoSpecID); - - // Do the Message Transports - - paramAdv.addProto(PeerGroup.tcpProtoClassID, PeerGroup.refTcpProtoSpecID); - paramAdv.addProto(PeerGroup.httpProtoClassID, PeerGroup.refHttpProtoSpecID); - paramAdv.addProto(McastTransport.MCAST_TRANSPORT_CLASSID, McastTransport.MCAST_TRANSPORT_SPECID); - - // Do the Applications - - // (none) - - // Insert the paramAdv in the World PeerGroup Impl Advertisement. - implAdv.setParam((XMLDocument) paramAdv.getDocument(MimeMediaType.XMLUTF8)); - - return implAdv; - } - - /** - * This constructor was originally the standard constructor and must be - * retained in case the World PeerGroup is accidentally instantiated via - * the module loading infrastructure. - * - * @throws PeerGroupException if an initialization error occurs - */ - public Platform() throws PeerGroupException { - throw new JxtaError("Zero params constructor is no longer supported for World PeerGroup class."); - } - - /** - * Default constructor - * - * @param config The configuration. - * @param storeHome Persistent store home. - */ - public Platform(ConfigParams config, URI storeHome) { - // initialize the store location. - setStoreHome(storeHome); - - // initialize the configuration advertisement. - setConfigAdvertisement(config); - } - - /** - * {@inheritDoc} - */ - @Override - protected synchronized void initFirst(PeerGroup nullParent, ID assignedID, Advertisement impl) throws PeerGroupException { - if (initComplete) { - LOG.severe("You cannot initialize more than one World PeerGroup!"); - throw new PeerGroupException("You cannot initialize more than one World PeerGroup!"); - } - - if (nullParent != null) { - LOG.severe("World PeerGroup cannot be instantiated with a parent group!"); - throw new PeerGroupException("World PeerGroup cannot be instantiated with a parent group!"); - } - - ModuleImplAdvertisement implAdv = (ModuleImplAdvertisement) impl; - - if(null == implAdv) { - implAdv = getJxtaLoader().findModuleImplAdvertisement(getClass()); - } - - if (null != jxtaHome) { - try { - URL downloadablesURL = jxtaHome.resolve("Downloaded/").toURL(); - - getJxtaLoader().addURL(downloadablesURL); - } catch (MalformedURLException badPath) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not install path for downloadables into JXTA Class Loader."); - } - } - } - - // Initialize the group. - super.initFirst(null, PeerGroupID.worldPeerGroupID, implAdv); - } - - /** - * {@inheritDoc} - */ - @Override - protected synchronized void initLast() throws PeerGroupException { - super.initLast(); - - // Publish our own adv. - try { - publishGroup("World PeerGroup", "Standard World PeerGroup Reference Implementation"); - } catch (IOException e) { - throw new PeerGroupException("Failed to publish World PeerGroup Advertisement", e); - } - } - - /** - * Returns a ModuleImplAdvertisement suitable for the Network Peer Group. - *

            - * The ModuleImplAdvertisement returned differs from the one returned by - * StdPeerGroup in that it has a different specID, name and description, as - * well as the high-level message transports . This definition is always the - * same and has a well known ModuleSpecID. It includes the basic services, - * high-level message transports and the shell for main application. - * - * @return A ModuleImplAdvertisement suitable for the Network Peer Group. - */ - @Override - public ModuleImplAdvertisement getAllPurposePeerGroupImplAdvertisement() { - JxtaLoader loader = getJxtaLoader(); - - // For now, use the well know NPG naming, it is not identical to the - // allPurpose PG because we use the class ShadowPeerGroup which - // initializes the peer config from its parent. - ModuleImplAdvertisement implAdv = loader.findModuleImplAdvertisement(PeerGroup.refNetPeerGroupSpecID); - - return implAdv; - } - - /** - * {@inheritDoc} - */ - @Override - protected void checkServices() throws ServiceNotFoundException { - super.checkServices(); - Service ignored; - ignored = lookupService(discoveryClassID); - ignored = lookupService(rendezvousClassID); - ignored = lookupService(peerinfoClassID); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/PlatformConfigurator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/PlatformConfigurator.java deleted file mode 100644 index ad4a684a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/PlatformConfigurator.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - - -import net.jxta.exception.ConfiguratorException; -import net.jxta.impl.protocol.PlatformConfig; -import net.jxta.peergroup.Configurator; - - -/** - * Defines a configurator for the JXTA Platform peer group. - * - * @deprecated This interface has been replaced with the {@link net.jxta.platform.NetworkConfigurator}. - */ -@Deprecated -public interface PlatformConfigurator extends Configurator { - - /** - * Retrieve the associated {@link net.jxta.impl.protocol.PlatformConfig} and - * potentially performing any required configuration of the parameters - * before returning. - * - * @return PlatformConfig - * @throws net.jxta.exception.ConfiguratorException If configuration error - * occurs. - */ - public PlatformConfig getPlatformConfig() throws ConfiguratorException; - - /** - * Sets the associated {@link net.jxta.impl.protocol.PlatformConfig}. - * - * @param pc the configuration - */ - public void setPlatformConfig(PlatformConfig pc); - - /** - * Sets the reconfiguration status to the specified status. If - * {@code true} then reconfiguration will be forced the next time the - * {@link net.jxta.impl.protocol.PlatformConfig} is retrieved. - * - * @param forceReconfig If {@code true} then a forced reconfiguration will - * occur the next time {@link #getPlatformConfig()} is called. - */ - public void setReconfigure(boolean forceReconfig); - - /** - * Determine if a forced reconfiguration is set for the next call to - * {@link #getPlatformConfig()}. - * - * @return Returns {@code true} if a forced reconfiguration will occur the - * next time {@link #getPlatformConfig()} is called. - */ - public boolean isReconfigure(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/RefCountPeerGroupInterface.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/RefCountPeerGroupInterface.java deleted file mode 100644 index f7deb226..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/RefCountPeerGroupInterface.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - -import net.jxta.exception.ServiceNotFoundException; -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.service.Service; - -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.Map; - -/** - * RefCountPeerGroupInterface is a PeerGroupInterface object that - * also serves as a peergroup very-strong reference. When the last - * such goes away, the peergroup terminates itself despite the existence - * of aeternal strong references from the various service's threads - * that would prevent it from ever being finalized. - * The alternative: to give only weak references to threads seems impractical. - */ -class RefCountPeerGroupInterface extends PeerGroupInterface { - - private Map roleMap; - - /** - * Constructs an interface object that front-ends a given - * PeerGroup object. - * - * @param theRealThing the peer group - */ - RefCountPeerGroupInterface(GenericPeerGroup theRealThing) { - super(theRealThing); - } - - RefCountPeerGroupInterface(GenericPeerGroup theRealThing, Map roleMap) { - super(theRealThing); - this.roleMap = roleMap; - } - - /** - * {@inheritDoc} - *

            - * Normally it is ignored. By definition, the interface object - * protects the real object's start/stop methods from being called. - *

            - * However we have to make an exception for groups: even the creator - * of a group does not have access to the real object. So the interface - * has to forward startApp to the group, which is responsible for - * ensuring that it is executed only once (if needed). - * - * @param arg A table of strings arguments. - * @return int status indication. - */ - @Override - public int startApp(String[] arg) { - // Unlike our superclass's method, we do call the real - // startApp method. - PeerGroup temp = groupImpl; - - if (null == temp) { - throw new IllegalStateException("This Peer Group interface object has been unreferenced and can no longer be used."); - } - - return temp.startApp(arg); - } - - /** - * {@inheritDoc} - *

            - * This is here for temporary class hierarchy reasons. - * it is normally ignored. By definition, the interface object - * protects the real object's start/stop methods from being called - *

            - * In that case we have to make an exception. Most applications - * currently assume that they do not share the group object and that they do - * refer to the real object directly. They call stopApp to signify their - * intention of no-longer using the group. Now that groups are shared, - * we convert stopApp() to unref() for compatibility. - * We could also just do nothing and let the interface be GC'd but - * calling unref() makes the group go away immediately if not shared, - * which is what applications that call stopApp expect. - */ - @Override - public void stopApp() { - unref(); - } - - /** - * {@inheritDoc} - *

            - * Since THIS is already such an object, it could return itself. - * However, we want the group to know about the number of interfaces - * objects floating around, so, we'll have the group make a new one. - * That way, applications which want to use unref() on interfaces can - * avoid sharing interface objects by using getInterface() as a sort of - * clone with the additional ref-counting semantics. - * - * @return Service An interface object that implements - * this service and nothing more. - */ - @Override - public Service getInterface() { - PeerGroup temp = groupImpl; - if (null == temp) { - throw new IllegalStateException("This Peer Group interface object has been unreferenced and can no longer be used."); - } - return temp.getInterface(); - } - - /** - * {@inheritDoc} - *

            - * Returns a weak interface object that refers to this interface - * object rather than to the group directly. The reason for that - * is that we want the owner of this interface object to be able - * to invalidate all weak interface objects made out of this interface - * object, without them keeping a reference to the group object, and - * without necessarily having to terminate the group. - * - * @return PeerGroup A weak interface object that implements - * this group and nothing more. - */ - - @Override - public PeerGroup getWeakInterface() { - return new PeerGroupInterface(this); - } - - /** - * Can only be called once. After that the reference is no-longer usuable. - */ - @Override - public void unref() { - GenericPeerGroup theGrp; - - synchronized (this) { - if (groupImpl == null) { - return; - } - - theGrp = (GenericPeerGroup) groupImpl; - groupImpl = null; - } - theGrp.decRefCount(); - } - - /** - * Service-specific role mapping is implemented here. - **/ - - /** - * {@inheritDoc} - */ - @Override - public Service lookupService(ID name) throws ServiceNotFoundException { - - return lookupService(name, 0); - } - - /** - * {@inheritDoc} - */ - @Override - public Service lookupService(ID name, int roleIndex) throws ServiceNotFoundException { - - if (roleMap != null) { - ID[] map = (ID[]) roleMap.get(name); - - // If there is a map, remap; else, identity is the default for - // role 0 only; the default mapping has only index 0. - - if (map != null) { - if (roleIndex < 0 || roleIndex >= map.length) { - throw new ServiceNotFoundException(name + "[" + roleIndex + "]"); - } - - // We have a translation; look it up directly - return groupImpl.lookupService(map[roleIndex]); - } - } - - // No translation; use the name as-is, provided roleIndex is 0. - // Do not call groupImpl.lookupService(name, id); group impls - // should not have to implement it at all. - - if (roleIndex != 0) { - throw new ServiceNotFoundException(name + "[" + roleIndex + "]"); - } - return groupImpl.lookupService(name); - } - - /** - * {@inheritDoc} - */ - @Override - public Iterator getRoleMap(ID name) { - - if (roleMap != null) { - ID[] map = (ID[]) roleMap.get(name); - - // If there is a map, remap; else, identity is the default for - // role 0 only; the default mapping has only index 0. - - if (map != null) { - // return an iterator on it. - return Collections.unmodifiableList(Arrays.asList(map)).iterator(); - } - } - // No translation; use the given name in a singleton. - return Collections.singletonList(name).iterator(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/ShadowPeerGroup.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/ShadowPeerGroup.java deleted file mode 100644 index 7d6adfee..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/ShadowPeerGroup.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - -import net.jxta.document.Advertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.exception.PeerGroupException; -import net.jxta.impl.endpoint.cbjx.CbJxDefs; -import net.jxta.impl.membership.pse.PSEMembershipService; -import net.jxta.platform.Application; -import net.jxta.platform.Module; -import net.jxta.protocol.ModuleImplAdvertisement; - -/** - * ShadowPeerGroup is almost a regular StdPeerGroup, except that it borrows its - * parent's configuration. The only real use is for the Net Peer Group. - */ -public class ShadowPeerGroup extends StdPeerGroup { - - /** - * Our application is the JXSE Shell. - */ - private Application shell = null; - - /** - * Create and populate the default module impl Advertisement for this class. - * - * @return The default module impl advertisement for this class. - */ - public static ModuleImplAdvertisement getDefaultModuleImplAdvertisement() { - ModuleImplAdvertisement implAdv = mkImplAdvBuiltin(PeerGroup.refNetPeerGroupSpecID, ShadowPeerGroup.class.getName(), "Default Network PeerGroup reference implementation"); - - // Build the param section now. - StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv(); - - // Set the services - // "Core" Services - paramAdv.addService(PeerGroup.endpointClassID, PeerGroup.refEndpointSpecID); - paramAdv.addService(PeerGroup.resolverClassID, PeerGroup.refResolverSpecID); - paramAdv.addService(PeerGroup.membershipClassID, PSEMembershipService.pseMembershipSpecID); - paramAdv.addService(PeerGroup.accessClassID, PeerGroup.refAccessSpecID); - - // "Standard" Services - paramAdv.addService(PeerGroup.discoveryClassID, PeerGroup.refDiscoverySpecID); - paramAdv.addService(PeerGroup.rendezvousClassID, PeerGroup.refRendezvousSpecID); - paramAdv.addService(PeerGroup.pipeClassID, PeerGroup.refPipeSpecID); - paramAdv.addService(PeerGroup.peerinfoClassID, PeerGroup.refPeerinfoSpecID); - paramAdv.addService(PeerGroup.proxyClassID, PeerGroup.refProxySpecID); - - // High-level Message Transports. - paramAdv.addProto(PeerGroup.routerProtoClassID, PeerGroup.refRouterProtoSpecID); - paramAdv.addProto(PeerGroup.tlsProtoClassID, PeerGroup.refTlsProtoSpecID); - paramAdv.addProto(CbJxDefs.msgtptClassID, CbJxDefs.cbjxMsgTransportSpecID); - paramAdv.addProto(PeerGroup.relayProtoClassID, PeerGroup.refRelayProtoSpecID); - - // Pour our newParamAdv in implAdv - XMLElement paramElement = (XMLElement) paramAdv.getDocument(MimeMediaType.XMLUTF8); - - implAdv.setParam(paramElement); - - return implAdv; - } - - /** - * {@inheritDoc} - * - *

            This implementation initializes the configuration advertisement with - * that of the parent group and otherwise behave exactly like its superclass. - */ - @Override - protected void initFirst(PeerGroup parent, ID assignedID, Advertisement impl) throws PeerGroupException { - - // Set the peer configuration before we start. - setConfigAdvertisement(parent.getConfigAdvertisement()); - - // Do the regular stuff now. - super.initFirst(parent, assignedID, impl); - } - - /** - * {@inheritDoc} - */ - @Override - protected void initLast() throws PeerGroupException { - // Nothing special, but that could change in the future - // Just remember that the possibility exists. - super.initLast(); - } - - /** - * {@inheritDoc} - *

            - * If it is available, start the shell. - */ - @Override - public int startApp(String[] args) { - int result = super.startApp(args); - - if (Module.START_OK != result) { - return result; - } - - // Main app is the shell (if it is available). - if (null != getLoader().findModuleImplAdvertisement(PeerGroup.refShellSpecID)) { - shell = (Application) loadModule(PeerGroup.applicationClassID, PeerGroup.refShellSpecID, PeerGroup.Both); - - if (null == shell) { - return -1; - } - - result = shell.startApp(new String[0]); - } - - return result; - } - - /** - * {@inheritDoc} - *

            If we started the shell we now must stop it. - */ - @Override - public void stopApp() { - if (null != shell) { - shell.stopApp(); - shell = null; - } - - super.stopApp(); - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/StdPeerGroup.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/StdPeerGroup.java deleted file mode 100644 index f4179350..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/StdPeerGroup.java +++ /dev/null @@ -1,986 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.peergroup; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Method; -import java.net.URI; -import java.net.URL; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.MessageTransport; -import net.jxta.exception.PeerGroupException; -import net.jxta.exception.ServiceNotFoundException; -import net.jxta.id.ID; -import net.jxta.impl.cm.Cm; -import net.jxta.impl.cm.SrdiIndex; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.JxtaLoader; -import net.jxta.platform.Module; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.service.Service; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.jxta.document.TextElement; - -/** - * A subclass of GenericPeerGroup that makes a peer group out of independent - * plugin services listed in its impl advertisement. - */ -public class StdPeerGroup extends GenericPeerGroup { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(StdPeerGroup.class.getName()); - - // A few things common to all ImplAdv for built-in things. - public static final XMLDocument STD_COMPAT = mkCS(); - public static final String MODULE_IMPL_STD_URI = "http://jxta-jxse.dev.java.net/download/jxta.jar"; - public static final String MODULE_IMPL_STD_PROVIDER = "sun.com"; - - protected static final String STD_COMPAT_FORMAT = "Efmt"; - - // FIXME 20061206 bondolo Update this to "JRE1.5" after 2.5 release. 2.4.1 and earlier don't do version comparison correctly. - - /** - * The Specification title and Specification version we require. - */ - protected static final String STD_COMPAT_FORMAT_VALUE = "JDK1.4.1"; - protected static final String STD_COMPAT_BINDING = "Bind"; - protected static final String STD_COMPAT_BINDING_VALUE = "V2.0 Ref Impl"; - - static { - // Initialize the JXTA class loader with the standard modules. - try { - Enumeration allProviderLists = GenericPeerGroup.class.getClassLoader().getResources("META-INF/services/net.jxta.platform.Module"); - for (URL providers : Collections.list(allProviderLists)) { - registerFromFile(providers); - } - } catch (IOException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to locate provider lists", ex); - } - } - - // XXX Force redefinition of StdPeerGroup implAdvertisement. - getJxtaLoader().defineClass(getDefaultModuleImplAdvertisement()); - } - - /** - * Register instance classes given a URL to a file containing modules which - * must be found on the current class path. Each line of the file contains a - * module spec ID, the class name and the Module description. The fields are - * separated by whitespace. Comments are marked with a '#', the pound sign. - * Any text following # on any line in the file is ignored. - * - * @param providerList the URL to a file containing a list of modules - * @return {@code true} if at least one of the instance classes could be - * registered otherwise {@code false}. - */ - private static boolean registerFromFile(URL providers) { - boolean registeredSomething = false; - InputStream urlStream = null; - - try { - urlStream = providers.openStream(); - BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream, "UTF-8")); - - String provider; - while ((provider = reader.readLine()) != null) { - int comment = provider.indexOf('#'); - - if (comment != -1) { - provider = provider.substring(0, comment); - } - - provider = provider.trim(); - - if (0 == provider.length()) { - continue; - } - - try { - String[] parts = provider.split("\\s", 3); - - if (3 == parts.length) { - ModuleSpecID msid = ModuleSpecID.create(URI.create(parts[0])); - String code = parts[1]; - String description = parts[2]; - - ModuleImplAdvertisement moduleImplAdv; - - try { - Class moduleClass = (Class) Class.forName(code); - - Method getImplAdvMethod = moduleClass.getMethod("getDefaultModuleImplAdvertisement"); - - moduleImplAdv = (ModuleImplAdvertisement) getImplAdvMethod.invoke(null); - } catch(Exception failed) { - // Use default ModuleImplAdvertisement. - moduleImplAdv = StdPeerGroup.mkImplAdvBuiltin(msid, code, description); - } - - getJxtaLoader().defineClass(moduleImplAdv); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Registered Module " + msid + " : " + parts[1]); - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to register \'" + provider + "\'"); - } - } - } catch (Exception allElse) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to register \'" + provider + "\'", allElse); - } - } - } - } catch (IOException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to read provider list " + providers, ex); - } - } finally { - if (null != urlStream) { - try { - urlStream.close(); - } catch (IOException ignored) { - - } - } - } - return registeredSomething; - } - - /** - * If {@code true} then the PeerGroup has been started. - */ - private volatile boolean started = false; - - /** - * The order in which we started the services. - */ - private final List moduleStartOrder = new ArrayList(); - - /** - * A map of the Message Transports for this group. - *

            - *

              - *
            • keys are {@link net.jxta.platform.ModuleClassID}
            • - *
            • values are {@link net.jxta.platform.Module}, but should also be - * {@link net.jxta.endpoint.MessageTransport}
            • - *
            - */ - private final Map messageTransports = new HashMap(); - - /** - * A map of the applications for this group. - *

            - *

              - *
            • keys are {@link net.jxta.platform.ModuleClassID}
            • - *
            • values are {@link net.jxta.platform.Module} or - * {@link net.jxta.protocol.ModuleImplAdvertisement} or - * {@link net.jxta.platform.ModuleSpecID}
            • - *
            - */ - private final Map applications = new HashMap(); - - /** - * Cache for this group. - */ - private Cm cm = null; - - private static XMLDocument mkCS() { - XMLDocument doc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Comp"); - - XMLElement e = doc.createElement(STD_COMPAT_FORMAT, STD_COMPAT_FORMAT_VALUE); - - doc.appendChild(e); - - e = doc.createElement(STD_COMPAT_BINDING, STD_COMPAT_BINDING_VALUE); - doc.appendChild(e); - return doc; - } - - /** - * An internal convenience method essentially for bootstrapping. - * Make a standard ModuleImplAdv for any service that comes builtin this - * reference implementation. - * In most cases there are no params, so we do not take that argument. - * The invoker may add params afterwards. - * - * @param specID spec ID - * @param code code uri - * @param descr description - * @return a ModuleImplAdvertisement - */ - static ModuleImplAdvertisement mkImplAdvBuiltin(ModuleSpecID specID, String code, String descr) { - ModuleImplAdvertisement implAdv = (ModuleImplAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleImplAdvertisement.getAdvertisementType()); - - implAdv.setModuleSpecID(specID); - implAdv.setCompat(STD_COMPAT); - implAdv.setCode(code); - implAdv.setUri(MODULE_IMPL_STD_URI); - implAdv.setProvider(MODULE_IMPL_STD_PROVIDER); - implAdv.setDescription(descr); - - return implAdv; - } - - /** - * Create and populate the default module impl Advertisement for this class. - * - * @return The default module impl advertisement for this class. - */ - private static ModuleImplAdvertisement getDefaultModuleImplAdvertisement() { - ModuleImplAdvertisement implAdv = mkImplAdvBuiltin(PeerGroup.allPurposePeerGroupSpecID, StdPeerGroup.class.getName(), "General Purpose Peer Group Implementation"); - - // Create the service list for the group. - StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv(); - ModuleImplAdvertisement moduleAdv; - - // set the services - - // core services - JxtaLoader loader = getJxtaLoader(); - - moduleAdv = loader.findModuleImplAdvertisement(PeerGroup.refEndpointSpecID); - paramAdv.addService(PeerGroup.endpointClassID, moduleAdv); - - moduleAdv = loader.findModuleImplAdvertisement(PeerGroup.refResolverSpecID); - paramAdv.addService(PeerGroup.resolverClassID, moduleAdv); - - moduleAdv = loader.findModuleImplAdvertisement(PeerGroup.refMembershipSpecID); - paramAdv.addService(PeerGroup.membershipClassID, moduleAdv); - - moduleAdv = loader.findModuleImplAdvertisement(PeerGroup.refAccessSpecID); - paramAdv.addService(PeerGroup.accessClassID, moduleAdv); - - // standard services - - moduleAdv = loader.findModuleImplAdvertisement(PeerGroup.refDiscoverySpecID); - paramAdv.addService(PeerGroup.discoveryClassID, moduleAdv); - - moduleAdv = loader.findModuleImplAdvertisement(PeerGroup.refRendezvousSpecID); - paramAdv.addService(PeerGroup.rendezvousClassID, moduleAdv); - - moduleAdv = loader.findModuleImplAdvertisement(PeerGroup.refPipeSpecID); - paramAdv.addService(PeerGroup.pipeClassID, moduleAdv); - - moduleAdv = loader.findModuleImplAdvertisement(PeerGroup.refPeerinfoSpecID); - paramAdv.addService(PeerGroup.peerinfoClassID, moduleAdv); - - // Applications - - moduleAdv = loader.findModuleImplAdvertisement(PeerGroup.refShellSpecID); - if (null != moduleAdv) { - paramAdv.addApp(PeerGroup.applicationClassID, moduleAdv); - } - - // Insert the newParamAdv in implAdv - XMLElement paramElement = (XMLElement) paramAdv.getDocument(MimeMediaType.XMLUTF8); - - implAdv.setParam(paramElement); - - return implAdv; - } - - /** - * constructor - */ - public StdPeerGroup() { - } - - /** - * {@inheritDoc} - */ - // @Override - public boolean compatible(Element compat) { - return isCompatible(compat); - } - - /** - * Evaluates if the given compatibility statement makes the module that - * bears it is loadable by this group. - * - * @param compat The compatibility statement being tested. - * @return {@code true} if we are compatible with the provided statement - * otherwise {@code false}. - */ - static boolean isCompatible(Element compat) { - boolean formatOk = false; - boolean bindingOk = false; - - if(!(compat instanceof TextElement)) { - return false; - } - - try { - Enumeration hisChildren = ((TextElement)compat).getChildren(); - int i = 0; - while (hisChildren.hasMoreElements()) { - // Stop after 2 elements; there shall not be more. - if (++i > 2) { - return false; - } - - TextElement e = hisChildren.nextElement(); - String key = e.getKey(); - String val = e.getValue().trim(); - - if (STD_COMPAT_FORMAT.equals(key)) { - Package javaLangPackage = Package.getPackage("java.lang"); - - boolean specMatches; - String version; - - if (val.startsWith("JDK") || val.startsWith("JRE")) { - specMatches = true; - version = val.substring(3).trim(); // allow for spaces. - } else if (val.startsWith(javaLangPackage.getSpecificationTitle())) { - specMatches = true; - version = val.substring(javaLangPackage.getSpecificationTitle().length()).trim(); // allow for spaces. - } else { - specMatches = false; - version = null; - } - - formatOk = specMatches && javaLangPackage.isCompatibleWith(version); - } else if (STD_COMPAT_BINDING.equals(key) && STD_COMPAT_BINDING_VALUE.equals(val)) { - bindingOk = true; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Bad element in compatibility statement : " + key); - } - return false; // Might as well stop right now. - } - } - } catch (Exception any) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure handling compatibility statement", any); - } - return false; - } - - return formatOk && bindingOk; - } - - /** - * Builds a table of modules indexed by their class ID. - * The values are the loaded modules, the keys are their classId. - * This routine interprets the parameter list in the advertisement. - * - * @param modules The modules to load - * @param privileged if true then modules will get a real reference to - * the group loading them, otherwise its an interface object. - */ - protected void loadAllModules(Map modules, boolean privileged) { - - Iterator> eachModule = modules.entrySet().iterator(); - - while (eachModule.hasNext()) { - Map.Entry anEntry = eachModule.next(); - ModuleClassID classID = anEntry.getKey(); - Object value = anEntry.getValue(); - - // Already loaded. - if (value instanceof Module) { - continue; - } - - // Try and load it. - try { - Module theModule = null; - - if (value instanceof ModuleImplAdvertisement) { - // Load module will republish locally but not in the - // parent since that adv does not come from there. - theModule = loadModule(classID, (ModuleImplAdvertisement) value, privileged); - } else if (value instanceof ModuleSpecID) { - // loadModule will republish both locally and in the parent - // Where the module was fetched. - theModule = loadModule(classID, (ModuleSpecID) value, FromParent, privileged); - } else { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Skipping: " + classID + " Unsupported module descriptor : " + value.getClass().getName()); - } - eachModule.remove(); - continue; - } - - if (theModule == null) { - throw new PeerGroupException("Could not find a loadable implementation for : " + classID); - } - - anEntry.setValue(theModule); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not load module for class ID : " + classID, e); - if (value instanceof ModuleImplAdvertisement) { - LOG.log(Level.WARNING, "Will be missing from peer group : " + - ((ModuleImplAdvertisement) value).getDescription()); - } else { - LOG.log(Level.WARNING, "Will be missing from peer group: " + value); - } - } - eachModule.remove(); - } - } - } - - /** - * The group does not care for start args, and does not come-up - * with args to pass to its main app. So, until we decide on something - * more useful, the args of the group's startApp are passed-on to the - * group's main app. NB: both the apps init and startApp methods are - * invoked. - * - * @return int Status. - */ - @Override - public int startApp(String[] arg) { - - if (!initComplete) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Group has not been initialized or init failed."); - } - return -1; - } - - // FIXME: maybe concurrent callers should be blocked until the - // end of startApp(). That could mean forever, though. - if (started) { - return Module.START_OK; - } - - started = true; - - // Normally does nothing, but we have to. - int res = super.startApp(arg); - - if (Module.START_OK != res) { - return res; - } - - loadAllModules(applications, false); // Apps are non-privileged; - - res = startModules((Map) applications); - - return res; - } - - /** - * {@inheritDoc} - */ - @Override - public void stopApp() { - // Shut down the group services and message transports. - Collections.reverse(moduleStartOrder); - - for (ModuleClassID aModule : moduleStartOrder) { - try { - if (messageTransports.containsKey(aModule)) { - Module theMessageTransport = (Module) messageTransports.remove(aModule); - - theMessageTransport.stopApp(); - } else { - removeService(aModule); - } - } catch (Exception any) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to stop module: " + aModule, any); - } - } - } - - moduleStartOrder.clear(); - - if (!messageTransports.isEmpty()) { - LOG.warning(messageTransports.size() + " message transports could not be shut down during peer group stop."); - } - - messageTransports.clear(); - - super.stopApp(); - - if (cm != null) { - cm.stop(); - cm = null; - } - } - - /** - * Given a list of all the modules we need to start attempt to start them. - * There is an a-priori order, but we'll iterate over the list until all - * where able to complete their start phase or no progress is made. Since we - * give modules the opportunity to pretend that they are making progress, we - * need to have a safeguard: we will not iterate through the list more than - * N^2 + 1 times without at least one module completing; N being the number - * of modules still in the list. This should cover the worst case scenario - * and still allow the process to eventually fail if it has no chance of - * success. - * - * @param services The services to start. - */ - private int startModules(Map services) { - int iterations = 0; - int maxIterations = services.size() * services.size() + iterations + 1; - - boolean progress = true; - - while (!services.isEmpty() && (progress || (iterations < maxIterations))) { - progress = false; - iterations++; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Service startApp() round {0} of {1}(max)", iterations, maxIterations)); - } - - Iterator> eachService = services.entrySet().iterator(); - - while (eachService.hasNext()) { - Map.Entry anEntry = eachService.next(); - ModuleClassID mcid = anEntry.getKey(); - Module aModule = anEntry.getValue(); - - int res; - - try { - res = aModule.startApp(null); - } catch (Throwable all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Exception in startApp() : " + aModule, all); - } - res = -1; - } - - switch (res) { - case Module.START_OK: - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Module started : " + aModule); - } - if (aModule instanceof Service) { - addService(mcid, (Service) aModule); - } else { - messageTransports.put(mcid, aModule); - } - - moduleStartOrder.add(mcid); - eachService.remove(); - progress = true; - break; - - case Module.START_AGAIN_PROGRESS: - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Service made progress during start : " + aModule); - } - progress = true; - break; - - case Module.START_AGAIN_STALLED: - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Service stalled during start : " + aModule); - } - break; - - case Module.START_DISABLED: - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Service declined to start : " + aModule); - } - eachService.remove(); - progress = true; - break; - - default: // (negative) - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Service failed to start (" + res + ") : " + aModule); - } - eachService.remove(); - progress = true; - break; - } - } - - if (progress) { - maxIterations = services.size() * services.size() + iterations + 1; - } - } - - // Uh-oh. Services co-dependency prevented them from starting. - if (!services.isEmpty()) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - StringBuilder failed = new StringBuilder( "No progress is being made in starting services after " - + iterations + " iterations. Giving up."); - - failed.append("\nThe following services could not be started : "); - - for (Map.Entry aService : services.entrySet()) { - failed.append("\n\t"); - failed.append(aService.getKey()); - failed.append(" : "); - failed.append(aService.getValue()); - } - - LOG.severe(failed.toString()); - } - - return -1; - } - - return Module.START_OK; - } - - /** - * {@inheritDoc} - *

            - * This method loads and initializes all of the peer group modules - * described in the provided implementation advertisement. Then, all modules - * are placed in a list and the list is processed iteratively. During each - * iteration, the {@link Module#startApp(String[])} method of each module - * is invoked once. Iterations continue until no progress is being made or - * the list is empty. - *

            - * The status returned by the {@link Module#startApp(String[])} method - * of each module is considered as follows: - *

            - *

              - *
            • {@link Module#START_OK}: The module is removed from the list of - * modules to be started and its {@link Module#startApp(String[])} - * method will not be invoked again. - *
            • - *

              - *

            • {@link Module#START_AGAIN_PROGRESS}: The module remains in the - * list of modules to be started and its {@link Module#startApp(String[])} - * method will be invoked during the next iteration, if there is one.
            • - *

              - *

            • {@link Module#START_AGAIN_STALLED}: The module remains in the list - * of modules to be started and its {@link Module#startApp(String[])} - * method will be invoked during the next iteration if there is one.
            • - *

              - *

            • Any other value: The module failed to initialize. Its - * {@link Module#startApp(String[])} method will not be invoked again.
            • - *
            - *

            - * Iterations through the list stop when: - *

              - *
            • The list is empty: the group initialization proceeds.
            • - *

              - *

            • A complete iteration was performed and all modules returned - * {@link Module#START_AGAIN_STALLED}: a {@link PeerGroupException} - * is thrown.
            • - *

              - *

            • A number of complete iteration completed without any module - * returning {@link Module#START_OK}: a {@link PeerGroupException} - * is thrown. The number of complete iterations before that happens is - * computed as 1 + the square of the number of modules currently in the - * list.
            • - *
            - */ - @Override - protected synchronized void initFirst(PeerGroup parent, ID assignedID, Advertisement impl) throws PeerGroupException { - - if (initComplete) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("You cannot initialize a PeerGroup more than once !"); - } - return; - } - - // Set-up the minimal GenericPeerGroup - super.initFirst(parent, assignedID, impl); - - // assignedID might have been null. It is now the peer group ID. - assignedID = getPeerGroupID(); - - // initialize cm before starting services. - try { - cm = new Cm(getHomeThreadGroup(), - getStoreHome(), assignedID.getUniqueValue().toString(), - Cm.DEFAULT_GC_MAX_INTERVAL, false); - } catch (Exception e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Error during creation of local store", e); - } - throw new PeerGroupException("Error during creation of local store", e); - } - - // flush srdi for this group - SrdiIndex.clearSrdi(this); - - // Load the list of peer group services from the impl advertisement params. - StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv(implAdvertisement.getParam()); - - Map initServices = new HashMap(paramAdv.getServices()); - - initServices.putAll(paramAdv.getProtos()); - - // Remove the modules disabled in the configuration file. - ConfigParams conf = getConfigAdvertisement(); - - if(null != conf) { - Iterator eachModule = initServices.keySet().iterator(); - - while(eachModule.hasNext()) { - ModuleClassID aModule = eachModule.next(); - - if(!conf.isSvcEnabled(aModule)) { - // remove disabled module - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Module disabled in configuration : " + aModule); - } - - eachModule.remove(); - } - } - } - - // We Applications are shelved until startApp() - applications.putAll(paramAdv.getApps()); - - if(null != conf) { - Iterator eachModule = applications.keySet().iterator(); - - while(eachModule.hasNext()) { - ModuleClassID aModule = eachModule.next(); - - if(!conf.isSvcEnabled(aModule)) { - // remove disabled module - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Application disabled in configuration : " + aModule); - } - - eachModule.remove(); - } - } - } - - loadAllModules(initServices, true); - - int res = startModules((Map) initServices); - - if(Module.START_OK != res) { - throw new PeerGroupException("Failed to start peer group services. res : " + res); - } - - // Make sure all the required services are loaded. - try { - checkServices(); - } catch (ServiceNotFoundException e) { - LOG.log(Level.SEVERE, "Missing peer group service", e); - throw new PeerGroupException("Missing peer group service", e); - } - - /* - * Publish a few things that have not been published in this - * group yet. - */ - DiscoveryService discoveryService = getDiscoveryService(); - - if (discoveryService != null) { - // It should work but if it does not we can survive. - try { - // Discovery service adv could not be published localy, - // since at that time there was no local discovery to - // publish to. - discoveryService.publish(discoveryService.getImplAdvertisement(), DEFAULT_LIFETIME, DEFAULT_EXPIRATION); - - // Try to publish our impl adv within this group. (it was published - // in the parent automatically when loaded. - discoveryService.publish(implAdvertisement, DEFAULT_LIFETIME, DEFAULT_EXPIRATION); - } catch (Exception nevermind) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to publish Impl adv within group.", nevermind); - } - } - } - } - - /** - * {@inheritDoc} - *

            - * Nothing special for now, but we might want to move some steps from - * initFirst() in the future. - */ - @Override - protected synchronized void initLast() throws PeerGroupException { - - super.initLast(); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Group : " + getPeerGroupID()); - - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tCompatibility Statement :\n\t\t\t"); - StringBuilder indent = new StringBuilder(STD_COMPAT.toString().trim()); - int from = indent.length(); - - while (from > 0) { - int returnAt = indent.lastIndexOf("\n", from); - - from = returnAt - 1; - if ((returnAt >= 0) && (returnAt != indent.length())) { - indent.insert(returnAt + 1, "\t\t\t"); - } - } - configInfo.append(indent); - Iterator eachProto = messageTransports.entrySet().iterator(); - - if (eachProto.hasNext()) { - configInfo.append("\n\t\tMessage Transports :"); - } - while (eachProto.hasNext()) { - Map.Entry anEntry = (Map.Entry) eachProto.next(); - ModuleClassID aMCID = (ModuleClassID) anEntry.getKey(); - Module anMT = (Module) anEntry.getValue(); - - configInfo.append("\n\t\t\t").append(aMCID).append("\t").append( - (anMT instanceof MessageTransport) - ? ((MessageTransport) anMT).getProtocolName() - : anMT.getClass().getName()); - } - Iterator> eachApp = applications.entrySet().iterator(); - - if (eachApp.hasNext()) { - configInfo.append("\n\t\tApplications :"); - } - while (eachApp.hasNext()) { - Map.Entry anEntry = eachApp.next(); - ModuleClassID aMCID = anEntry.getKey(); - Object anApp = anEntry.getValue(); - - if (anApp instanceof ModuleImplAdvertisement) { - ModuleImplAdvertisement adv = (ModuleImplAdvertisement) anApp; - - configInfo.append("\n\t\t\t").append(aMCID).append("\t").append(adv.getCode()); - } else { - configInfo.append("\n\t\t\t").append(aMCID).append("\t").append(anApp.getClass().getName()); - } - } - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - *

            - * FIXME 20070801 bondolo To improve compatibility with existing - * applications the returned {@code ModuleImplAdvertisement} will contain - * embedded {@code ModuleImplAdvertisement}s for the referenced services as - * opposed to {@code ModuleSpecID}s. This is because JXSE 2.4.1 and earlier - * do not handle load failures of modules loaded by spec id correctly. - * After JXSE 2.5 is released this should be changed to use the better - * {@code ModuleSpecID} based peer group module specification. - */ - // @Override - public ModuleImplAdvertisement getAllPurposePeerGroupImplAdvertisement() { - JxtaLoader loader = getJxtaLoader(); - - // grab an impl adv - ModuleImplAdvertisement implAdv = loader.findModuleImplAdvertisement(PeerGroup.allPurposePeerGroupSpecID); - - return implAdv; - } - - - /** - * Returns the cache manager associated with this group. - * - * @return the cache manager associated with this group. - */ - public Cm getCacheManager() { - return cm; - } - - /** - * Return a map of the applications for this group. - *

            - *

              - *
            • keys are {@link net.jxta.platform.ModuleClassID}
            • - *
            • values are {@link net.jxta.platform.Module} or - * {@link net.jxta.protocol.ModuleImplAdvertisement}
            • - *
            - * - * @return a map of the applications for this group. - */ - public Map getApplications() { - return Collections.unmodifiableMap(applications); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/StdPeerGroupParamAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/StdPeerGroupParamAdv.java deleted file mode 100644 index c35b9ce4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/StdPeerGroupParamAdv.java +++ /dev/null @@ -1,517 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.peergroup; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLElement; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleImplAdvertisement; - -import java.net.URI; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Not actually an advertisement, but often acts as part of one. - * - * @deprecated This internal class will eventually be removed. It has several - * problems which make it difficult to support. (The most obvious that it - * provides poor abstraction and provides references to its' own internal data - * structures). This class is expected to be replaced by a public API class - * performing a similar function though such an alternative is not yet available. - * You are encouraged to copy this code into your own application or service if - * if you depend upon it. - */ -@Deprecated -public class StdPeerGroupParamAdv { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(StdPeerGroupParamAdv.class.getName()); - - private static final String PARAM_TAG = "Parm"; - private static final String PROTO_TAG = "Proto"; - private static final String APP_TAG = "App"; - private static final String SVC_TAG = "Svc"; - private static final String MCID_TAG = "MCID"; - private static final String MSID_TAG = "MSID"; - private static final String MIA_TAG = ModuleImplAdvertisement.getAdvertisementType(); - - // In the future we should be able to manipulate all modules regardless of - // their kind, but right now it helps to keep them categorized as follows. - - /** - * The services which will be loaded for this peer group. - *

            - *

              - *
            • Keys are {@link net.jxta.platform.ModuleClassID}.
            • - *
            • Values are {@link net.jxta.platform.ModuleSpecID} or - * {@link net.jxta.protocol.ModuleImplAdvertisement}.
            • - *
            - */ - private final Map services = new HashMap(); - - /** - * The protocols (message transports) which will be loaded for this peer - * group. - *

            - *

              - *
            • Keys are {@link net.jxta.platform.ModuleClassID}.
            • - *
            • Values are {@link net.jxta.platform.ModuleSpecID} or - * {@link net.jxta.protocol.ModuleImplAdvertisement}.
            • - *
            - */ - private final Map transports = new HashMap(); - - /** - * The applications which will be loaded for this peer group. - *

            - *

              - *
            • Keys are {@link net.jxta.platform.ModuleClassID}.
            • - *
            • Values are {@link net.jxta.platform.ModuleSpecID} or - * {@link net.jxta.protocol.ModuleImplAdvertisement}.
            • - *
            - */ - private final Map apps = new HashMap(); - - /** - * Private constructor for new instances. - */ - public StdPeerGroupParamAdv() { - } - - /** - * Private constructor for serialized instances. - * - * @param root the root element - */ - public StdPeerGroupParamAdv(Element root) { - if (!(root instanceof XMLElement)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XMLElement"); - } - initialize((XMLElement) root); - } - - /** - * Private constructor for xml serialized instances. - * - * @param doc The XML serialization of the advertisement. - */ - public StdPeerGroupParamAdv(XMLElement doc) { - initialize(doc); - } - - /** - * Add a service to the set of services entries described in this - * Advertisement. - * - * @param mcid The module class id of the module being added. - * @param module The module being added. - */ - public void addService(ModuleClassID mcid, Object module) { - if(null == mcid) { - throw new IllegalArgumentException("Illegal ModuleClassID"); - } - - if(null == module) { - throw new IllegalArgumentException("Illegal module"); - } - - services.put(mcid, module); - } - - /** - * Return the services entries described in this Advertisement. - *

            - * The result (very unwisely) is the internal map of this - * Advertisement. Modifying it results in changes to this Advertisement. - * For safety the Map should be copied before being modified. - * - * @return the services entries described in this Advertisement. - */ - public Map getServices() { - return services; - } - - /** - * Add a protocol (message transport) to the set of protocol entries - * described in this Advertisement. - * - * @param mcid The module class id of the module being added. - * @param module The module being added. - */ - public void addProto(ModuleClassID mcid, Object module) { - if(null == mcid) { - throw new IllegalArgumentException("Illegal ModuleClassID"); - } - - if(null == module) { - throw new IllegalArgumentException("Illegal module"); - } - - transports.put(mcid, module); - } - - /** - * Return the protocols (message transports) entries described in this Advertisement. - *

            - * The result (very unwisely) is the internal map of this Advertisement. - * Modifying it results in changes to this Advertisement. - * For safety the Map should be copied before being modified. - * - * @return the protocols (message transports) entries described in this Advertisement. - */ - public Map getProtos() { - return transports; - } - - /** - * Add an application to the set of application entries described in this - * Advertisement. - * - * @param mcid The module class id of the module being added. - * @param module The module being added. - */ - public void addApp(ModuleClassID mcid, Object module) { - if(null == mcid) { - throw new IllegalArgumentException("Illegal ModuleClassID"); - } - - if(null == module) { - throw new IllegalArgumentException("Illegal module"); - } - - apps.put(mcid, module); - } - - /** - * Return the application entries described in this Advertisement. - *

            - * The result (very unwisely) is the internal map of this Advertisement. - * Modifying it results in changes to this Advertisement. - * For safety the Map should be copied before being modified. - * - * @return the application entries described in this Advertisement. - */ - public Map getApps() { - return apps; - } - - /** - * Replaces the table of services described by this Advertisement. All - * existing entries are lost. - * - * @param servicesTable the services table - */ - public void setServices(Map servicesTable) { - if(servicesTable.containsKey(null)) { - throw new IllegalArgumentException("null key in servicesTable"); - } - - if(servicesTable.containsValue(null)) { - throw new IllegalArgumentException("null value in servicesTable"); - } - - if (servicesTable == this.services) { - return; - } - - this.services.clear(); - - if (null != servicesTable) { - this.services.putAll(servicesTable); - } - } - - /** - * Replaces the table of protocols described by this Advertisement. All - * existing entries are lost. - * - * @param protosTable The message transport descriptors for the group. - */ - public void setProtos(Map protosTable) { - if(protosTable.containsKey(null)) { - throw new IllegalArgumentException("null key in protosTable"); - } - - if(protosTable.containsValue(null)) { - throw new IllegalArgumentException("null value in protosTable"); - } - - if (protosTable == this.transports) { - return; - } - - this.transports.clear(); - - if (null != protosTable) { - this.transports.putAll(protosTable); - } - } - - /** - * Replaces the table of applications described by this Advertisement. All - * existing entries are lost. - * - * @param appsTable The application descriptors for the group. - */ - public void setApps(Map appsTable) { - if(appsTable.containsKey(null)) { - throw new IllegalArgumentException("null key in appsTable"); - } - - if(appsTable.containsValue(null)) { - throw new IllegalArgumentException("null value in appsTable"); - } - - if (appsTable == this.apps) { - return; - } - - this.apps.clear(); - - if (null != appsTable) { - this.apps.putAll(appsTable); - } - } - - private void initialize(XMLElement doc) { - if (!doc.getName().equals(PARAM_TAG)) { - throw new IllegalArgumentException("Can not construct " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - // set defaults - int appCount = 0; - Enumeration modules = doc.getChildren(); - - while (modules.hasMoreElements()) { - XMLElement module = modules.nextElement(); - String tagName = module.getName(); - - Map theTable; - - if (SVC_TAG.equals(tagName)) { - theTable = services; - } else if (APP_TAG.equals(tagName)) { - theTable = apps; - } else if (PROTO_TAG.equals(tagName)) { - theTable = transports; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Unhandled top-level tag : " + tagName); - } - continue; - } - - ModuleSpecID specID = null; - ModuleClassID classID = null; - ModuleImplAdvertisement inLineAdv = null; - - try { - if (module.getTextValue() != null) { - specID = (ModuleSpecID) IDFactory.fromURI(new URI(module.getTextValue())); - } - - // Check for children anyway. - Enumeration fields = module.getChildren(); - - while (fields.hasMoreElements()) { - XMLElement field = fields.nextElement(); - - String fieldName = field.getName(); - - if (MCID_TAG.equals(fieldName)) { - classID = (ModuleClassID) IDFactory.fromURI(new URI(field.getTextValue())); - } else if (MSID_TAG.equals(field.getName())) { - specID = (ModuleSpecID) IDFactory.fromURI(new URI(field.getTextValue())); - } else if (MIA_TAG.equals(field.getName())) { - inLineAdv = (ModuleImplAdvertisement) AdvertisementFactory.newAdvertisement(field); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Unhandled field : " + fieldName); - } - } - } - } catch (Exception any) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Broken entry; skipping", any); - } - continue; - } - - if (inLineAdv == null && specID == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Insufficent entry; skipping"); - } - continue; - } - - Object theValue; - - if (inLineAdv != null) { - specID = inLineAdv.getModuleSpecID(); - theValue = inLineAdv; - } else { - theValue = specID; - } - - if (classID == null) { - classID = specID.getBaseClass(); - } - - // For applications, the role does not matter. We just create a - // unique role ID on the fly. - // When outputing the adv we get rid of it to save space. - - if (theTable == apps) { - // Only the first (or only) one may use the base class. - if (classID == PeerGroup.applicationClassID) { - if (appCount++ != 0) { - classID = IDFactory.newModuleClassID(classID); - } - } - } - theTable.put(classID, theValue); - } - } - - /** - * {@inheritDoc} - */ - public Document getDocument(MimeMediaType encodeAs) { - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(encodeAs, PARAM_TAG); - - outputModules(doc, services, SVC_TAG); - outputModules(doc, transports, PROTO_TAG); - outputModules(doc, apps, APP_TAG); - - return doc; - } - - private void outputModules(StructuredDocument doc, Map modulesTable, String mainTag) { - - for (Map.Entry entry : modulesTable.entrySet()) { - ModuleClassID mcid = entry.getKey(); - Object val = entry.getValue(); - Element m; - - if(null == mcid) { - throw new IllegalStateException("null ModuleClassID in " + mainTag ); - } - - // For applications, we ignore the role ID. It is not meaningfull, - // and a new one is assigned on the fly when loading this adv. - - if (val instanceof Advertisement) { - m = doc.createElement(mainTag); - doc.appendChild(m); - - if (modulesTable != apps && !mcid.equals(mcid.getBaseClass())) { - // It is not an app and there is a role ID. Output it. - Element i = doc.createElement(MCID_TAG, mcid.toString()); - - m.appendChild(i); - } - - StructuredDocument advdoc = (StructuredDocument) ((Advertisement) val).getDocument(doc.getMimeType()); - - StructuredDocumentUtils.copyElements(doc, m, advdoc); - } else if (val instanceof ModuleSpecID) { - if (modulesTable == apps || mcid.equals(mcid.getBaseClass())) { - // Either it is an app or there is no role ID. - // So the specId is good enough. - m = doc.createElement(mainTag, val.toString()); - doc.appendChild(m); - } else { - // The role ID matters, so the classId must be separate. - m = doc.createElement(mainTag); - doc.appendChild(m); - - Element i; - - i = doc.createElement(MCID_TAG, mcid.toString()); - m.appendChild(i); - - i = doc.createElement(MSID_TAG, val.toString()); - m.appendChild(i); - } - } else { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("unsupported descriptor for " + mcid + " in " + mainTag +" module table : " + val); - } - throw new IllegalStateException("unsupported descriptor for " + mcid + " in " + mainTag +" module table : " + val); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/package.html deleted file mode 100644 index 86deacfd..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/peergroup/package.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - Provides the standard JXTA Peer Group implementations as well as legacy peer - group configuration functionality. The legacy peer configuration classes are - all deprecated. - - @see JXTA Protocols Specification - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/BlockingWireOutputPipe.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/BlockingWireOutputPipe.java deleted file mode 100644 index 9a304434..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/BlockingWireOutputPipe.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.document.MimeMediaType; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.ID; -import net.jxta.impl.endpoint.tcp.TcpMessenger; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.OutputPipe; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This Object is created when a call to PipeService.createOutputPipe(propgateAdv) with a Set containing a single - * PeerID. This pipe blocks until a valid messeger is created (i.e. resolved and useable). With this object it is - * possible to detect connection failures during the messenger resolution. Notge, this pipe also avoids utilitizing the - * rendezvous for propagation, effectively reducing message overhead, resulting in improved performance. - *

            - * #send is remains asynchronous. - */ -public class BlockingWireOutputPipe implements OutputPipe { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(NonBlockingWireOutputPipe.class.getName()); - - /** - * If true then the pipe has been closed and will no longer accept messages. - */ - private volatile boolean closed = false; - - /** - * The advertisement we were created from. - */ - private final PipeAdvertisement pAdv; - - private final PeerGroup group; - private Messenger destMessenger = null; - private EndpointAddress destination; - private EndpointService endpoint = null; - private RouteAdvertisement route = null; - - /** - * Create a new blocking output pipe - * - * @param group The peergroup context. - * @param pAdv advertisement for the pipe we are supporting. - * @param peerID the destination PeerID. - */ - public BlockingWireOutputPipe(PeerGroup group, PipeAdvertisement pAdv, PeerID peerID) { - - this.pAdv = pAdv; - this.group = group; - this.endpoint = group.getEndpointService(); - destination = new EndpointAddress("jxta", peerID.getUniqueValue().toString(), "PipeService", pAdv.getID().toString()); - destMessenger = endpoint.getMessenger(destination); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Created output pipe for " + getPipeID()); - } - } - /** - * Create a new blocking output pipe - * - * @param group The peergroup context. - * @param pAdv advertisement for the pipe we are supporting. - * @param peerID the destination PeerID. - * @param route the destination route. - */ - public BlockingWireOutputPipe(PeerGroup group, PipeAdvertisement pAdv, PeerID peerID, RouteAdvertisement route) { - this.route = route; - this.pAdv = pAdv; - this.group = group; - this.endpoint = group.getEndpointService(); - destination = new EndpointAddress("jxta", peerID.getUniqueValue().toString(), "PipeService", pAdv.getID().toString()); - if (route != null) { - destMessenger = endpoint.getDirectMessenger(destination, route, true); - } - if (destMessenger == null) { - destMessenger = endpoint.getMessenger(destination); - } - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Created output pipe for " + getPipeID()); - } - } - - /** - * {@inheritDoc} - */ - public synchronized void close() { - - if (closed) { - return; - } - // Close the queue so that no more messages are accepted - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Closing queue for " + getPipeID()); - } - closed = true; - } - - /** - * {@inheritDoc} - */ - public boolean isClosed() { - return closed; - } - - /** - * {@inheritDoc} - */ - public final String getType() { - return pAdv.getType(); - } - - /** - * {@inheritDoc} - */ - public final ID getPipeID() { - return pAdv.getPipeID(); - } - - /** - * {@inheritDoc} - */ - public final String getName() { - return pAdv.getName(); - } - - /** - * {@inheritDoc} - */ - public final PipeAdvertisement getAdvertisement() { - return pAdv; - } - - private void checkMessenger() throws IOException { - if (!(destMessenger instanceof TcpMessenger) && destMessenger != null && (destMessenger.getState() & Messenger.USABLE) != 0) { - return; - } - if (destMessenger != null && !destMessenger.isClosed()) { - return; - } - synchronized (this) { - if (route != null) { - destMessenger = endpoint.getDirectMessenger(destination, route, true); - } - destMessenger = endpoint.getMessenger(destination); - if (!(destMessenger instanceof TcpMessenger) && destMessenger == null || (destMessenger.getState() & Messenger.TERMINAL) != 0) { - if (destMessenger != null) { - destMessenger.close(); - destMessenger = null; - } - throw new IOException("Unable to create a messenger to " + destination.toString()); - } - } - } - - /** - * {@inheritDoc} - */ - public boolean send(Message message) throws IOException { - if (closed) { - throw new IOException("Pipe closed"); - } - WireHeader header = new WireHeader(); - - header.setPipeID(getPipeID()); - header.setSrcPeer(group.getPeerID()); - header.setTTL(1); - header.setMsgId(WirePipe.createMsgId()); - - XMLDocument asDoc = (XMLDocument) header.getDocument(MimeMediaType.XMLUTF8); - MessageElement elem = new TextDocumentMessageElement(WirePipeImpl.WIRE_HEADER_ELEMENT_NAME, asDoc, null); - Message msg = message.clone(); - - msg.replaceMessageElement(WirePipeImpl.WIRE_HEADER_ELEMENT_NAMESPACE, elem); - checkMessenger(); - try { - if (destMessenger instanceof TcpMessenger) { - ((TcpMessenger) destMessenger).sendMessageDirect(msg, null, null, true); - } else if (!destMessenger.sendMessage(msg, null, null)) { - throw new IOException("Pipe closed"); - } - } catch (IOException io) { - checkMessenger(); - if (!destMessenger.sendMessage(msg, null, null)) { - throw new IOException("Pipe closed"); - } - } - return true; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/InputPipeImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/InputPipeImpl.java deleted file mode 100644 index 0c318380..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/InputPipeImpl.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.Message; -import net.jxta.id.ID; -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.util.UnbiasedQueue; -import net.jxta.logging.Logging; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.PipeID; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.protocol.PipeAdvertisement; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Implements the {@link net.jxta.pipe.InputPipe} interface by listening on the - * endpoint for messages to service "PipeService" and a param of the Pipe ID. - */ -class InputPipeImpl implements EndpointListener, InputPipe { - - /** - * logger - */ - private final static Logger LOG = Logger.getLogger(InputPipeImpl.class.getName()); - - protected final static int QUEUESIZE = 100; - - protected PipeRegistrar registrar; - - protected final PipeAdvertisement pipeAdv; - protected final ID pipeID; - - protected volatile boolean closed = false; - - protected PipeMsgListener listener; - protected final UnbiasedQueue queue; - - /** - * Constructor for the InputPipeImpl object - * - * @param r pipe resolver - * @param adv pipe advertisement - * @param listener listener to receive messages - * @throws IOException if an io error occurs - */ - InputPipeImpl(PipeRegistrar r, PipeAdvertisement adv, PipeMsgListener listener) throws IOException { - registrar = r; - this.pipeAdv = adv; - this.listener = listener; - - pipeID = adv.getPipeID(); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info( - "Creating InputPipe for " + pipeID + " of type " + adv.getType() + " with " - + ((null != listener) ? "listener" : "queue")); - } - - // queue based inputpipe? - if (listener == null) { - queue = UnbiasedQueue.synchronizedQueue(new UnbiasedQueue(QUEUESIZE, true)); - } else { - queue = null; - } - - if (!registrar.register(this)) { - throw new IOException("Could not register input pipe (already registered) for " + pipeID); - } - } - - /** - * {@inheritDoc} - *

            - * Closes the pipe. - */ - @Override - protected synchronized void finalize() throws Throwable { - if (!closed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Pipe is being finalized without being previously closed. This is likely a bug."); - } - } - close(); - super.finalize(); - } - - /** - * {@inheritDoc} - */ - public Message waitForMessage() throws InterruptedException { - return poll(0); - } - - /** - * {@inheritDoc} - */ - public Message poll(int timeout) throws InterruptedException { - if (listener == null) { - return (Message) queue.pop(timeout); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("poll() has no effect in listener mode."); - } - return null; - } - } - - /** - * {@inheritDoc} - */ - public synchronized void close() { - if (closed) { - return; - } - closed = true; - - // Close the queue - if (null == listener) { - queue.close(); - } - - listener = null; - // Remove myself from the pipe registrar. - if (!registrar.forget(this)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("close() : pipe was not registered with registrar."); - } - } - registrar = null; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Closed " + pipeID); - } - } - - /** - * {@inheritDoc} - */ - public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { - // if we are closed, ignore any additional messages - if (closed) { - return; - } - - // XXX: header check, security and such should be done here - // before pushing the message onto the queue. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received " + msg + " from " + srcAddr + " for " + pipeID); - } - // determine where demux the msg, to listener, or onto the queue - if (null == queue) { - PipeMsgListener temp = listener; - if (null == temp) { - return; - } - - PipeMsgEvent event = new PipeMsgEvent(this, msg, (PipeID) pipeID); - try { - temp.pipeMsgEvent(event); - } catch (Throwable ignored) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in listener for : " + pipeID + "(" + temp.getClass().getName() + ")", ignored); - } - } - } else { - boolean pushed = false; - while (!pushed && !queue.isClosed()) { - try { - pushed = queue.push(msg, TimeUtils.ASECOND); - } catch (InterruptedException woken) { - Thread.interrupted(); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - synchronized (this) { - LOG.fine("Queued " + msg + " for " + pipeID + "\n\tqueue closed : " + queue.isClosed() + "\tnumber in queue : " - + queue.getCurrentInQueue() + "\tnumber queued : " + queue.getNumEnqueued() + "\tnumber dequeued : " - + queue.getNumDequeued()); - } - } - } - } - - /** - * Gets the pipe type - * - * @return The type - */ - public String getType() { - return pipeAdv.getType(); - } - - /** - * Gets the pipe id - * - * @return The type - */ - public ID getPipeID() { - return pipeID; - } - - /** - * Gets the pipe name - * - * @return The name - */ - public String getName() { - return pipeAdv.getName(); - } - - /** - * Gets the pipe advertisement - * - * @return The advertisement - */ - public PipeAdvertisement getAdvertisement() { - return pipeAdv; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/NonBlockingOutputPipe.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/NonBlockingOutputPipe.java deleted file mode 100644 index eccf5342..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/NonBlockingOutputPipe.java +++ /dev/null @@ -1,768 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.id.ID; -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.util.UnbiasedQueue; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.PipeID; -import net.jxta.protocol.PipeAdvertisement; - -import java.io.IOException; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * An implementation of Ouput Pipe which sends messages on the pipe - * asynchronously. The send() method for this implementation will - * never block. - */ -class NonBlockingOutputPipe implements PipeResolver.Listener, OutputPipe, Runnable { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(NonBlockingOutputPipe.class.getName()); - - /** - * Amount of time an idle worker thread will linger - */ - private static final long IDLEWORKERLINGER = 10 * TimeUtils.ASECOND; - - /** - * Minimum Query interval. Queries will not be sent more frequently than - * this interval. - */ - private static final long QUERYINTERVALMIN = 15 * TimeUtils.ASECOND; - - /** - * Query timeout minimum. Waits for query response will not be shorter than - * this interval. - */ - private static final long QUERYTIMEOUTMIN = 1 * TimeUtils.AMINUTE; - - /** - * If true then the pipe has been closed and will no longer accept messages. - */ - private volatile boolean closed = false; - - /** - * If true then this pipe has just migrated. Used to prevent re-entering - * migration from an unfinished migration. - */ - private boolean migrated = false; - - /** - * Group in which we are working. - */ - private PeerGroup peerGroup = null; - - /** - * The endpoint of our group. - */ - private EndpointService endpoint = null; - - /** - * The pipe resolver we will use for migrate and verify. - */ - private PipeResolver pipeResolver = null; - - /** - * The advertisement we were created from. - */ - private PipeAdvertisement pAdv = null; - - /** - * The current peer the pipe is resolved to. - */ - private ID destPeer = null; - - /** - * The set of peers to which the pipe can be resolved. - */ - private Set resolvablePeers = null; - - /** - * The endpoint destination address for the remote peer we are resolved to. - */ - private EndpointAddress destAddress = null; - private Messenger destMessenger = null; - - /** - * The worker thread which actually sends messages on the pipe - */ - private volatile Thread serviceThread = null; - - /** - * Absolute time in milliseconds at which we will send the next verify - * request. - */ - private long nextVerifyAt = 0; - - /** - * Queue of messages waiting to be sent. - */ - private final UnbiasedQueue queue = UnbiasedQueue.synchronizedQueue(new UnbiasedQueue(50, false)); - - /** - * Tracks the state of our worker thread. - */ - enum WorkerState { - /** - * Find a new eligible destination peer which is listening on the pipe. - */ - STARTMIGRATE, - - /** - * Issue resolution queries and wait for responses - */ - PENDINGMIGRATE, - - /** - * Determine if the destination peer is still listening on the pipe. - */ - STARTVERIFY, - - /** - * Issue verify queries and wait for responses - */ - PENDINGVERIFY, - - /** - * Acquire a messenger to the destination peer. - */ - ACQUIREMESSENGER, - - /** - * Send messages via the messenger to the destination peer. - */ - SENDMESSAGES, - - /** - * Exit. - */ - CLOSED - } - - /** - * The current state of the worker thread - */ - private WorkerState workerstate; - - /** - * The query id we are currently operating under. - */ - private int queryID = -1; - - /** - * Create a new output pipe - * - * @param peerGroup peergroup we are working in. - * @param pipeResolver the piperesolver this pipe is bound to. - * @param pAdv advertisement for the pipe we are supporting. - * @param destPeer the peer this pipe is currently bound to. - * @param peers the set of peers we allow this pipe to be bound to. - */ - public NonBlockingOutputPipe(PeerGroup peerGroup, PipeResolver pipeResolver, PipeAdvertisement pAdv, ID destPeer, Set peers) { - - this.peerGroup = peerGroup; - endpoint = peerGroup.getEndpointService(); - this.pipeResolver = pipeResolver; - - this.pAdv = pAdv; - this.destPeer = destPeer; - this.resolvablePeers = new HashSet(peers); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Constructing for " + getPipeID()); - } - workerstate = WorkerState.ACQUIREMESSENGER; - startServiceThread(); - } - - /** - * {@inheritDoc} - */ - @Override - protected void finalize() throws Throwable { - if (!closed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Pipe is being finalized without being previously closed. This is likely a bug."); - } - } - close(); - super.finalize(); - } - - /** - * {@inheritDoc} - */ - public synchronized void close() { - - // Close the queue so that no more messages are accepted - if (!closed) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Closing for " + getPipeID()); - } - queue.close(); - } - closed = true; - } - - /** - * {@inheritDoc} - */ - public boolean isClosed() { - return closed; - } - - /** - * {@inheritDoc} - */ - public final String getType() { - return pAdv.getType(); - } - - /** - * {@inheritDoc} - */ - public final ID getPipeID() { - return pAdv.getPipeID(); - } - - /** - * {@inheritDoc} - */ - public final String getName() { - return pAdv.getName(); - } - - /** - * {@inheritDoc} - */ - public final PipeAdvertisement getAdvertisement() { - return pAdv; - } - - /** - * {@inheritDoc} - */ - public boolean send(Message msg) throws IOException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Queuing " + msg + " for pipe " + getPipeID()); - } - - boolean pushed = false; - while (!queue.isClosed()) { - try { - pushed = queue.push(msg, 250 * TimeUtils.AMILLISECOND); - break; - } catch (InterruptedException woken) { - Thread.interrupted(); - } - } - - if (!pushed && queue.isClosed()) { - IOException failed = new IOException("Could not enqueue " + msg + " for sending. Pipe is closed."); - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, failed.getMessage(), failed); - } - throw failed; - } - startServiceThread(); - return pushed; - } - - /** - * {@inheritDoc} - *

            - * Sends the messages. - *

            - * This method does a lot of things. It has several distinct states: - *

            - * - * - * - * - * - * - * - *

            - *

            - * - * Acquire a messenger to the specified destination peer. If a - * messenger is acquired, then go to SENDMESSAGES state - * otherwise go to STARTMIGRATE. - * - *

            - *

            - * - * - * - *

            - *

            - * - * - * - *

            - *

            - * - * - * - *

            - *

            - * - * - * - *

            - *

            - * - * - * - *

            - *

            - * - * - * - * - *
            STATEActivity
            ACQUIREMESSENGER
            SENDMESSAGESSend messages until queue is closed and all messages have - * been sent. Go to state CLOSED when done. If the messenger - * becomes closed then go to ACQUIREMESSENGER. If - * there are no messages to send for IDLEWORKERLINGER - * milliseconds then the worker thread will exit. It will only be - * restarted if another message is eventually enqueued. - *
            STARTVERIFYStarts a verification query(s) to the destination peer. This - * state is activated after - * PipeServiceImpl.VERIFYINTERVAL milliseconds of - * sending messages. The query responses will be tracked in the - * PENDINGVERIFY state.
            STARTMIGRATEStarts a query(s) for peers listening on this pipe. The - * query responses will be tracked in the PENDINGMIGRATE - * state.
            PENDINGVERIFYIssues query messages to verify that the destination peer is - * still listening on the pipe. Queries are issued every - * QUERYINTERVAL milliseconds. If a positive response - * is received, go to state ACQUIREMESSENGER. If no response - * is received within QUERYTIMEOUT milliseconds or a - * negative response is received then go to state - * STARTMIGRATE.
            PENDINGMIGRATEIssues query messages to find a new destination peer. - * Queries are issued every QUERYINTERVAL milliseconds. - * If a positive response is received, go to state - * ACQUIREMESSENGER. If no positive response from an - * eligible peer is received within QUERYTIMEOUT - * milliseconds go to state CLOSED.
            CLOSEDExit the worker thread.
            - */ - public void run() { - long absoluteTimeoutAt = -1; - long nextQueryAt = -1; - - try { - // state loop - while (WorkerState.CLOSED != workerstate) { - synchronized (this) { - LOG.fine("NON-BLOCKING WORKER AT STATE : " + workerstate - + ((WorkerState.SENDMESSAGES == workerstate) - ? "\n\t" + TimeUtils.toRelativeTimeMillis(nextVerifyAt, TimeUtils.timeNow()) - + " until verify." - : "")); - - // switch() emulation - if ((WorkerState.STARTVERIFY == workerstate) || (WorkerState.STARTMIGRATE == workerstate)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - if (null == destPeer) { - LOG.fine("Starting re-resolve for \'" + getPipeID()); - } else { - LOG.fine("Starting verify for \'" + getPipeID() + "\' to : " + destPeer); - } - } - - queryID = PipeResolver.getNextQueryID(); - pipeResolver.addListener(getPipeID(), this, queryID); - absoluteTimeoutAt = TimeUtils.toAbsoluteTimeMillis( - Math.max(QUERYTIMEOUTMIN, (PipeServiceImpl.VERIFYINTERVAL / 20))); - nextQueryAt = TimeUtils.timeNow(); - - if (WorkerState.STARTVERIFY == workerstate) { - workerstate = WorkerState.PENDINGVERIFY; - } else if (WorkerState.STARTMIGRATE == workerstate) { - workerstate = WorkerState.PENDINGMIGRATE; - } - - // move on to the next state. - } else if ((WorkerState.PENDINGVERIFY == workerstate) || (WorkerState.PENDINGMIGRATE == workerstate)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Pipe " + ((WorkerState.PENDINGVERIFY == workerstate) ? "verify" : "migrate") - + "in progress. Continues for " - + TimeUtils.toRelativeTimeMillis(absoluteTimeoutAt, TimeUtils.timeNow()) - + "ms. Next query in " + TimeUtils.toRelativeTimeMillis(nextQueryAt, TimeUtils.timeNow()) - + "ms."); - } - - // check to see if we are completely done. - if (TimeUtils.toRelativeTimeMillis(absoluteTimeoutAt, TimeUtils.timeNow()) <= 0) { - pipeResolver.removeListener(getPipeID(), queryID); - - if (WorkerState.PENDINGVERIFY == workerstate) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Pipe \'" + getPipeID() + "\' has migrated from " + destPeer); - } - workerstate = WorkerState.STARTMIGRATE; - // move on to the next state. - continue; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Pipe \'" + getPipeID() + "\' cannot be migrated and is being closed"); - } - workerstate = WorkerState.CLOSED; - close(); - // move on to the next state. - continue; - } - } - - // check if its time ot send another copy of the query. - if (TimeUtils.toRelativeTimeMillis(nextQueryAt, TimeUtils.timeNow()) <= 0) { - if (null != destPeer) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Sending out verify query (" + queryID + ") for \'" + getPipeID() + "\' to : " - + destPeer); - } - pipeResolver.sendPipeQuery(pAdv, Collections.singleton(destPeer), queryID); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending out resolve query (" + queryID + ") for " + getPipeID()); - } - pipeResolver.sendPipeQuery(pAdv, resolvablePeers, queryID); - } - nextQueryAt = TimeUtils.toAbsoluteTimeMillis( - Math.max(QUERYINTERVALMIN, (PipeServiceImpl.VERIFYINTERVAL / 50))); - } - - long sleep = TimeUtils.toRelativeTimeMillis(Math.min(nextQueryAt, absoluteTimeoutAt), TimeUtils.timeNow()); - - if (sleep >= 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Waiting " + sleep + "ms for response for (" + queryID + ") for " + getPipeID()); - } - try { - wait(sleep); - } catch (InterruptedException woken) { - Thread.interrupted(); - } - } - - // move on to the next state. - } else if (WorkerState.ACQUIREMESSENGER == workerstate) { - if ((null == destMessenger) || destMessenger.isClosed()) { - destMessenger = null; - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting messenger to \'" + destPeer + "\' for pipe " + getPipeID()); - } - - destAddress = mkAddress(destPeer, getPipeID()); - // todo 20031011 bondolo@jxta.org This should not be done under sync - destMessenger = endpoint.getMessenger(destAddress); - if (destMessenger == null) { - // We could not get a messenger to the peer, forget it and try again. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not get messenger to : " + destPeer + ". "); - } - - if (migrated) { - // we can't migrate again, we never finished. - // the last migrate! - workerstate = WorkerState.CLOSED; - close(); - } else { - workerstate = WorkerState.STARTMIGRATE; - } - pipeResolver.removeListener((PipeID) getPipeID(), queryID); - queryID = -1; - destPeer = null; - destAddress = null; - - // move on to the next state. - continue; - } else { - // migration completed. - migrated = false; - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Using existing messenger to : " + destPeer); - } - } - - workerstate = WorkerState.SENDMESSAGES; - nextVerifyAt = TimeUtils.toAbsoluteTimeMillis(PipeServiceImpl.VERIFYINTERVAL); - - // move on to the next state. - continue; // can't just fall through because we would start sending messages immediately. - } else if (WorkerState.SENDMESSAGES == workerstate) { - // is it time to do verification again? - if (TimeUtils.toRelativeTimeMillis(nextVerifyAt, TimeUtils.timeNow()) <= 0) { - workerstate = WorkerState.STARTVERIFY; - pipeResolver.removeListener(getPipeID(), queryID); - queryID = -1; - } - // move on to the next state. - } else if (WorkerState.CLOSED == workerstate) { - queue.clear(); // they aren't going to be sent - if (null != destMessenger) { - destMessenger.close(); - destMessenger = null; - } - serviceThread = null; - break; - } else { - LOG.warning("Unrecognized state in worker thread : " + workerstate); - } - } - - // now actually send messages. We don't do this under the global sync. - if (WorkerState.SENDMESSAGES == workerstate) { - Message msg = null; - - try { - msg = (Message) queue.pop(IDLEWORKERLINGER); - } catch (InterruptedException woken) { - Thread.interrupted(); - continue; - } - - if (null == msg) { - synchronized (this) { - // before deciding to die, we need to make sure that - // nobody snuck something into the queue. If there - // is, then we have to be the one to service the - // queue. - if (null == queue.peek()) { - if (closed) { - workerstate = WorkerState.CLOSED; - continue; - } else { - serviceThread = null; - break; - } - } else { - continue; - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + " on " + getPipeID()); - } - - if (!destMessenger.isClosed()) { - try { - destMessenger.sendMessageB(msg, null, null); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure sending " + msg + " on " + getPipeID(), failed); - } - } - } - - // May be now closed due to failing to send. - if (destMessenger.isClosed()) { - synchronized (this) { - workerstate = WorkerState.ACQUIREMESSENGER; - destMessenger = null; - } - } - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - - // give another thread the chance to start unless one already has. - // If the exception was caused by damaged state on this object then - // starting a new Thread may just cause the same exception again. - // Unfortunate tradeoff. - synchronized (this) { - if (serviceThread == Thread.currentThread()) { - serviceThread = null; - } - } - } finally { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info( - "Thread exit : " + Thread.currentThread().getName() + "\n\tworker state : " + workerstate - + "\tqueue closed : " + queue.isClosed() + "\tnumber in queue : " + queue.getCurrentInQueue() - + "\tnumber queued : " + queue.getNumEnqueued() + "\tnumber dequeued : " + queue.getNumDequeued()); - } - } - } - - /** - * Starts the worker thread if it is not already running. - */ - private synchronized void startServiceThread() { - // if there is no service thread, start one. - if ((null == serviceThread) && !closed) { - serviceThread = new Thread(peerGroup.getHomeThreadGroup(), this - , - "Worker Thread for NonBlockingOutputPipe : " + getPipeID()); - serviceThread.setDaemon(true); - serviceThread.start(); - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info( - "Thread start : " + serviceThread.getName() + "\n\tworker state : " + workerstate + "\tqueue closed : " - + queue.isClosed() + "\tnumber in queue : " + queue.getCurrentInQueue() + "\tnumber queued : " - + queue.getNumEnqueued() + "\tnumber dequeued : " + queue.getNumDequeued()); - } - } - } - - /** - * Convenience method for constructing a peer endpoint address from its - * peer id - * - * @param destPeer the desitnation peer - * @param pipeID the pipe to put in the param field. - * @return the pipe endpoint address. - */ - protected EndpointAddress mkAddress(ID destPeer, ID pipeID) { - return new EndpointAddress("jxta", destPeer.getUniqueValue().toString(), "PipeService", pipeID.toString()); - } - - /** - * {@inheritDoc} - */ - public synchronized boolean pipeNAKEvent(PipeResolver.Event event) { - - if (((workerstate == WorkerState.PENDINGVERIFY) || (workerstate == WorkerState.ACQUIREMESSENGER) - || (workerstate == WorkerState.SENDMESSAGES)) - && (event.getPeerID().equals(destPeer) && (event.getQueryID() == queryID))) { - // we have been told that the destination peer no longer wants - // to talk with us. We will try to migrate to another peer. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Pipe \'" + getPipeID() + "\' is closed at " + event.getPeerID()); - } - - workerstate = WorkerState.STARTMIGRATE; - pipeResolver.removeListener(getPipeID(), queryID); - queryID = -1; - destPeer = null; - destAddress = null; - if (null != destMessenger) { - destMessenger.close(); - destMessenger = null; - } - notify(); - return true; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Ignoring NAK from " + event.getPeerID()); - } - - // didn't refer to us or we don't care. - return false; - } - - /** - * {@inheritDoc} - */ - public synchronized boolean pipeResolveEvent(PipeResolver.Event event) { - - if (((workerstate == WorkerState.PENDINGVERIFY) || (workerstate == WorkerState.PENDINGMIGRATE)) - && (event.getQueryID() == queryID)) { - if ((workerstate == WorkerState.PENDINGVERIFY) && !event.getPeerID().equals(destPeer)) { - // not from the right peer so ignore it. - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Ignoring response from " + event.getPeerID()); - } - return false; - } else { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Pipe \'" + getPipeID() + "\' is verified for " + destPeer); - } - } - - workerstate = WorkerState.ACQUIREMESSENGER; - migrated = true; - destPeer = event.getPeerID(); - - if ((workerstate == WorkerState.PENDINGMIGRATE) && Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Pipe \'" + getPipeID() + "\' has migrated to " + destPeer); - } - notify(); - return true; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Ignoring resolve from " + event.getPeerID()); - } - // didn't refer to us or we don't care. - return false; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/NonBlockingWireOutputPipe.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/NonBlockingWireOutputPipe.java deleted file mode 100644 index 93023f1c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/NonBlockingWireOutputPipe.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.document.MimeMediaType; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.ID; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.OutputPipe; -import net.jxta.protocol.PipeAdvertisement; - -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * An implementation of Ouput Pipe which sends messages on the pipe - * asynchronously. The send() method for this implementation will - * never block. - */ -class NonBlockingWireOutputPipe implements OutputPipe { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(NonBlockingWireOutputPipe.class.getName()); - - /** - * If true then the pipe has been closed and will no longer accept messages. - */ - private volatile boolean closed = false; - - /** - * Group in which we are working. - */ - private final PeerGroup peerGroup; - - /** - * The endpoint of our group. - */ - private final WirePipe wire; - - /** - * The advertisement we were created from. - */ - private final PipeAdvertisement pAdv; - - /** - * The set of peers to which messages on this pipe are sent. If empty then - * the message is sent to all propagation targets. - */ - private final Set destPeers; - - /** - * Create a new output pipe - * - * @param group The peergroup we are working in. - * @param wire The propagate pipe service. - * @param pAdv advertisement for the pipe we are supporting. - * @param peers the set of peers we allow this pipe to be bound to. - */ - public NonBlockingWireOutputPipe(PeerGroup group, WirePipe wire, PipeAdvertisement pAdv, Set peers) { - - peerGroup = group; - this.wire = wire; - this.destPeers = new HashSet(peers); - this.pAdv = pAdv; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Constructing for " + getPipeID()); - } - } - - /** - * {@inheritDoc} - */ - public synchronized void close() { - - // Close the queue so that no more messages are accepted - if (!closed) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Closing queue for " + getPipeID()); - } - } - closed = true; - } - - /** - * {@inheritDoc} - */ - public boolean isClosed() { - return closed; - } - - /** - * {@inheritDoc} - */ - public final String getType() { - return pAdv.getType(); - } - - /** - * {@inheritDoc} - */ - public final ID getPipeID() { - return pAdv.getPipeID(); - } - - /** - * {@inheritDoc} - */ - public final String getName() { - return pAdv.getName(); - } - - /** - * {@inheritDoc} - */ - public final PipeAdvertisement getAdvertisement() { - return pAdv; - } - - /** - * {@inheritDoc} - */ - public boolean send(Message message) throws IOException { - if (closed) { - // also throw it here to void the extra operations - throw new IOException("Pipe closed"); - } - - WireHeader header = new WireHeader(); - header.setPipeID(getPipeID()); - header.setSrcPeer(peerGroup.getPeerID()); - header.setTTL(destPeers.isEmpty() ? 200 : 1); - header.setMsgId(WirePipe.createMsgId()); - - XMLDocument asDoc = (XMLDocument) header.getDocument(MimeMediaType.XMLUTF8); - MessageElement elem = new TextDocumentMessageElement(WirePipeImpl.WIRE_HEADER_ELEMENT_NAME, asDoc, null); - - Message msg = message.clone(); - msg.replaceMessageElement(WirePipeImpl.WIRE_HEADER_ELEMENT_NAMESPACE, elem); - return sendUnModified(msg, header); - } - - /** - * Sends a message unaltered - * - * @param msg the message to send - * @return true if successful - * @throws IOException if an io error occurs - * @param header message header - */ - boolean sendUnModified(Message msg, WireHeader header) throws IOException { - if (closed) { - throw new IOException("Pipe closed"); - } - wire.sendMessage(msg, destPeers, header); - // we are here, there are not io exception, we assume it succeeded - return true; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeRegistrar.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeRegistrar.java deleted file mode 100644 index 71bd0f1d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeRegistrar.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.pipe.InputPipe; - -/** - * Interface for classes which manage input pipe registrations. - */ -interface PipeRegistrar { - - /** - * Register that this peer is an InputPipe for the specified Pipe ID. - * - * @param pipe The InputPipe to be registered. - * @return If {@code true} then the pipe was registered, otherwise - * {@code false}. - */ - boolean register(InputPipe pipe); - - /** - * This peer is no longer listening on the specified pipe. - * - * @param pipe The InputPipe to be forgotten. - * @return {@code true} if the pipe was removed otherwise {@code false}. - */ - boolean forget(InputPipe pipe); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeResolver.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeResolver.java deleted file mode 100644 index 768bb15b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeResolver.java +++ /dev/null @@ -1,1218 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.credential.Credential; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.OutgoingMessageEvent; -import net.jxta.id.ID; -import net.jxta.impl.cm.Srdi; -import net.jxta.impl.cm.Srdi.SrdiInterface; -import net.jxta.impl.cm.SrdiIndex; -import net.jxta.impl.protocol.PipeResolverMsg; -import net.jxta.impl.protocol.ResolverQuery; -import net.jxta.impl.protocol.SrdiMessageImpl; -import net.jxta.impl.resolver.InternalQueryHandler; -import net.jxta.impl.util.TimeUtils; -import net.jxta.logging.Logging; -import net.jxta.membership.MembershipService; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.PipeID; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.protocol.PipeResolverMessage; -import net.jxta.protocol.PipeResolverMessage.MessageType; -import net.jxta.protocol.ResolverQueryMsg; -import net.jxta.protocol.ResolverResponseMsg; -import net.jxta.protocol.ResolverSrdiMsg; -import net.jxta.protocol.SrdiMessage; -import net.jxta.protocol.SrdiMessage.Entry; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.rendezvous.RendezVousStatus; -import net.jxta.resolver.ResolverService; -import net.jxta.resolver.SrdiHandler; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EventListener; -import java.util.EventObject; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This class implements the Resolver interfaces for a PipeServiceImpl. - */ -class PipeResolver implements SrdiInterface, InternalQueryHandler, SrdiHandler, PipeRegistrar { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(PipeResolver.class.getName()); - - private final static String PipeResolverName = "JxtaPipeResolver"; - private final static String srdiIndexerFileName = "pipeResolverSrdi"; - - /** - * Local SRDI GC Interval - */ - private final static long GcDelay = 1 * TimeUtils.AMINUTE; - - /** - * Constant for pipe event listeners to signify any query id. - */ - final static int ANYQUERY = 0; - - /** - * The current query ID. The next value returned by {@link #getNextQueryID()} - * will be one greater than this value. - */ - private static int currentQueryID = 1; - - /** - * Group we are working for - */ - private PeerGroup myGroup = null; - /** - * Group we are working for - */ - private EndpointService endpoint = null; - - /** - * Resolver Service we will register with - */ - private ResolverService resolver = null; - - /** - * The discovery service we will use - */ - private DiscoveryService discovery = null; - - /** - * Membership Service we will use - */ - private MembershipService membership = null; - - private Srdi srdi = null; - private Thread srdiThread = null; - private SrdiIndex srdiIndex = null; - private RendezVousService rendezvous = null; - - /** - * The locally registered {@link net.jxta.pipe.InputPipe}s - */ - private final Map localInputPipes = new HashMap(); - - /** - * Registered listeners for pipe events. - */ - private final Map> outputpipeListeners = new HashMap>(); - - /** - * Encapsulates current Membership Service credential. - */ - final static class CurrentCredential { - /** - * The current default credential - */ - final Credential credential; - - /** - * The current default credential in serialized XML form. - */ - final XMLDocument credentialDoc; - - CurrentCredential(Credential credential, XMLDocument credentialDoc) { - this.credential = credential; - this.credentialDoc = credentialDoc; - } - } - - /** - * The current Membership service default credential. - */ - CurrentCredential currentCredential; - - /** - * Listener we use for membership property events. - */ - private class CredentialListener implements PropertyChangeListener { - - /** - * Standard Constructor - */ - CredentialListener() {} - - /** - * {@inheritDoc} - */ - public void propertyChange(PropertyChangeEvent evt) { - if (MembershipService.DEFAULT_CREDENTIAL_PROPERTY.equals(evt.getPropertyName())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("New default credential event"); - } - - synchronized (PipeResolver.this) { - Credential cred = (Credential) evt.getNewValue(); - XMLDocument credentialDoc; - - if (null != cred) { - try { - credentialDoc = (XMLDocument) cred.getDocument(MimeMediaType.XMLUTF8); - currentCredential = new CurrentCredential(cred, credentialDoc); - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not generate credential document", all); - } - currentCredential = null; - } - } else { - currentCredential = null; - } - } - } - } - } - - final CredentialListener membershipCredListener = new CredentialListener(); - - /** - * A pipe resolver event. - */ - static class Event extends EventObject { - - private final ID peerid; - private final ID pipeid; - private final String type; - private final int queryID; - - /** - * Creates a new pipe resolution event - * - * @param source The PipeResolver generating the event. - * @param peerid The peer on which the pipe was found - * @param pipeid the pipe which was found - * @param type the type of pipe which was found - * @param queryid The query id associated with the response returned in this event - */ - public Event(PipeResolver source, ID peerid, ID pipeid, String type, int queryid) { - super(source); - this.peerid = peerid; - this.pipeid = pipeid; - this.type = type; - this.queryID = queryid; - } - - /** - * Returns the peer associated with the event - * - * @return peerid - */ - public ID getPeerID() { - return peerid; - } - - /** - * Returns the pipe associated with the event - * - * @return pipeid - */ - public ID getPipeID() { - return pipeid; - } - - /** - * Returns the type of the pipe that is associated with the event - * - * @return type - */ - public String getType() { - return type; - } - - /** - * Returns The query id associated with the response returned in this event - * - * @return query id associated with the response - */ - public int getQueryID() { - return queryID; - } - } - - - /** - * Pipe Resolver Event Listener. Implement this interface is you wish to - * Receive Pipe Resolver events. - */ - interface Listener extends EventListener { - /** - * Pipe Resolve event - * - * @param event event the PipeResolver Event - * @return true if the event was handled otherwise false - */ - boolean pipeResolveEvent(Event event); - - /** - * A NAK Event was received for this pipe - * - * @param event event the PipeResolver Event - * @return true if the event was handled otherwise false - */ - boolean pipeNAKEvent(Event event); - } - - /** - * return the next query id. - * - * @return the next eligible query id. - */ - static synchronized int getNextQueryID() { - currentQueryID++; - if (currentQueryID == Integer.MAX_VALUE) { - currentQueryID = 1; - } - return currentQueryID; - } - - /** - * Constructor for the PipeResolver object - * - * @param peerGroup group for which this PipeResolver operates in - */ - PipeResolver(PeerGroup peerGroup) { - - myGroup = peerGroup; - resolver = myGroup.getResolverService(); - membership = myGroup.getMembershipService(); - rendezvous = myGroup.getRendezVousService(); - endpoint = myGroup.getEndpointService(); - - // Register to the Generic ResolverServiceImpl - resolver.registerHandler(PipeResolverName, this); - - // start srdi - srdiIndex = new SrdiIndex(myGroup, srdiIndexerFileName, GcDelay); - - srdi = new Srdi(myGroup, PipeResolverName, this, srdiIndex, 2 * TimeUtils.AMINUTE, 1 * TimeUtils.AYEAR); - srdiThread = new Thread(myGroup.getHomeThreadGroup(), srdi, "Pipe Resolver Srdi Thread"); - srdiThread.setDaemon(true); - srdiThread.start(); - - resolver.registerSrdiHandler(PipeResolverName, this); - synchronized (this) { - // register our credential listener. - membership.addPropertyChangeListener(MembershipService.DEFAULT_CREDENTIAL_PROPERTY, membershipCredListener); - try { - // set the initial version of the default credential. - currentCredential = null; - Credential credential = membership.getDefaultCredential(); - XMLDocument credentialDoc; - - if (null != credential) { - credentialDoc = (XMLDocument) credential.getDocument(MimeMediaType.XMLUTF8); - currentCredential = new CurrentCredential(credential, credentialDoc); - } - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "could not get default credential", all); - } - } - } - } - - private boolean isRendezvous() { - if (rendezvous == null) { - rendezvous = myGroup.getRendezVousService(); - } - RendezVousStatus mode = rendezvous.getRendezVousStatus(); - return (mode == RendezVousStatus.RENDEZVOUS ||mode == RendezVousStatus.AUTO_RENDEZVOUS); - } - - /** - * {@inheritDoc} - */ - public int processQuery(ResolverQueryMsg query) { - return processQuery(query, null); - } - - /** - * {@inheritDoc} - */ - public int processQuery(ResolverQueryMsg query, EndpointAddress srcAddr) { - - String queryFrom; - - if (null != srcAddr) { - if ("jxta".equals(srcAddr.getProtocolName())) { - queryFrom = ID.URIEncodingName + ":" + ID.URNNamespace + ":" + srcAddr.getProtocolAddress(); - } else { - // we don't know who routed us the query. Assume it came from the source. - queryFrom = query.getSrcPeer().toString(); - } - } else { - // we don't know who routed us the query. Assume it came from the source. - queryFrom = query.getSrcPeer().toString(); - } - - String responseDest = query.getSrcPeer().toString(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Starting for :" + query.getQueryId() + " from " + srcAddr); - } - - Reader queryReader = new StringReader(query.getQuery()); - StructuredTextDocument doc = null; - try { - doc = (StructuredTextDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, queryReader); - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "discarding malformed request ", e); - } - // no sense in re-propagation here - return ResolverService.OK; - } finally { - try { - queryReader.close(); - } catch (IOException ignored) { - // ignored - } - queryReader = null; - } - - PipeResolverMessage pipeQuery; - try { - pipeQuery = new PipeResolverMsg(doc); - } catch (IllegalArgumentException badDoc) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "discarding malformed request ", badDoc); - } - // no sense in re-propagation here - return ResolverService.OK; - } finally { - doc = null; - } - - // is it a query? - if (!pipeQuery.getMsgType().equals(MessageType.QUERY)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("expected query - discarding."); - } - // no sense in re-propagation here - return ResolverService.OK; - } - - // see if it is a query directed at our peer. - Set destPeers = pipeQuery.getPeerIDs(); - boolean directedQuery = !destPeers.isEmpty(); - boolean queryForMe = !directedQuery; - - if (directedQuery) { - for (Object destPeer : destPeers) { - ID aPeer = (ID) destPeer; - if (aPeer.equals(myGroup.getPeerID())) { - queryForMe = true; - break; - } - } - - if (!queryForMe) { - // It is an directed query, but request wasn't for this peer. - if (query.getSrcPeer().toString().equals(queryFrom)) { - // we only respond if the original src was not the query forwarder - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("discarding query. Query not for us."); - } - // tell the resolver no further action is needed. - return ResolverService.OK; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("responding to \'misdirected\' forwarded query."); - } - responseDest = queryFrom; - } - } - - PeerID peerID = null; - if (queryForMe) { - // look locally. - InputPipe ip = findLocal((PipeID) pipeQuery.getPipeID()); - if ((ip != null) && (ip.getType().equals(pipeQuery.getPipeType()))) { - peerID = myGroup.getPeerID(); - } - } - - if ((null == peerID) && !directedQuery) { - // This request was sent to everyone. - if (myGroup.isRendezvous()) { - // We are a RDV, allow the ResolverService to repropagate the query - List results = srdiIndex.query(pipeQuery.getPipeType(), PipeAdvertisement.IdTag, - pipeQuery.getPipeID().toString(), 20); - - if (!results.isEmpty()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("forwarding query to " + results.size() + " peers"); - } - srdi.forwardQuery(results, query); - // tell the resolver no further action is needed. - return ResolverService.OK; - } - - // we don't know anything, continue the walk. - return ResolverService.Repropagate; - } else { - // We are an edge - if (query.getSrcPeer().toString().equals(queryFrom)) { - // we only respond if the original src was not the query forwarder - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("discarding query."); - } - - // tell the resolver no further action is needed. - return ResolverService.OK; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("responding to query forwarded for \'misdirected\' query."); - } - responseDest = queryFrom; - } - } - - // Build the answer - PipeResolverMessage pipeResp = new PipeResolverMsg(); - - pipeResp.setMsgType(MessageType.ANSWER); - pipeResp.setPipeID(pipeQuery.getPipeID()); - pipeResp.setPipeType(pipeQuery.getPipeType()); - if (null == peerID) { - // respond negative. - pipeResp.addPeerID(myGroup.getPeerID()); - pipeResp.setFound(false); - } else { - pipeResp.addPeerID(peerID); - pipeResp.setFound(true); - pipeResp.setInputPeerAdv(myGroup.getPeerAdvertisement()); - } - - // make a response from the incoming query - ResolverResponseMsg res = query.makeResponse(); - - CurrentCredential current = currentCredential; - if (null != current) { - res.setCredential(current.credentialDoc); - } - res.setResponse(pipeResp.getDocument(MimeMediaType.XMLUTF8).toString()); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending answer for query \'" + query.getQueryId() + "\' to : " + responseDest); - } - resolver.sendResponse(responseDest, res); - return ResolverService.OK; - } - - /** - * {@inheritDoc} - */ - public void processResponse(ResolverResponseMsg response) { - processResponse(response, null); - } - - /** - * {@inheritDoc} - */ - public void processResponse(ResolverResponseMsg response, EndpointAddress srcAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("got a response for \'" + response.getQueryId() + "\'"); - } - - Reader resp = new StringReader(response.getResponse()); - StructuredTextDocument doc = null; - try { - doc = (StructuredTextDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, resp); - } catch (Throwable e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "malformed response - discard", e); - } - return; - } finally { - try { - resp.close(); - } catch (IOException ignored) {// ignored - } - resp = null; - } - - PipeResolverMessage pipeResp; - - try { - pipeResp = new PipeResolverMsg(doc); - } catch (Throwable caught) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "malformed response - discarding.", caught); - } - return; - } finally { - doc = null; - } - - // check if it's a response. - if (!pipeResp.getMsgType().equals(MessageType.ANSWER)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("expected response - discarding."); - } - return; - } - - PeerAdvertisement padv = pipeResp.getInputPeerAdv(); - - if ((null != padv) && !(myGroup.getPeerID().equals(padv.getPeerID()))) { - try { - // This is not our own peer adv so we keep it only for the default - // expiration time. - if (null == discovery) { - discovery = myGroup.getDiscoveryService(); - } - if (null != discovery) { - discovery.publish(padv, DiscoveryService.DEFAULT_EXPIRATION, DiscoveryService.DEFAULT_EXPIRATION); - } - } catch (IOException ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("could not publish peer adv"); - } - } - } - - String ipId = pipeResp.getPipeID().toString(); - - Set peerRsps = pipeResp.getPeerIDs(); - - for (Object peerRsp : peerRsps) { - // process each peer for which this response is about. - PeerID peer = (PeerID) peerRsp; - if (!pipeResp.isFound()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("NACK for pipe \'" + ipId + "\' from peer " + peer); - } - - // We have received a NACK. Remove that entry. - srdiIndex.add(pipeResp.getPipeType(), PipeAdvertisement.IdTag, ipId, peer, 0); - } else { - long exp = getEntryExp(pipeResp.getPipeType(), PipeAdvertisement.IdTag, ipId, peer); - if ((PipeServiceImpl.VERIFYINTERVAL / 2) > exp) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Using Expiration " + (PipeServiceImpl.VERIFYINTERVAL / 2) + " which is > " + exp); - } - // create antry only if one does not exist,or entry exists with - // lesser lifetime - // cache the result for half the verify interval - srdiIndex.add(pipeResp.getPipeType(), PipeAdvertisement.IdTag, ipId, peer, - (PipeServiceImpl.VERIFYINTERVAL / 2)); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("DB Expiration " + exp + " > " + (PipeServiceImpl.VERIFYINTERVAL / 2) - + " overriding attempt to decrease lifetime"); - } - } - } - - // call listener for pipeid - callListener(response.getQueryId(), pipeResp.getPipeID(), pipeResp.getPipeType(), peer, !pipeResp.isFound()); - } - } - - private long getEntryExp(String pkey, String skey, String value, PeerID peerid) { - List list = srdiIndex.getRecord(pkey, skey, value); - - for (SrdiIndex.Entry entry : list) { - if (entry.peerid.equals(peerid)) { - // exp in millis - return TimeUtils.toRelativeTimeMillis(entry.expiration); - } - } - return -1; - } - - /** - * {@inheritDoc} - */ - public boolean processSrdi(ResolverSrdiMsg message) { - - if (!isRendezvous()) { - // avoid caching in non rendezvous mode - return true; - } - if (message == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("no SRDI message"); - } - return false; - } - - if (message.getPayload() == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("empty SRDI message"); - } - return false; - } - - SrdiMessage srdiMsg; - try { - StructuredTextDocument asDoc = (StructuredTextDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, new StringReader(message.getPayload())); - srdiMsg = new SrdiMessageImpl(asDoc); - } catch (Throwable e) { - // we don't understand this msg, let's skip it - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Invalid SRDI message", e); - } - return false; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received an SRDI messsage with " + srdiMsg.getEntries().size() + " entries from " + srdiMsg.getPeerID()); - } - - for (Object o : srdiMsg.getEntries()) { - Entry entry = (Entry) o; - srdiIndex.add(srdiMsg.getPrimaryKey(), entry.key, entry.value, srdiMsg.getPeerID(), entry.expiration); - } - - if (!PipeService.PropagateType.equals(srdiMsg.getPrimaryKey())) { - // don't replicate entries for propagate pipes. For unicast type - // pipes the replica is useful in finding pipe instances. Since - // walking rather than searching is done for propagate pipes this - // appropriate. - srdi.replicateEntries(srdiMsg); - } - return true; - } - - /** - * {@inheritDoc} - */ - public void messageSendFailed(PeerID peerid, OutgoingMessageEvent e) {// so what. - } - - /** - * {@inheritDoc} - */ - public void pushEntries(boolean all) { - pushSrdi((PeerID) null, all); - } - - /** - * unregisters the resolver handler - */ - void stop() { - - resolver.unregisterHandler(PipeResolverName); - resolver.unregisterSrdiHandler(PipeResolverName); - - srdiIndex.stop(); - srdiIndex = null; - // stop the srdi thread - if (srdiThread != null) { - srdi.stop(); - } - srdiThread = null; - srdi = null; - - membership.removePropertyChangeListener("defaultCredential", membershipCredListener); - currentCredential = null; - - // Avoid cross-reference problems with GC - myGroup = null; - resolver = null; - discovery = null; - membership = null; - - outputpipeListeners.clear(); - - // close the local pipes - List openLocalPipes = new ArrayList(localInputPipes.values()); - for (InputPipe aPipe : openLocalPipes) { - try { - aPipe.close(); - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failure closing " + aPipe); - } - } - } - - localInputPipes.clear(); - } - - /** - * {@inheritDoc} - */ - public boolean register(InputPipe ip) { - - PipeID pipeID = (PipeID) ip.getPipeID(); - synchronized (this) { - if (localInputPipes.containsKey(pipeID)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Existing registered InputPipe for " + pipeID); - } - return false; - } - - // Register this input pipe - boolean registered = endpoint.addIncomingMessageListener((EndpointListener) ip, "PipeService", pipeID.toString()); - if (!registered) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Existing registered Endpoint Listener for " + pipeID); - } - return false; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Registering local InputPipe for " + pipeID); - } - localInputPipes.put(pipeID, ip); - } - - // Announce the pipe to SRDI so that others will know we are listening. - pushSrdi(ip, true); - - // Call anyone who may be listening for this input pipe. - callListener(0, pipeID, ip.getType(), myGroup.getPeerID(), false); - return true; - } - - /** - * Return the local {@link net.jxta.pipe.InputPipe InputPipe}, if any, for the - * specified {@link net.jxta.pipe.PipeID PipeID}. - * - * @param pipeID the PipeID who's InputPipe is desired. - * @return The InputPipe object. - */ - public InputPipe findLocal(PipeID pipeID) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Find local InputPipe for " + pipeID); - } - - // First look if the pipe is a local InputPipe - InputPipe ip = localInputPipes.get(pipeID); - // Found it. - if ((null != ip) && Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("found local InputPipe for " + pipeID); - } - return ip; - } - - /** - * {@inheritDoc} - */ - public boolean forget(InputPipe pipe) { - - PipeID pipeID = (PipeID) pipe.getPipeID(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unregistering local InputPipe for " + pipeID); - } - - // Unconditionally announce the change to SRDI. - // FIXME 20040529 bondolo This is overkill, it should be able to wait - // until the deltas are pushed. - pushSrdi(pipe, false); - - InputPipe ip; - - synchronized (this) { - ip = localInputPipes.remove(pipeID); - } - - if (pipe != ip) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Pipe removed was not the same as the pipe to be removed!"); - } - } - - if (null != ip) { - // remove the queue for the general demux - EndpointListener removed = endpoint.removeIncomingMessageListener("PipeService", pipeID.toString()); - - if ((null == removed) || (pipe != removed)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("removeIncomingMessageListener() did not remove correct pipe!"); - } - } - } - - return (ip != null); - } - - /** - * Add a pipe resolver listener - * - * @param listener listener - * @param queryID The query this callback is being made in response to. - * @param pipeID The pipe which is the subject of the event. - * @return true if sucessfully added - */ - synchronized boolean addListener(ID pipeID, Listener listener, int queryID) { - - Map perpipelisteners = outputpipeListeners.get(pipeID); - - // if no map for this pipeid, make one and add it to the top map. - if (null == perpipelisteners) { - perpipelisteners = new HashMap(); - outputpipeListeners.put(pipeID, perpipelisteners); - } - - boolean alreadyThere = perpipelisteners.containsKey(queryID); - - if (!alreadyThere) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("adding listener for " + pipeID + " / " + queryID); - } - - perpipelisteners.put(queryID, listener); - } - - return alreadyThere; - } - - /** - * Call the listener for the specified pipe id informing it about the - * specified peer. - * - * @param qid The query this callback is being made in response to. - * @param pipeID The pipe which is the subject of the event. - * @param type The type of the pipe which is the subject of the event. - * @param peer The peer on which the remote input pipe was found. - * @param NAK indicate whether the event is a nack - */ - void callListener(int qid, ID pipeID, String type, PeerID peer, boolean NAK) { - - Event newevent = new Event(this, peer, pipeID, type, qid); - boolean handled = false; - - while (!handled) { - Listener pipeListener; - - synchronized (this) { - Map perpipelisteners = outputpipeListeners.get(pipeID); - if (null == perpipelisteners) { - if ((ANYQUERY != qid) && Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No listener for pipe " + pipeID); - } - break; - } - pipeListener = perpipelisteners.get(qid); - } - - if (null != pipeListener) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Calling Pipe resolver listener " + (NAK ? "NAK " : "") + "for " + pipeID); - } - - try { - if (NAK) { - handled = pipeListener.pipeNAKEvent(newevent); - } else { - handled = pipeListener.pipeResolveEvent(newevent); - } - } catch (Throwable ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING - , - "Uncaught Throwable in listener for: " + pipeID + "(" + pipeListener.getClass().getName() + ")", ignored); - } - } - } - - // if we havent tried it already, try it with the ANYQUERY - if (ANYQUERY == qid) { - break; - } - qid = ANYQUERY; - } - } - - /** - * Remove a pipe resolver listener - * - * @param pipeID listener to remove - * @param queryID matching queryid. - * @return listener object removed - */ - synchronized Listener removeListener(ID pipeID, int queryID) { - - Map perpipelisteners = outputpipeListeners.get(pipeID); - - if (null == perpipelisteners) { - return null; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removing listener for " + pipeID + " / " + queryID); - } - Listener removedListener = perpipelisteners.remove(queryID); - - if (perpipelisteners.isEmpty()) { - outputpipeListeners.remove(pipeID); - } - - return removedListener; - } - - /** - * Send a request to find an input pipe - * - * @param adv the advertisement for the pipe we are seeking. - * @param acceptablePeers the set of peers at which we wish the pipe to - * be resolved. We will not accept responses from peers other than those - * in this set. Empty set means all peers are acceptable. - * @param queryID the query ID to use for the query. if zero then a query - * ID will be generated - * @return the query id under which the request was sent - */ - int sendPipeQuery(PipeAdvertisement adv, Set acceptablePeers, int queryID) { - - // choose a query id if non-prechosen. - if (0 == queryID) { - queryID = getNextQueryID(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine((acceptablePeers.isEmpty() ? "Undirected" : "Directed") + " query (" + queryID + ") for " + adv.getPipeID()); - } - - Collection targetPeers = new ArrayList(acceptablePeers); - - // check local srdi to see if we have a potential answer - List knownLocations = srdiIndex.query(adv.getType(), PipeAdvertisement.IdTag, adv.getPipeID().toString(), 100); - - if (!knownLocations.isEmpty()) { - // we think we know where the pipe might be... - - if (!acceptablePeers.isEmpty()) { - // only keep those peers which are acceptable. - knownLocations.retainAll(acceptablePeers); - } - - // if the known locations contain any of the acceptable peers then - // we will send a directed query to ONLY those peers. - if (!knownLocations.isEmpty()) { - targetPeers = knownLocations; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Using SRDI cache results for directed query (" + queryID + ") for " + adv.getPipeID()); - } - } - } - - // build the pipe query message. - PipeResolverMessage pipeQry = new PipeResolverMsg(); - - pipeQry.setMsgType(MessageType.QUERY); - pipeQry.setPipeID(adv.getPipeID()); - pipeQry.setPipeType(adv.getType()); - - for (Object targetPeer : targetPeers) { - pipeQry.addPeerID((PeerID) targetPeer); - } - - StructuredTextDocument asDoc = (StructuredTextDocument) pipeQry.getDocument(MimeMediaType.XMLUTF8); - - // build the resolver query - ResolverQuery query = new ResolverQuery(); - - query.setHandlerName(PipeResolverName); - query.setQueryId(queryID); - query.setSrcPeer(myGroup.getPeerID()); - query.setQuery(asDoc.toString()); - - CurrentCredential current = currentCredential; - - if (null != current) { - query.setCredential(current.credentialDoc); - } - - if (targetPeers.isEmpty()) { - // we have no idea, walk the tree - - if (myGroup.isRendezvous()) { - // We are a rdv, then send it to the replica peer. - - PeerID peer = srdi.getReplicaPeer(pipeQry.getPipeType() + PipeAdvertisement.IdTag + pipeQry.getPipeID().toString()); - if (null != peer) { - srdi.forwardQuery(peer, query); - return queryID; - } - } - - resolver.sendQuery(null, query); - } else { - // send it only to the peers whose result we would accept. - - for (ID targetPeer : targetPeers) { - resolver.sendQuery(targetPeer.toString(), query); - } - } - return queryID; - } - - /** - * {@inheritDoc} - */ - SrdiIndex getSrdiIndex() { - return srdiIndex; - } - - /** - * {@inheritDoc} - *

            - * This implementation knows nothing of deltas, it just pushes it all. - */ - private void pushSrdi(PeerID peer, boolean all) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Pushing " + (all ? "all" : "deltas") + " SRDI to " + peer); - } - - Map> types = new HashMap>(); - - synchronized (this) { - for (InputPipe ip : localInputPipes.values()) { - Entry entry = new Entry(PipeAdvertisement.IdTag, ip.getPipeID().toString(), Long.MAX_VALUE); - String type = ip.getType(); - List entries = types.get(type); - - if (null == entries) { - entries = new ArrayList(); - types.put(type, entries); - } - entries.add(entry); - } - } - - for (String type : types.keySet()) { - List entries = types.get(type); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending a Pipe SRDI messsage in " + myGroup.getPeerGroupID() + " of " + entries.size() + " entries of type " + type); - } - - SrdiMessage srdiMsg = new SrdiMessageImpl(myGroup.getPeerID(), 1, type, entries); - if (null == peer) { - srdi.pushSrdi(null, srdiMsg); - } else { - srdi.pushSrdi(peer, srdiMsg); - } - } - } - - /** - * Push SRDI entry for the specified pipe - * - * @param ip the pipe who's entry we are pushing - * @param adding adding an entry for the pipe or expiring the entry? - */ - private void pushSrdi(InputPipe ip, boolean adding) { - - srdiIndex.add(ip.getType(), PipeAdvertisement.IdTag, ip.getPipeID().toString(), myGroup.getPeerID(), - adding ? Long.MAX_VALUE : 0); - - SrdiMessage srdiMsg; - try { - srdiMsg = new SrdiMessageImpl(myGroup.getPeerID(), 1, // ttl - ip.getType(), PipeAdvertisement.IdTag, ip.getPipeID().toString(), adding ? Long.MAX_VALUE : 0); - - if (myGroup.isRendezvous()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Replicating a" + (adding ? "n add" : " remove") + " Pipe SRDI entry for pipe [" + ip.getPipeID() - + "] of type " + ip.getType()); - } - - srdi.replicateEntries(srdiMsg); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending a" + (adding ? "n add" : " remove") + " Pipe SRDI messsage for pipe [" + ip.getPipeID() - + "] of type " + ip.getType()); - } - srdi.pushSrdi(null, srdiMsg); - } - } catch (Throwable e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught throwable pushing SRDI entries", e); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeServiceImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeServiceImpl.java deleted file mode 100644 index e36833d0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeServiceImpl.java +++ /dev/null @@ -1,748 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.pipe; - - -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.util.TimeUtils; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.OutputPipeEvent; -import net.jxta.pipe.OutputPipeListener; -import net.jxta.pipe.PipeID; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.platform.Module; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.service.Service; -import net.jxta.peer.PeerID; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.text.MessageFormat; - - -/** - * A JXTA {@link net.jxta.pipe.PipeService} implementation which implements the - * standard JXTA Pipe Resolver Protocol (PRP). - *

            - * This class provides implementation for Unicast, unicast secure and - * (indirectly) propagate pipes. - * - * @see net.jxta.pipe.PipeService - * @see net.jxta.pipe.InputPipe - * @see net.jxta.pipe.OutputPipe - * @see net.jxta.endpoint.Message - * @see net.jxta.protocol.PipeAdvertisement - * @see net.jxta.protocol.PipeResolverMessage - * @see JXTA Protocols Specification : Pipe Binding Protocol - */ -public class PipeServiceImpl implements PipeService, PipeResolver.Listener { - - /** - * The Logger - */ - private final static Logger LOG = Logger.getLogger(PipeServiceImpl.class.getName()); - - /** - * the interval at which we verify that a pipe is still resolved at a - * remote peer. - */ - static final long VERIFYINTERVAL = 20 * TimeUtils.AMINUTE; - - /** - * The group this PipeService is working for. - */ - private PeerGroup group = null; - - /** - * Our resolver handler. - */ - private PipeResolver pipeResolver = null; - - /** - * Link to wire pipe impl. - */ - private WirePipeImpl wirePipe = null; - - /** - * the interface object we will hand out. - */ - private PipeService myInterface = null; - - /** - * the impl advertisement for this impl. - */ - private ModuleImplAdvertisement implAdvertisement = null; - - /** - * Table of listeners for asynchronous output pipe creation. - *

            - *

              - *
            • keys are {@link net.jxta.pipe.PipeID}
            • - *
            • values are {@link java.util.Map}
            • - *
            - * Within the value Map: - *
              - *
            • keys are {@link java.lang.Integer} representing queryid
            • - *
            • values are {@link OutputPipeHolder}
            • - *
            - */ - private final Map> outputPipeListeners = new HashMap>(); - - /** - * Has the pipe service been started? - */ - private volatile boolean started = false; - - /** - * holds a pipe adv and a listener which will be called for resolutions - * of the pipe. - */ - private static class OutputPipeHolder { - final PipeAdvertisement adv; - final Set peers; - final OutputPipeListener listener; - final int queryid; - - OutputPipeHolder(PipeAdvertisement adv, Set peers, OutputPipeListener listener, int queryid) { - this.adv = adv; - this.peers = peers; - this.listener = listener; - this.queryid = queryid; - } - } - - - /** - * A listener useful for implementing synchronous behaviour. - */ - private static class syncListener implements OutputPipeListener { - - volatile OutputPipeEvent event = null; - - syncListener() {} - - /** - * Called when a input pipe has been located for a previously registered - * pipe. The event contains an {@link net.jxta.pipe.OutputPipe} which can - * be used to communicate with the remote peer. - * - * @param event net.jxta.pipe.outputPipeEvent event - */ - public synchronized void outputPipeEvent(OutputPipeEvent event) { - // we only accept the first event. - if (null == this.event) { - this.event = event; - notifyAll(); - } - } - } - - /** - * Default Constructor (don't delete) - */ - public PipeServiceImpl() {// What is reason for this constructor??? - // the same is automatically generated. - } - - /** - * {@inheritDoc} - *

            - * We create only a single interface object and return it over and over - * again. - */ - public synchronized PipeService getInterface() { - if (null == myInterface) { - myInterface = new PipeServiceInterface(this); - } - return myInterface; - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * {@inheritDoc} - */ - public synchronized void init(PeerGroup group, ID assignedID, Advertisement impl) { - - this.group = group; - implAdvertisement = (ModuleImplAdvertisement) impl; - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Pipe Service : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tVerify Interval : " + VERIFYINTERVAL + "ms"); - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - *

            - * Currently this service does not expect arguments. - */ - public synchronized int startApp(String[] args) { - - Service needed = group.getEndpointService(); - - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - return START_AGAIN_STALLED; - } - - needed = group.getResolverService(); - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a resolver service"); - } - return START_AGAIN_STALLED; - } - - needed = group.getMembershipService(); - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a membership service"); - } - return START_AGAIN_STALLED; - } - - needed = group.getRendezVousService(); - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a rendezvous service"); - } - return START_AGAIN_STALLED; - } - - // create our resolver handler; it will register itself w/ the resolver. - pipeResolver = new PipeResolver(group); - - // Create the WirePipe (propagated pipe) - wirePipe = new WirePipeImpl(group, pipeResolver); - - // XXX 20061221 We could check the result of this. - wirePipe.startApp(args); - - started = true; - - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - public synchronized void stopApp() { - started = false; - - try { - if (wirePipe != null) { - wirePipe.stopApp(); - } - } catch (Throwable failed) { - LOG.log(Level.SEVERE, "Failed to stop wire pipe", failed); - } finally { - wirePipe = null; - } - - try { - if (pipeResolver != null) { - pipeResolver.stop(); - } - } catch (Throwable failed) { - LOG.log(Level.SEVERE, "Failed to stop pipe resolver", failed); - } finally { - pipeResolver = null; - } - - // Avoid cross-reference problem with GC - group = null; - myInterface = null; - - // clear outputPipeListeners - Collection> values = outputPipeListeners.values(); - - for (Map value : values) { - value.clear(); - } - outputPipeListeners.clear(); - } - - /** - * {@inheritDoc} - */ - public InputPipe createInputPipe(PipeAdvertisement adv) throws IOException { - return createInputPipe(adv, null); - } - - /** - * {@inheritDoc} - */ - public InputPipe createInputPipe(PipeAdvertisement adv, PipeMsgListener listener) throws IOException { - - if (!started) { - throw new IllegalStateException("Pipe Service has not been started or has been stopped"); - } - - String type = adv.getType(); - - if (type == null) { - throw new IllegalArgumentException("PipeAdvertisement type may not be null"); - } - - PipeID pipeId = (PipeID) adv.getPipeID(); - - if (pipeId == null) { - throw new IllegalArgumentException("PipeAdvertisement PipeID may not be null"); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Create " + type + " InputPipe for " + pipeId); - } - - InputPipe inputPipe; - // create an InputPipe. - if (type.equals(PipeService.UnicastType)) { - inputPipe = new InputPipeImpl(pipeResolver, adv, listener); - } else if (type.equals(PipeService.UnicastSecureType)) { - inputPipe = new SecureInputPipeImpl(pipeResolver, adv, listener); - } else if (type.equals(PipeService.PropagateType)) { - if (wirePipe != null) { - inputPipe = wirePipe.createInputPipe(adv, listener); - } else { - throw new IOException("No propagated pipe servive available"); - } - } else { - // Unknown type - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Cannot create pipe for unknown type : " + type); - } - throw new IOException("Cannot create pipe for unknown type : " + type); - } - return inputPipe; - } - - /** - * {@inheritDoc} - */ - public OutputPipe createOutputPipe(PipeAdvertisement pipeAdv, long timeout) throws IOException { - return createOutputPipe(pipeAdv, Collections.emptySet(), timeout); - } - - /** - * {@inheritDoc} - */ - public OutputPipe createOutputPipe(PipeAdvertisement adv, Set resolvablePeers, long timeout) throws IOException { - // convert zero to max value. - if (0 == timeout) { - timeout = Long.MAX_VALUE; - } - - long absoluteTimeOut = TimeUtils.toAbsoluteTimeMillis(timeout); - - // Make a listener, start async resolution and then wait until the timeout expires. - syncListener localListener = new syncListener(); - - int queryid = PipeResolver.getNextQueryID(); - - createOutputPipe(adv, resolvablePeers, localListener, queryid); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Waiting synchronously for " + timeout + "ms to resolve OutputPipe for " + adv.getPipeID()); - } - - try { - synchronized (localListener) { - while ((null == localListener.event) && (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), absoluteTimeOut) < 0)) { - try { - localListener.wait(TimeUtils.ASECOND); - } catch (InterruptedException woken) { - Thread.interrupted(); - } - } - } - } finally { - // remove the listener we installed. - removeOutputPipeListener(adv.getPipeID().toString(), queryid); - } - - if (null != localListener.event) { - return localListener.event.getOutputPipe(); - } else { - throw new IOException("Output Pipe could not be resolved after " + timeout + "ms."); - } - } - - /** - * {@inheritDoc} - */ - public void createOutputPipe(PipeAdvertisement pipeAdv, OutputPipeListener listener) throws IOException { - createOutputPipe(pipeAdv, Collections.emptySet(), listener); - } - - /** - * {@inheritDoc} - */ - public void createOutputPipe(PipeAdvertisement pipeAdv, Set resolvablePeers, OutputPipeListener listener) throws IOException { - createOutputPipe(pipeAdv, resolvablePeers, listener, PipeResolver.getNextQueryID()); - } - - private void createOutputPipe(PipeAdvertisement pipeAdv, Set resolvablePeers, OutputPipeListener listener, int queryid) throws IOException { - - if (!started) { - throw new IOException("Pipe Service has not been started or has been stopped"); - } - - // Recover the PipeId from the PipeServiceImpl Advertisement - PipeID pipeId = (PipeID) pipeAdv.getPipeID(); - String type = pipeAdv.getType(); - - if (null == type) { - IllegalArgumentException failed = new IllegalArgumentException("Pipe type was not set"); - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, failed.getMessage(), failed); - } - throw failed; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Create " + type + " OutputPipe for " + pipeId); - } - - if (PipeService.PropagateType.equals(type)) { - OutputPipe op; - - if (resolvablePeers.size() == 1) { - op = new BlockingWireOutputPipe(group, pipeAdv, (PeerID) resolvablePeers.iterator().next()); - } else { - if (wirePipe != null) { - op = wirePipe.createOutputPipe(pipeAdv, resolvablePeers); - } else { - throw new IOException("No propagated pipe service available"); - } - } - - if (null != op) { - OutputPipeEvent newevent = new OutputPipeEvent(this.getInterface(), op, pipeId.toString(), PipeResolver.ANYQUERY); - - try { - listener.outputPipeEvent(newevent); - } catch (Throwable ignored) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, - "Uncaught Throwable in listener for " + pipeId + " (" + listener.getClass().getName() + ")", - ignored); - } - } - } - } else if (PipeService.UnicastType.equals(type) || PipeService.UnicastSecureType.equals(type)) { - - addOutputPipeListener(pipeId, new OutputPipeHolder(pipeAdv, resolvablePeers, listener, queryid)); - pipeResolver.addListener(pipeId, this, queryid); - pipeResolver.sendPipeQuery(pipeAdv, resolvablePeers, queryid); - - // look locally for the pipe - if (resolvablePeers.isEmpty() || resolvablePeers.contains(group.getPeerID())) { - InputPipe local = pipeResolver.findLocal(pipeId); - - // if we have a local instance, make sure the local instance is of the same type. - if (null != local) { - if (local.getType().equals(pipeAdv.getType())) { - pipeResolver.callListener(queryid, pipeId, local.getType(), group.getPeerID(), false); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning(MessageFormat.format("rejecting local pipe ({0}) because type is not ({1})", local.getType(), - pipeAdv.getType())); - } - } - } - } - } else { - // Unknown type - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("createOutputPipe: cannot create pipe for unknown type : " + type); - } - throw new IOException("cannot create pipe for unknown type : " + type); - } - } - - /* - * Add an output listener for the given pipeId. - */ - private void addOutputPipeListener(PipeID pipeId, OutputPipeHolder pipeHolder) { - synchronized (outputPipeListeners) { - Map perpipelisteners = outputPipeListeners.get(pipeId); - - if (perpipelisteners == null) { - perpipelisteners = new HashMap(); - outputPipeListeners.put(pipeId, perpipelisteners); - } - if (perpipelisteners.get(pipeHolder.queryid) != null) { - LOG.warning("Clobbering output pipe listener for query " + pipeHolder.queryid); - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Adding pipe listener for pipe " + pipeId + " and query " + pipeHolder.queryid); - } - perpipelisteners.put(pipeHolder.queryid, pipeHolder); - } - } - - /** - * {@inheritDoc} - */ - public OutputPipeListener removeOutputPipeListener(String pipeID, OutputPipeListener listener) { - throw new UnsupportedOperationException("Legacy method not supported. Use interface object if you need this method."); - } - - /** - * {@inheritDoc} - */ - public OutputPipeListener removeOutputPipeListener(ID pipeID, OutputPipeListener listener) { - - // remove all instances of this listener, regardless of queryid - if (pipeResolver == null) { - return null; - } - - if (!(pipeID instanceof PipeID)) { - throw new IllegalArgumentException("pipeID must be a PipeID."); - } - - synchronized (outputPipeListeners) { - Map perpipelisteners = outputPipeListeners.get(pipeID); - - if (perpipelisteners != null) { - Set> entries = perpipelisteners.entrySet(); - - for (Map.Entry entry : entries) { - OutputPipeHolder pl = entry.getValue(); - - if (pl.listener == listener) { - pipeResolver.removeListener((PipeID) pipeID, pl.queryid); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing listener for query " + pl.queryid); - } - perpipelisteners.remove(entry.getKey()); - } - } - // clean up the map if there are no more listeners for the pipe - if (perpipelisteners.isEmpty()) { - outputPipeListeners.remove(pipeID); - } - } - } - return listener; - } - - private OutputPipeListener removeOutputPipeListener(String opID, int queryID) { - - if (pipeResolver == null) { - return null; - } - - PipeID pipeID; - try { - URI aPipeID = new URI(opID); - pipeID = (PipeID) IDFactory.fromURI(aPipeID); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad pipe ID: " + opID); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("id was not a pipe id: " + opID); - } - - synchronized (outputPipeListeners) { - Map perpipelisteners = outputPipeListeners.get(pipeID); - - if (perpipelisteners != null) { - OutputPipeHolder pipeHolder = perpipelisteners.get(queryID); - - perpipelisteners.remove(queryID); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing listener for query " + queryID); - } - // clean up the map if there are no more listeners for the pipe - if (perpipelisteners.isEmpty()) { - outputPipeListeners.remove(pipeID); - } - pipeResolver.removeListener(pipeID, queryID); - if (pipeHolder != null) { - return pipeHolder.listener; - } - } - - } - return null; - } - - /** - * {@inheritDoc} - */ - public boolean pipeResolveEvent(PipeResolver.Event event) { - - try { - ID peerID = event.getPeerID(); - ID pipeID = event.getPipeID(); - int queryID = event.getQueryID(); - OutputPipeHolder pipeHolder; - - synchronized (outputPipeListeners) { - Map perpipelisteners = outputPipeListeners.get(pipeID); - - if (perpipelisteners == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No listener for event for pipe " + pipeID); - } - return false; - } - pipeHolder = perpipelisteners.get(queryID); - if (pipeHolder == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No listener for event for query " + queryID); - } - return false; - } - } - - // check if they wanted a resolve from a specific peer. - if (!pipeHolder.peers.isEmpty() && !pipeHolder.peers.contains(peerID)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Event was for wrong peer \'" + peerID + "\'. Discarding."); - } - return false; - } - - // create op - String type = pipeHolder.adv.getType(); - OutputPipe op; - - if (PipeService.UnicastType.equals(type)) { - op = new NonBlockingOutputPipe(group, pipeResolver, pipeHolder.adv, peerID, pipeHolder.peers); - } else if (PipeService.UnicastSecureType.equals(type)) { - op = new SecureOutputPipe(group, pipeResolver, pipeHolder.adv, peerID, pipeHolder.peers); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not create output pipe of type \'" + type + "\'. Discarding."); - } - return false; - } - - // Generate an event when the output pipe was succesfully opened. - OutputPipeEvent newevent = new OutputPipeEvent(this.getInterface(), op, pipeID.toString(), queryID); - try { - pipeHolder.listener.outputPipeEvent(newevent); - } catch (Throwable ignored) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE - , - "Uncaught Throwable in listener for " + pipeID + "(" + pipeHolder.getClass().getName() + ")", ignored); - } - } - removeOutputPipeListener(pipeID.toString(), queryID); - return true; - } catch (IOException ie) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Error creating output pipe " + event.getPipeID(), ie); - } - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No listener for event for " + event.getPipeID()); - } - return false; - } - - /** - * {@inheritDoc} - *

            - * We don't do anything with NAKs (yet) - */ - public boolean pipeNAKEvent(PipeResolver.Event event) { - return false; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeServiceInterface.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeServiceInterface.java deleted file mode 100644 index b3626691..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/PipeServiceInterface.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.*; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.peer.PeerID; - -import java.io.IOException; -import java.net.URI; -import java.util.Set; -import net.jxta.protocol.ModuleImplAdvertisement; - -/** - * This class implements the Pipe interface. - */ -class PipeServiceInterface implements PipeService { - - PipeServiceImpl impl; - - /** - * The only authorized constructor. - * @param theRealThing the PipeService - */ - public PipeServiceInterface(PipeServiceImpl theRealThing) { - impl = theRealThing; - } - - /** - * {@inheritDoc} - *

            - * Since THIS is already such an object, it returns itself. - * FIXME: it is kind of absurd to have this method part of the - * interface but we do not want to define two levels of Service interface - * just for that. - * - * @return ResolverService An interface object that implements - * this service and nothing more. - */ - public PipeService getInterface() { - return this; - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return impl.getImplAdvertisement(); - } - - /** - * {@inheritDoc} - *

            - * FIXME: This is meaningless for the interface object; - * it is there only to satisfy the requirements of the - * interface that we implement. Ultimately, the API should define - * two levels of interfaces: one for the real service implementation - * and one for the interface object. Right now it feels a bit heavy - * to so that since the only different between the two would be - * init() and may-be getName(). - */ - public void init(PeerGroup pg, ID assignedID, Advertisement impl) {} - - /** - * {@inheritDoc} - *

            - * This is here for temporary class hierarchy reasons. - * it is ALWAYS ignored. By definition, the interface object - * protects the real object's start/stop methods from being called - */ - public int startApp(String[] arg) { - return 0; - } - - /** - * {@inheritDoc} - *

            - * This is here for temporary class hierarchy reasons. - * it is ALWAYS ignored. By definition, the interface object - * protects the real object's start/stop methods from being called - *

            - * This request is currently ignored. - */ - public void stopApp() {} - - /** - * {@inheritDoc} - */ - public InputPipe createInputPipe(PipeAdvertisement adv) throws IOException { - return impl.createInputPipe(adv); - } - - /** - * {@inheritDoc} - */ - public InputPipe createInputPipe(PipeAdvertisement adv, PipeMsgListener listener) throws IOException { - return impl.createInputPipe(adv, listener); - } - - /** - * {@inheritDoc} - */ - public OutputPipe createOutputPipe(PipeAdvertisement pipeAdv, long timeout) throws IOException { - return impl.createOutputPipe(pipeAdv, timeout); - } - - /** - * {@inheritDoc} - */ - public OutputPipe createOutputPipe(PipeAdvertisement adv, Set peers, long timeout) throws IOException { - return impl.createOutputPipe(adv, peers, timeout); - } - - /** - * {@inheritDoc} - */ - public void createOutputPipe(PipeAdvertisement pipeAdv, OutputPipeListener listener) throws IOException { - impl.createOutputPipe(pipeAdv, listener); - } - - /** - * {@inheritDoc} - */ - public void createOutputPipe(PipeAdvertisement adv, Set peers, OutputPipeListener listener) throws IOException { - impl.createOutputPipe(adv, peers, listener); - } - - /** - * {@inheritDoc} - */ - public OutputPipeListener removeOutputPipeListener(String pipeID, OutputPipeListener listener) { - return removeOutputPipeListener(ID.create(URI.create(pipeID)), listener); - } - - /** - * {@inheritDoc} - */ - public OutputPipeListener removeOutputPipeListener(ID pipeID, OutputPipeListener listener) { - return impl.removeOutputPipeListener(pipeID, listener); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/SecureInputPipeImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/SecureInputPipeImpl.java deleted file mode 100644 index 8bdaae84..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/SecureInputPipeImpl.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.impl.endpoint.tls.TlsTransport; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.protocol.PipeAdvertisement; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.IOException; - -/** - * Implements the {@link net.jxta.pipe.InputPipe} interface by listening on the - * endpoint for messages to service "PipeService" and a param of the Pipe ID. - */ -public class SecureInputPipeImpl extends InputPipeImpl { - private final static Logger LOG = Logger.getLogger(SecureInputPipeImpl.class.getName()); - - /** - * Constructor for the SecureInputPipeImpl object - * - * @param pipeResolver pipe resolver - * @param adv pipe advertisement - * @throws IOException if an io error occurs - */ - SecureInputPipeImpl(PipeResolver pipeResolver, PipeAdvertisement adv) throws IOException { - - this(pipeResolver, adv, null); - } - - /** - * Constructor for the SecureInputPipeImpl object - * @param r pipe resolver - * @param adv the pipe advertisement - * @param listener the message listener - * @throws IOException if an io error occurs - */ - SecureInputPipeImpl(PipeResolver r, PipeAdvertisement adv, PipeMsgListener listener) throws IOException { - - super(r, adv, listener); - } - - /** - * {@inheritDoc} - */ - @Override - public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - Object fromTLS = msg.getMessageProperty(TlsTransport.class); - - if (null != fromTLS) { - super.processIncomingMessage(msg, srcAddr, dstAddr); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("processIncomingMessage : Discarding " + msg + " because it did not come from TLS"); - } - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/SecureOutputPipe.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/SecureOutputPipe.java deleted file mode 100644 index 15775068..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/SecureOutputPipe.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.PipeAdvertisement; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.IOException; -import java.util.Set; - -/** - * This class implements the Secure non blocking Output Pipe - */ -class SecureOutputPipe extends NonBlockingOutputPipe { - - private static final Logger LOG = Logger.getLogger(SecureOutputPipe.class.getName()); - - public SecureOutputPipe(PeerGroup group, PipeResolver resolver, PipeAdvertisement pipeAdv, ID destPeer, Set peers) throws IOException { - super(group, resolver, pipeAdv, destPeer, peers); - } - - /** - * {@inheritDoc} - * - *

            - * We can't fail to send a message. Secure pipes are expected to be - * reliable and ordered. - */ - @Override - public synchronized boolean send(Message msg) throws IOException { - - boolean sent = false; - int attempts = 1; - - while (!sent && !isClosed()) { - try { - sent = super.send(msg); - - if (!sent) { - wait(10 + (1 << Math.min(attempts, 14))); - attempts++; - } - } catch (InterruptedException woken) { - Thread.interrupted(); - } - } - - if (!sent && isClosed()) { - IOException failed = new IOException("Could not enqueue " + msg + " for sending. Pipe is closed."); - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, failed.getMessage(), failed); - } - throw failed; - } - return sent; - } - - /** - * {@inheritDoc} - */ - @Override - protected EndpointAddress mkAddress(ID destPeer, ID pipeID) { - return new EndpointAddress("jxtatls", destPeer.getUniqueValue().toString(), "PipeService", pipeID.toString()); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/WireHeader.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/WireHeader.java deleted file mode 100644 index e6abfb4f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/WireHeader.java +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This class implements a JXTA-WIRE header. - */ -public class WireHeader { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(WireHeader.class.getName()); - - private static final String Name = "JxtaWire"; - private static final String MsgIdTag = "MsgId"; - private static final String PipeIdTag = "PipeId"; - private static final String SrcTag = "SrcPeer"; - private static final String TTLTag = "TTL"; - private static final String PeerTag = "VisitedPeer"; - - private ID srcPeer = ID.nullID; - private ID pipeID = ID.nullID; - private String msgId = null; - private int TTL = Integer.MIN_VALUE; - - public WireHeader() {} - - public WireHeader(Element root) { - initialize(root); - } - - public void setSrcPeer(ID p) { - srcPeer = p; - } - - public ID getSrcPeer() { - return srcPeer; - } - - public void setTTL(int t) { - TTL = t; - } - - public int getTTL() { - return TTL; - } - - public String getMsgId() { - return msgId; - } - - public void setMsgId(String id) { - this.msgId = id; - } - - public ID getPipeID() { - return pipeID; - } - - public void setPipeID(ID id) { - this.pipeID = id; - } - - /** - * Called to handle elements during parsing. - * - * @param elem Element to parse - * @return true if element was handled, otherwise false. - */ - protected boolean handleElement(XMLElement elem) { - if (elem.getName().equals(SrcTag)) { - try { - URI pID = new URI(elem.getTextValue()); - setSrcPeer(IDFactory.fromURI(pID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerID ID in header: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals(MsgIdTag)) { - msgId = elem.getTextValue(); - return true; - } - - if (elem.getName().equals(PipeIdTag)) { - try { - URI pipeID = new URI(elem.getTextValue()); - setPipeID(IDFactory.fromURI(pipeID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad pipe ID in header"); - } - return true; - } - - if (elem.getName().equals(TTLTag)) { - TTL = Integer.parseInt(elem.getTextValue()); - return true; - } - - // IGNORE obsolete element "VisitedPeer" - return elem.getName().equals(PeerTag); - - } - - /** - * internal method to process a document into a header. - * - * @param root where to start. - */ - protected void initialize(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - String doctype = doc.getName(); - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(Name) && !Name.equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.getName()); - } - } - } - - // Sanity Check! - - if (null == getMsgId()) { - throw new IllegalArgumentException("Header does not contain a message id"); - } - - if (ID.nullID == getPipeID()) { - throw new IllegalArgumentException("Header does not contain a pipe id"); - } - - if (TTL < 1) { - throw new IllegalArgumentException("TTL must be >= 1"); - } - } - - /** - * Returns the docment for this header - * - * @param encodeAs mime type encoding - * @return the docment for this header - */ - public Document getDocument(MimeMediaType encodeAs) { - StructuredTextDocument doc = (StructuredTextDocument) - StructuredDocumentFactory.newStructuredDocument(encodeAs, Name); - - if (doc instanceof XMLDocument) { - ((XMLDocument) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - if (null == getMsgId()) { - throw new IllegalStateException("Message id is not initialized"); - } - - if (ID.nullID == getPipeID()) { - throw new IllegalStateException("PipeID is not initialized"); - } - - if (TTL < 1) { - throw new IllegalStateException("TTL must be >= 1"); - } - - Element e; - if ((srcPeer != null) && (srcPeer != ID.nullID)) { - e = doc.createElement(SrcTag, srcPeer.toString()); - doc.appendChild(e); - } - - e = doc.createElement(PipeIdTag, getPipeID().toString()); - doc.appendChild(e); - - e = doc.createElement(MsgIdTag, getMsgId()); - doc.appendChild(e); - - e = doc.createElement(TTLTag, Integer.toString(TTL)); - doc.appendChild(e); - - return doc; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/WirePipe.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/WirePipe.java deleted file mode 100644 index 22dbbe38..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/WirePipe.java +++ /dev/null @@ -1,557 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.*; -import net.jxta.id.ID; -import net.jxta.impl.cm.SrdiIndex; -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.id.UUID.UUIDFactory; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.rendezvous.RendezVousService; - -import java.io.IOException; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * WirePipe (aka Propagated pipe) is very similar to IGMP, where a creation of an - * input pipe results in a propagated pipe membership registration with the peer's - * rendezvous peer, and a closure results in a propagated pipe group resignation, - * these group registration/resignation are simply PipeService SRDI messages. - */ -public class WirePipe implements EndpointListener, InputPipe, PipeRegistrar { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(WirePipe.class.getName()); - - /** - * The number of message ID we track to eliminate duplicate messages. - */ - private static final int MAX_RECORDED_MSGIDS = 250; - - private volatile boolean closed = false; - - private final PeerGroup peerGroup; - private final PipeResolver pipeResolver; - private final WirePipeImpl wireService; - private final PipeAdvertisement pipeAdv; - - private final RendezVousService rendezvous; - private final PeerID localPeerId; - private NonBlockingWireOutputPipe repropagater; - int messagesReceived = 0; - - /** - * Table of local input pipes listening on this pipe. Weak map (used as a - * Set) so that we don't keep pipes unnaturally alive and consuming - * resources. - */ - private final Map wireinputpipes = new WeakHashMap(); - - /** - * The list of message ids we have already seen. The most recently seen - * messages are at the end of the list. - *

            - * XXX 20031102 bondolo@jxta.org: We might want to consider three - * performance enhancements: - *

            - *

              - *
            • Reverse the order of elements in the list. This would result - * in faster searching since the default strategy for ArrayList to - * search in index order. We are most likely to see duplicate messages - * amongst the messages we have seen recently. This would make - * additions more costly.
            • - *

              - *

            • When we do find a duplicate in the list, exchange it's location - * with the newest message in the list. This will keep annoying dupes - * close to the start of the list.
            • - *

              - *

            • When the array reaches MaxNbOfStoredIds treat it as a ring.
            • - *
            - */ - private final List msgIds = new ArrayList(MAX_RECORDED_MSGIDS); - - /** - * Constructor - * - * @param group The Group associated with this service - * @param pipeResolver the associated pipe resolver - * @param wireService The pipe service associated with this pipe - * @param adv pipe advertisement - */ - public WirePipe(PeerGroup group, PipeResolver pipeResolver, WirePipeImpl wireService, PipeAdvertisement adv) { - this.peerGroup = group; - this.pipeResolver = pipeResolver; - this.wireService = wireService; - this.pipeAdv = adv; - localPeerId = peerGroup.getPeerID(); - rendezvous = group.getRendezVousService(); - } - - /** - * {@inheritDoc} - *

            - * Closes the pipe. - */ - @Override - protected synchronized void finalize() throws Throwable { - - if (!closed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Pipe is being finalized without being previously closed. This is likely a bug."); - } - } - close(); - super.finalize(); - } - - /** - * {@inheritDoc} - */ - public synchronized boolean register(InputPipe wireinputpipe) { - if (closed) { - return false; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Registering input pipe for " + pipeAdv.getPipeID()); - } - - wireinputpipes.put(wireinputpipe, null); - boolean registered; - if (1 == wireinputpipes.size()) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Registering " + pipeAdv.getPipeID() + " with pipe resolver."); - } - registered = pipeResolver.register(this); - } else { - registered = true; - } - return registered; - } - - /** - * {@inheritDoc} - */ - public synchronized boolean forget(InputPipe wireinputpipe) { - boolean removed = null != wireinputpipes.remove(wireinputpipe); - - if (wireinputpipes.isEmpty()) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Deregistering wire pipe with pipe resolver"); - } - pipeResolver.forget(this); - } - - if (removed && Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removed input pipe for " + pipeAdv.getPipeID()); - } - return removed; - } - - // This is the InputPipe API implementation. - // This is needed only to be able to register an InputPipe to the PipeResolver. - // Not everything has to be implemented. - - /** - * {@inheritDoc} - */ - public Message waitForMessage() throws InterruptedException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("This method is not really supported."); - } - return null; - } - - /** - * {@inheritDoc} - */ - public Message poll(int timeout) throws InterruptedException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("This method is not really supported."); - } - return null; - } - - /** - * {@inheritDoc} - */ - public synchronized void close() { - if (closed) { - return; - } - - closed = true; - - if (null != repropagater) { - repropagater.close(); - repropagater = null; - } - - List inputPipes = new ArrayList(wireinputpipes.keySet()); - - for (InputPipe anInputPipe : inputPipes) { - anInputPipe.close(); - } - - wireinputpipes.clear(); - msgIds.clear(); - wireService.forgetWirePipe(pipeAdv.getPipeID()); - } - - /** - * {@inheritDoc} - */ - public String getType() { - return pipeAdv.getType(); - } - - /** - * {@inheritDoc} - */ - public ID getPipeID() { - return pipeAdv.getPipeID(); - } - - /** - * {@inheritDoc} - */ - public String getName() { - return pipeAdv.getName(); - } - - /** - * {@inheritDoc} - */ - public PipeAdvertisement getAdvertisement() { - return pipeAdv; - } - - /** - * {@inheritDoc} - *

            - * Handler for messages received through the normal pipe endpoint - * listener. - *

            - * "PipeService" / <PipeID> - */ - public void processIncomingMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - // Check if there is a JXTA-WIRE header - MessageElement elem = message.getMessageElement(WirePipeImpl.WIRE_HEADER_ELEMENT_NAMESPACE, - WirePipeImpl.WIRE_HEADER_ELEMENT_NAME); - - if (null == elem) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No JxtaWireHeader element. Discarding " + message); - } - return; - } - - WireHeader header; - try { - XMLDocument doc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(elem); - header = new WireHeader(doc); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "bad wire header", e); - } - return; - } - processIncomingMessage(message, header, srcAddr, dstAddr); - } - - /** - * local version with the wire header already parsed. There are two paths - * to this point; via the local endpoint listener or via the general - * propagation listener in WirePipeImpl. - * - * @param message the message - * @param header the wire header - * @param srcAddr source - * @param dstAddr destination - */ - void processIncomingMessage(Message message, WireHeader header, EndpointAddress srcAddr, EndpointAddress dstAddr) { - if (recordSeenMessage(header.getMsgId())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Discarding duplicate " + message); - } - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Processing " + message + " from " + srcAddr + " on " + pipeAdv.getPipeID()); - } - callLocalListeners(message, srcAddr, dstAddr); - if (peerGroup.isRendezvous()) { - repropagate(message, header); - } - } - - /** - * Calls the local listeners for a given pipe. - * - * @param message the message - * @param srcAddr source The peer which sent us the message (last hop). - * @param dstAddr dest The wire pipe the message was sent to. - */ - private void callLocalListeners(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - List listeners = new ArrayList(wireinputpipes.keySet()); - if (listeners.isEmpty()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No local listeners for " + pipeAdv.getPipeID()); - } - } else { - int listenersCalled = 0; - for (InputPipeImpl anInputPipe : listeners) { - try { - anInputPipe.processIncomingMessage(message.clone(), srcAddr, dstAddr); - listenersCalled++; - } catch (Throwable ignored) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable during callback (" + anInputPipe + ") for " + anInputPipe.getPipeID(), ignored); - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Called " + listenersCalled + " of " + listeners.size() + " local listeners for " + pipeAdv.getPipeID()); - } - } - } - - /** - * Repropagate a message. - * - * @param message the message - * @param header the header - */ - void repropagate(Message message, WireHeader header) { - - if (closed) { - return; - } - - if ((header.getTTL() <= 1)) { - // This message has run out of fuel. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No TTL remaining - discarding " + message + " on " + header.getPipeID()); - } - return; - } - - Message msg = message.clone(); - header.setTTL(header.getTTL() - 1); - XMLDocument headerDoc = (XMLDocument) header.getDocument(MimeMediaType.XMLUTF8); - MessageElement elem = new TextDocumentMessageElement(WirePipeImpl.WIRE_HEADER_ELEMENT_NAME, headerDoc, null); - - msg.replaceMessageElement(WirePipeImpl.WIRE_HEADER_ELEMENT_NAMESPACE, elem); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Repropagating " + msg + " on " + header.getPipeID()); - } - - synchronized (this) { - if (closed) { - return; - } - if (null == repropagater) { - repropagater = wireService.createOutputPipe(pipeAdv, Collections.EMPTY_SET); - } - } - - try { - if (!repropagater.sendUnModified(msg, header)) { - // XXX bondolo@jxta.org we don't make any attempt to retry. - // There is a potential problem in that we have accepted the - // message locally but didn't resend it. If we get another copy - // of this message then we will NOT attempt to repropagate it - // even if we should. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failure repropagating " + msg + " on " + header.getPipeID() + ". Could not queue message."); - } - } - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure repropagating " + msg + " on " + header.getPipeID(), failed); - } - } - } - - /** - * Sends a message on the propagated pipe. if set is not empty, then the - * message is sent to set of peers. - * - * @param message The message to send. - * @param peers The peers to which the message will be sent. If the - * set is empty then the message is sent to all members of the pipe that are - * connected to the rendezvous, as well as walk the message through the network - * @param header message header - * @throws java.io.IOException if an io error occurs - */ - void sendMessage(Message message, Set peers, WireHeader header) throws IOException { - message = message.clone(); - - // do local listeners if we are to be one of the destinations - if (peers.isEmpty() || peers.contains(localPeerId)) { - if (!recordSeenMessage(header.getMsgId())) { - callLocalListeners(message, new EndpointAddress(localPeerId, null, null), - new EndpointAddress(pipeAdv.getPipeID(), null, null)); - } - } - - if (peers.isEmpty()) { - if (peerGroup.isRendezvous()) { - // propagate to my clients - SrdiIndex srdiIndex = pipeResolver.getSrdiIndex(); - List peerids = srdiIndex.query(PipeService.PropagateType, PipeAdvertisement.IdTag, getPipeID().toString(), - Integer.MAX_VALUE); - - peerids.retainAll(rendezvous.getConnectedPeerIDs()); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Propagating " + message + " to " + peerids.size() + " subscriber peers."); - } - rendezvous.propagate(Collections.enumeration(peerids), message, WirePipeImpl.WIRE_SERVICE_NAME, - wireService.getServiceParameter(), 1); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Propagating " + message + " to whole network."); - } - // propagate to local sub-net - rendezvous.propagateToNeighbors(message, WirePipeImpl.WIRE_SERVICE_NAME, wireService.getServiceParameter(), - RendezVousService.DEFAULT_TTL); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Walking " + message + " through peerview."); - } - // walk the message through rdv network (edge, or rendezvous) - rendezvous.walk(message, WirePipeImpl.WIRE_SERVICE_NAME, wireService.getServiceParameter(), - RendezVousService.DEFAULT_TTL); - } else { - // Send to specific peers - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Propagating " + message + " to " + peers.size() + " peers."); - } - rendezvous.propagate(Collections.enumeration(peers), message, WirePipeImpl.WIRE_SERVICE_NAME, - wireService.getServiceParameter(), 1); - } - } - - /** - * Create a unique (mostly) identifier for this message - * - * @return a message sequence uuid - */ - static String createMsgId() { - return UUIDFactory.newSeqUUID().toString(); - } - - /** - * Adds a message ID to our table or stored IDs. - * - * @param id to add. - * @return false if ID was added, true if it was a duplicate. - */ - private boolean recordSeenMessage(String id) { - - UUID msgid; - try { - msgid = new UUID(id); - } catch (IllegalArgumentException notauuid) { - // XXX 20031024 bondolo@jxta.org these two conversions are provided - // for backwards compatibility and should eventually be removed. - try { - msgid = UUIDFactory.newHashUUID(Long.parseLong(id), 0); - } catch (NumberFormatException notanumber) { - msgid = UUIDFactory.newHashUUID(id.hashCode(), 0); - } - } - synchronized (msgIds) { - if (msgIds.contains(msgid)) { - // Already there. Nothing to do - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("duplicate " + msgid); - } - return true; - } - if (msgIds.size() < MAX_RECORDED_MSGIDS) { - msgIds.add(msgid); - } else { - msgIds.set((messagesReceived % MAX_RECORDED_MSGIDS), msgid); - } - messagesReceived++; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("added " + msgid); - } - return false; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/WirePipeImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/WirePipeImpl.java deleted file mode 100644 index c976b54d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/WirePipeImpl.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.pipe; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.id.ID; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.platform.Module; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.rendezvous.RendezVousService; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * The Wire (Propagated) Pipe Service. - */ -public class WirePipeImpl implements EndpointListener { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(WirePipeImpl.class.getName()); - - /** - * Service name we register our listener with. - */ - final static String WIRE_SERVICE_NAME = "jxta.service.wirepipe"; - - /** - * Service param we register our listener with. - *

            - * Including the wireParam as part of the destination endpoint address - * is needed only for backwards compatibility with legacy version of JXTA. - * The wireParam is no longer registered as part of the endpoint listener - * address. - */ - private final String wireParam; - - /** - * The Message namespace we use for passing the wire header. - */ - final static String WIRE_HEADER_ELEMENT_NAMESPACE = "jxta"; - - /** - * The Message Element name we use for passing the wire header. - */ - final static String WIRE_HEADER_ELEMENT_NAME = "JxtaWireHeader"; - - /** - * The wire pipes we know of. - */ - private final Map wirePipes = new HashMap(); - - private final PeerGroup group; - private final PipeResolver pipeResolver; - - private EndpointService endpoint = null; - private RendezVousService rendezvous = null; - - /** - * @param group Description of the Parameter - * @param pipeResolver Description of the Parameter - */ - WirePipeImpl(PeerGroup group, PipeResolver pipeResolver) { - this.group = group; - this.pipeResolver = pipeResolver; - this.wireParam = group.getPeerGroupID().getUniqueValue().toString(); - } - - /** - * To support WirePipe.send(Message, Enumeration) - * - * @return The serviceParameter value - */ - public String getServiceParameter() { - return wireParam; - } - - /** - * Supply arguments and starts this service if it hadn't started by itself. - *

            - * Currently this service does not expect arguments. - * - * @param arg A table of strings arguments. - * @return int status indication. - */ - public int startApp(String[] arg) { - endpoint = group.getEndpointService(); - - if (null == endpoint) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - return Module.START_AGAIN_STALLED; - } - - rendezvous = group.getRendezVousService(); - if (null == rendezvous) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a rendezvous service"); - } - return Module.START_AGAIN_STALLED; - } - - // Set our Endpoint Listener - try { - endpoint.addIncomingMessageListener(this, WIRE_SERVICE_NAME, null); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed registering Endpoint Listener", e); - } - throw new IllegalStateException("Failed registering Endpoint Listener"); - } - return Module.START_OK; - } - - /** - * Ask this service to stop. - */ - public void stopApp() { - Collection allWirePipes = new ArrayList(wirePipes.values()); - - for (WirePipe aWirePipe : allWirePipes) { - // Close all of the wire pipes. - aWirePipe.close(); - } - wirePipes.clear(); - - // Clear our listener - endpoint.removeIncomingMessageListener(WIRE_SERVICE_NAME, null); - - endpoint = null; - rendezvous = null; - } - - /** - * create an InputPipe from a pipe Advertisement - * - * @param adv is the advertisement of the PipeServiceImpl. - * @param listener PipeMsgListener to receive msgs. - * @return InputPipe InputPipe object created - * @throws IOException error creating input pipe - */ - InputPipe createInputPipe(PipeAdvertisement adv, PipeMsgListener listener) throws IOException { - WirePipe wirePipe = getWirePipe(adv); - return new InputPipeImpl(wirePipe, adv, listener); - } - - /** - * create an OutputPipe from the pipe Advertisement giving a PeerId(s) - * where the corresponding InputPipe is supposed to be. - * - * @param adv is the advertisement of the NetPipe. - * @param peers is a set of the PeerId of the peers where to look - * for the corresponding Pipes - * @return OuputPipe corresponding OutputPipe - */ - NonBlockingWireOutputPipe createOutputPipe(PipeAdvertisement adv, Set peers) { - WirePipe wirePipe = getWirePipe(adv); - return new NonBlockingWireOutputPipe(group, wirePipe, adv, peers); - } - - /** - * PropagateType pipes - * - * @param adv the pipe adv - * @return the wire pipe - */ - private WirePipe getWirePipe(PipeAdvertisement adv) { - WirePipe wirePipe; - - synchronized (wirePipes) { - // First see if we have already a WirePipe for this pipe - wirePipe = wirePipes.get(adv.getPipeID()); - - if (null == wirePipe) { - // No.. There is none. Create a new one. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Creating new wire pipe for " + adv.getPipeID()); - } - wirePipe = new WirePipe(group, pipeResolver, this, adv); - wirePipes.put(adv.getPipeID(), wirePipe); - } - } - return wirePipe; - } - - /** - * PropagateType pipes - * - * @param pipeID Pipe ID - * @param create if true create one if one does not exist - * @return the wire pipe - */ - private WirePipe getWirePipe(ID pipeID, boolean create) { - WirePipe wirePipe; - - synchronized (wirePipes) { - // First see if we have already a WirePipe for this pipe - wirePipe = wirePipes.get(pipeID); - - if ((null == wirePipe) && create) { - // No.. There is none. Create a new one. - // XXX 20031019 bondolo@jxta.org Check for the adv in local discovery maybe? - PipeAdvertisement adv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement( - PipeAdvertisement.getAdvertisementType()); - - adv.setPipeID(pipeID); - adv.setType(PipeService.PropagateType); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Creating new wire pipe for " + adv.getPipeID()); - } - wirePipe = new WirePipe(group, pipeResolver, this, adv); - wirePipes.put(pipeID, wirePipe); - } - } - return wirePipe; - } - - /** - * Remove a wire pipe from our collection of wire pipes. - * - * @param pipeID The ID of the wire pipe to forget. - * @return {@code true} if the wire pipe had been registered otherwise - * {@code false}. - */ - boolean forgetWirePipe(ID pipeID) { - synchronized (wirePipes) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removing wire pipe for " + pipeID); - } - return null != wirePipes.remove(pipeID); - } - } - - /** - * {@inheritDoc} - *

            - * Listener for "jxta.service.wirepipe" / <null> - */ - public void processIncomingMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - // Check if there is a JXTA-WIRE header - MessageElement elem = message.getMessageElement(WIRE_HEADER_ELEMENT_NAMESPACE, WIRE_HEADER_ELEMENT_NAME); - - if (null == elem) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No JxtaWireHeader element. Discarding " + message); - } - return; - } - - WireHeader header; - - try { - XMLDocument doc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(elem); - header = new WireHeader(doc); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "bad wire header for " + message, e); - } - return; - } - - WirePipe wirePipe = getWirePipe(header.getPipeID(), rendezvous.isRendezVous()); - if (null != wirePipe) { - wirePipe.processIncomingMessage(message, header, srcAddr, dstAddr); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Ignoring message " + message + " for id " + header.getPipeID()); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/package.html deleted file mode 100644 index b4d52dd8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/pipe/package.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - -A JXTA {@link net.jxta.pipe.PipeService} implementation which implements the -standard JXTA Pipe Resolver Protocol (PRP). - -@see net.jxta.pipe.PipeService -@see net.jxta.pipe.InputPipe -@see net.jxta.pipe.OutputPipe -@see net.jxta.protocol.PipeAdvertisement -@see net.jxta.endpoint.Message -@see JXTA Protocols - Specification : Pipe Binding Protocol - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/AccessPointAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/AccessPointAdv.java deleted file mode 100644 index d6d6946e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/AccessPointAdv.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.protocol.AccessPointAdvertisement; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Associates a set of EndpointAddresses with a PeerID. - *

            - *

            - *    <xs:complexType name ="jxta:APA">
            - *      <xs:sequence>
            - *        <xs:element name="PID" type="jxta:JXTAID" minOccurs="0" maxOccurs="1"/>
            - *        <xs:sequence>
            - *          <xs:element name="EA" type="jxta:JXTAID" minOccurs="0" maxOccurs="unbounded"/>
            - *        </xs:sequence>
            - *      </xs:sequence>
            - *    </xs:complexType>
            - *  
            - * - * @see net.jxta.protocol.AccessPointAdvertisement - */ -public class AccessPointAdv extends AccessPointAdvertisement implements Cloneable { - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(AccessPointAdv.class.getName()); - - private static final String PID_TAG = "PID"; - private static final String EA_TAG = "EA"; - - private static final String[] INDEXFIELDS = { PID_TAG}; - - /** - * Instantiator for AdvertisementFactory - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return AccessPointAdv.getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new AccessPointAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - return new AccessPointAdv(root); - } - } - - /** - * Returns the identifying type of this Advertisement. - *

            - * Note: This is a static method. It cannot be used to determine - * the runtime type of an advertisment. ie. - *

            -     *      Advertisement adv = module.getSomeAdv();
            -     *      String advType = adv.getAdvertisementType();
            -     *  
            - *

            - * This is wrong and does not work the way you might expect. - * This call is not polymorphic and calls - * Advertiement.getAdvertisementType() no matter what the real type of the - * advertisment. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:APA"; - } - - /** - * Private constructor. Use the Advertisement factory and accessors. - */ - private AccessPointAdv() {} - - /** - * Private constructor. Use the Advertisement factory and accessors. - * - * @param root the element - */ - private AccessPointAdv(Element root) { - if (!(root instanceof XMLElement)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public AccessPointAdv clone() { - return (AccessPointAdv) super.clone(); - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return INDEXFIELDS; - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public ID getID() { - ID pid = getPeerID(); - - if (null == pid) { - throw new IllegalStateException("cannot build ID: no peer id"); - } - - try { - // We have not yet built it. Do it now - String seed = getAdvType() + getPeerID().toString(); - - InputStream in = new ByteArrayInputStream(seed.getBytes()); - - return IDFactory.newCodatID(PeerGroupID.worldPeerGroupID, seed.getBytes(), in); - } catch (Exception ez) { - IllegalStateException failed = new IllegalStateException("cannot build ID"); - - failed.initCause(ez); - - throw failed; - } - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (PID_TAG.equals(elem.getName())) { - String uri = elem.getTextValue(); - - if (null != uri) { - try { - URI pID = new URI(uri.trim()); - - setPeerID((PeerID) IDFactory.fromURI(pID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerID ID in advertisement"); - } catch (ClassCastException notPID) { - throw new IllegalArgumentException("Not a Peer ID"); - } - - return true; - } - } - - if (EA_TAG.equals(elem.getName())) { - String epa = elem.getTextValue(); - - if (null != epa) { - addEndpointAddress(epa.trim()); - return true; - } - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - if (getPeerID() != null) { - Element e = adv.createElement(PID_TAG, getPeerID().toString()); - - adv.appendChild(e); - } - - Enumeration each = getEndpointAddresses(); - - while (each.hasMoreElements()) { - Element e2 = adv.createElement(EA_TAG, each.nextElement().toString()); - - adv.appendChild(e2); - } - return adv; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/Certificate.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/Certificate.java deleted file mode 100644 index adb8fb92..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/Certificate.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.impl.membership.pse.PSEUtils; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.StringReader; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.*; - - -/** - * A lightweight container for X.509 Certificates. - * * - *

            
            - *   <xs:element name="jxta:cert" type="Certificate"/>
            - * 

            - * <xs:complexType name="Certificate" type="xs:string"> - * <xs:element name="Issuer" type="jxta:cert" minOccurs="0" /> - * </xs:complexType> - *

            - */ -public class Certificate { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(Certificate.class.getName()); - - /** - * - **/ - private List certs = null; - - /** - **/ - public Certificate() { - super(); - } - - public Certificate(Element root) { - this(); - certs = new ArrayList(); - initialize(root); - } - - /** - * returns the Message type. This will match the XML doctype declaration. - * - * @return a string - */ - public static String getMessageType() { - return "jxta:cert"; - } - - public X509Certificate[] getCertificates() { - return certs.toArray(new X509Certificate[certs.size()]); - } - - public void setCertificates(X509Certificate[] certs) { - this.certs = new ArrayList(Arrays.asList(certs)); - } - - public void setCertificates(List certs) { - this.certs = new ArrayList(certs); - } - - /** - * Initializes the message from a document. - * - * @param root the element - */ - private void initialize(Element root) { - - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XMLElement"); - } - - XMLElement doc = (XMLElement) root; - - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getMessageType()) && !getMessageType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - String value = doc.getTextValue(); - - value = value.trim(); - - try { - byte[] cert_der = PSEUtils.base64Decode(new StringReader(value)); - - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - certs.add((X509Certificate) cf.generateCertificate(new ByteArrayInputStream(cert_der))); - } catch (IOException error) { - throw new IllegalArgumentException("bad certificate."); - } catch (CertificateException error) { - throw new IllegalArgumentException("bad certificate."); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - Element elem = (Element) elements.nextElement(); - - if (!elem.getKey().equals("Issuer")) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - continue; - } - - Certificate issuer = new Certificate(elem); - - certs.addAll(Arrays.asList(issuer.getCertificates())); - } - - // Begin checking sanity! - if (certs.isEmpty()) { - throw new IllegalArgumentException("certificate not initialized."); - } - } - - /** - * Creates a document out of the message. - * - * @param encodeAs The document representation format requested. - * @return the message as a document. - */ - public Document getDocument(MimeMediaType encodeAs) { - String encodedCert; - - try { - encodedCert = PSEUtils.base64Encode((certs.get(0)).getEncoded()); - } catch (CertificateEncodingException failed) { - IllegalStateException failure = new IllegalStateException("bad certificate."); - - failure.initCause(failed); - - throw failure; - } catch (IOException failed) { - IllegalStateException failure = new IllegalStateException("Could not encode certificate."); - - failure.initCause(failed); - - throw failure; - } - - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(encodeAs, getMessageType(), encodedCert); - - if (doc instanceof XMLDocument) { - ((XMLDocument) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - ((XMLDocument) doc).addAttribute("xml:space", "preserve"); - } - - Iterator eachCert = certs.iterator(); - - eachCert.next(); // skip me. - - Element addTo = doc; - - while (eachCert.hasNext()) { - X509Certificate anIssuer = eachCert.next(); - - try { - encodedCert = PSEUtils.base64Encode(anIssuer.getEncoded()); - } catch (CertificateEncodingException failed) { - IllegalStateException failure = new IllegalStateException("bad certificate."); - - failure.initCause(failed); - - throw failure; - } catch (IOException failed) { - IllegalStateException failure = new IllegalStateException("Could not encode certificate."); - - failure.initCause(failed); - - throw failure; - } - - Element issuerElement = doc.createElement("Issuer", encodedCert); - - addTo.appendChild(issuerElement); - - if (doc instanceof Attributable) { - ((Attributable) issuerElement).addAttribute("type", getMessageType()); - } - - addTo = issuerElement; - } - - return doc; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/CertificateSigningRequest.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/CertificateSigningRequest.java deleted file mode 100644 index d10a85e1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/CertificateSigningRequest.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.io.StringReader; - -import java.io.IOException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import org.bouncycastle.jce.PKCS10CertificationRequest; - -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; - -import net.jxta.impl.membership.pse.PSEUtils; - - -/** - * A lightweight container for a PKCS#10/RFC2986 Certificate Signing Request. - * - * @deprecated The types exported from this implementation are subject to - * change. - * - *
            
            - *   <xs:element name="jxta:csr" type="CertificateSigningRequest"/>
            - *
            - *   <xs:complexType name="csr">
            - *     <xs:all>
            - *     </xs:all>
            - *   </xs:complexType>
            - * 
            - * - * @see PKCS #10 - * @see IETF RFC 2986 - **/ -@Deprecated -public class CertificateSigningRequest { - - /** - * Logger - **/ - private final static transient Logger LOG = Logger.getLogger(CertificateSigningRequest.class.getName()); - - private PKCS10CertificationRequest csr = null; - - public CertificateSigningRequest() { - super(); - } - - public CertificateSigningRequest(Element root) { - this(); - initialize(root); - } - - /** - * returns the Message type. This will match the XML doctype declaration. - * - * @return a string - **/ - public static String getMessageType() { - return "jxta:CertificateSigningRequest"; - } - - public PKCS10CertificationRequest getCSR() { - return csr; - } - - public void setCSR(PKCS10CertificationRequest csr) { - this.csr = csr; - } - - /** - * Initializes the message from a document. - **/ - protected void initialize(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XMLElement"); - } - - XMLElement doc = (XMLElement) root; - - String docName = doc.getName(); - - if (!docName.equals(getMessageType())) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + docName); - } - - String value = doc.getTextValue(); - - value = value.trim(); - - try { - byte[] csr_der = PSEUtils.base64Decode(new StringReader(value)); - - csr = new PKCS10CertificationRequest(csr_der); - } catch (IOException error) { - throw new IllegalArgumentException("bad certificate signing request."); - } - - // Begin checking sanity! - if (null == csr) { - throw new IllegalArgumentException("certificate signing request not initialized."); - } - } - - /** - * Creates a document out of the message. - * - * @param encodeAs The document representation format requested. - * @return the message as a document. - **/ - public Document getDocument(MimeMediaType encodeAs) { - - String encodedCSR; - - try { - encodedCSR = PSEUtils.base64Encode(csr.getEncoded()); - } catch (IOException failed) { - IllegalStateException failure = new IllegalStateException("Could not encode certificate signing request."); - - failure.initCause(failed); - - throw failure; - } - - StructuredTextDocument doc = (StructuredTextDocument) StructuredDocumentFactory.newStructuredDocument(encodeAs - , - getMessageType(), encodedCSR); - - if (doc instanceof XMLDocument) { - ((XMLDocument) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - ((XMLDocument) doc).addAttribute("xml:space", "preserve"); - } - - return doc; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/DiscoveryConfigAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/DiscoveryConfigAdv.java deleted file mode 100644 index 6e5a9d5a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/DiscoveryConfigAdv.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.util.Enumeration; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * Contains parameters for configuration of the Reference Implemenation - * Rendezvous Service. - * - *

            
            - *
            - * 
            - * - */ -public final class DiscoveryConfigAdv extends ExtendableAdvertisement { - - /** - * Instantiator for DiscoveryConfigAdv - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return advType; - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new DiscoveryConfigAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - return new DiscoveryConfigAdv(root); - } - } - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(DiscoveryConfigAdv.class.getName()); - - /** - * Our DOCTYPE - */ - private static final String advType = "jxta:DiscoConfigAdv"; - - private static final String FORWARD_ALWAYS_REPLICA = "forwardAlwaysReplica"; - private static final String FORWARD_BELOW_TRESHOLD = "forwardBelowThreshold"; - private static final String LOCAL_ONLY = "localOnly"; - - private static final String[] fields = {}; - - /** - * If true, the discovery service will always forward queries to the replica peer - * even if there are local responses, unless the replica peer is the local peer. - */ - private boolean forwardAlwaysReplica = false; - - /** - * If true, the discovery service will always forward queries if the number of local - * responses is below the specified threshold. The threshold may be reduced by the number - * of local responses before forwarding. NOTE: not yet implemented. - */ - private boolean forwardBelowTreshold = false; - - /** - * localOnly discovery. - */ - private boolean localOnly = false; - - /** - * Returns the identifying type of this Advertisement. - * - *

            Note: This is a static method. It cannot be used to determine - * the runtime type of an advertisment. ie. - *

            -     *      Advertisement adv = module.getSomeAdv();
            -     *      String advType = adv.getAdvertisementType();
            -     *  
            - * - *

            This is wrong and does not work the way you might expect. - * This call is not polymorphic and calls - * Advertiement.getAdvertisementType() no matter what the real type of the - * advertisment. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return advType; - } - - /** - * Use the Instantiator through the factory - */ - DiscoveryConfigAdv() {} - - /** - * Use the Instantiator through the factory - * @param root the element - */ - DiscoveryConfigAdv(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration eachAttr = doc.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute aDiscoAttr = (Attribute) eachAttr.nextElement(); - String name = aDiscoAttr.getName(); - boolean flag = Boolean.valueOf(aDiscoAttr.getValue().trim()); - - if (FORWARD_ALWAYS_REPLICA.equals(name)) { - forwardAlwaysReplica = flag; - } else if (FORWARD_BELOW_TRESHOLD.equals(name)) { - forwardBelowTreshold = flag; - } else if (LOCAL_ONLY.equals(name)) { - localOnly = flag; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + name); - } - } - } - } - - /** - * Make a safe clone of this DiscoveryConfigAdv. - * - * @return Object A copy of this DiscoveryConfigAdv - */ - @Override - public DiscoveryConfigAdv clone() throws CloneNotSupportedException { - - throw new CloneNotSupportedException("Not implemented"); - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public ID getID() { - return ID.nullID; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - if (adv instanceof Attributable) { - Attributable attrDoc = (Attributable) adv; - - // Do not output if false. It is the default value. - if (forwardAlwaysReplica) { - attrDoc.addAttribute(FORWARD_ALWAYS_REPLICA, Boolean.toString(forwardAlwaysReplica)); - } - if (forwardBelowTreshold) { - attrDoc.addAttribute(FORWARD_BELOW_TRESHOLD, Boolean.toString(forwardBelowTreshold)); - } - if (localOnly) { - attrDoc.addAttribute(FORWARD_BELOW_TRESHOLD, Boolean.toString(localOnly)); - } - } - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return fields; - } - - /** - * True if this discovery service will forward queries to the replica peer in all cases, rather - * than only in the absence of local responses. - * - * @return The current setting. - */ - public boolean getForwardAlwaysReplica() { - return forwardAlwaysReplica; - } - - /** - * Specifies if this discovery service will forward queries to the replica peer in all cases, rather than only in the absence - * of local responses. - * - * @param newvalue The new setting. - */ - public void setForwardAlwaysReplica(boolean newvalue) { - forwardAlwaysReplica = newvalue; - } - - /** - * True if this discovery service will forward queries when the number of local responses - * is below the specified treshold, rather than only in the absence of local responses. - * - * @return The current setting. - */ - public boolean getForwardBelowTreshold() { - return forwardBelowTreshold; - } - - /** - * Specifies if this discovery service will forward queries when the number of local responses is below the specified - * treshold, rather than only in the absence of local responses. - * - * @param newvalue The new setting. - */ - public void setForwardBelowTreshold(boolean newvalue) { - forwardBelowTreshold = newvalue; - } - - /** - * True if this discovery service performs only local discovery. - * - * @return The current setting. - */ - public boolean getLocalOnly() { - return localOnly; - } - - /** - * Specifies if this discovery service will perform local only discovery. - * - * @param newvalue The new setting. - */ - public void setLocalOnly(boolean newvalue) { - localOnly = newvalue; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/DiscoveryQuery.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/DiscoveryQuery.java deleted file mode 100644 index 3c3dbee5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/DiscoveryQuery.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.io.IOException; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.*; -import net.jxta.protocol.DiscoveryQueryMsg; -import net.jxta.protocol.PeerAdvertisement; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.StringReader; -import java.lang.reflect.UndeclaredThrowableException; -import java.util.Enumeration; - - -/** - * Implements the Discovery Query Message according to the schema defined by the - * standard JXTA Peer Discovery Protocol (PDP). - *

            - *

            - * <xs:element name="DiscoveryQuery" type="jxta:DiscoveryQuery"/>
            - * 

            - * <xsd:simpleType name="DiscoveryQueryType"> - * <xsd:restriction base="xsd:string"> - * <!-- peer --> - * <xsd:enumeration value="0"/> - * <!-- group --> - * <xsd:enumeration value="1"/> - * <!-- adv --> - * <xsd:enumeration value="2"/> - * </xsd:restriction> - * </xsd:simpleType> - *

            - * <xs:complexType name="DiscoveryQuery"> - * <xs:sequence> - * <xs:element name="Type" type="jxta:DiscoveryQueryType"/> - * <xs:element name="Threshold" type="xs:unsignedInt" minOccurs="0"/> - * <xs:element name="Attr" type="xs:string" minOccurs="0"/> - * <xs:element name="Value" type="xs:string" minOccurs="0"/> - * <!-- The following should refer to a peer adv, but is instead a whole doc for historical reasons --> - * <xs:element name="PeerAdv" type="xs:string" minOccurs="0"/> - * </xs:sequence> - * </xs:complexType> - *

            - * - * @see net.jxta.discovery.DiscoveryService - * @see net.jxta.impl.discovery.DiscoveryServiceImpl - * @see JXTA Protocols Specification : Peer Discovery Protocol - */ -public class DiscoveryQuery extends DiscoveryQueryMsg { - - private static final Logger LOG = Logger.getLogger(DiscoveryQuery.class.getName()); - - private static final String typeTag = "Type"; - private static final String peerAdvTag = "PeerAdv"; - private static final String thresholdTag = "Threshold"; - private static final String queryAttrTag = "Attr"; - private static final String queryValueTag = "Value"; - - /** - * Default constructor - */ - public DiscoveryQuery() {} - - /** - * Construct from a StructuredDocument - * - * @param doc the element - */ - public DiscoveryQuery(Element doc) { - initialize(doc); - } - - /** - * Process an individual element from the document during parse. Normally, - * implementations will allow the base advertisments a chance to handle the - * element before attempting ot handle the element themselves. ie. - *

            - *

            
            -     *  protected boolean handleElement(Element elem) {
            -     * 

            - * if (super.handleElement()) { - * // it's been handled. - * return true; - * } - *

            - * ... handle elements here ... - *

            - * // we don't know how to handle the element - * return false; - * } - *

            - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - */ - protected boolean handleElement(XMLElement elem) { - - String value = elem.getTextValue(); - - if(null == value) { - return false; - } - - value = value.trim(); - - if(0 == value.length()) { - return false; - } - - if (elem.getName().equals(typeTag)) { - setDiscoveryType(Integer.parseInt(value)); - return true; - } - if (elem.getName().equals(thresholdTag)) { - setThreshold(Integer.parseInt(value)); - return true; - } - if (elem.getName().equals(peerAdvTag)) { - try { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, new StringReader(value)); - PeerAdvertisement adv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(asDoc); - setPeerAdvertisement(adv); - return true; - } catch(IOException failed) { - IllegalArgumentException failure = new IllegalArgumentException("Bad Peer Advertisement"); - failure.initCause(failed); - - throw failure; - } - } - if (elem.getName().equals(queryAttrTag)) { - setAttr(value); - return true; - } - if (elem.getName().equals(queryValueTag)) { - setValue(value); - return true; - } - - // element was not handled - return false; - } - - /** - * Intialize a Discovery Query from a portion of a structured document. - * - * @param root document to intialize from - */ - protected void initialize(Element root) { - - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XMLElement"); - } - - XMLElement doc = (XMLElement) root; - - if (!doc.getName().equals(getAdvertisementType())) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - setDiscoveryType(-1); // force illegal value; - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element : " + elem.toString()); - } - } - } - - // sanity check time! - - if ((DiscoveryService.PEER != getDiscoveryType()) && (DiscoveryService.GROUP != getDiscoveryType()) - && (DiscoveryService.ADV != getDiscoveryType())) { - throw new IllegalArgumentException("Type is not one of the required values."); - } - if (getThreshold() < 0) { - throw new IllegalArgumentException("Threshold must not be less than zero."); - } - if ((getDiscoveryType() != DiscoveryService.PEER) && (getThreshold() == 0)) { - throw new IllegalArgumentException("Threshold may not be zero."); - } - if ((null == getAttr()) && (null != getValue())) { - throw new IllegalArgumentException("Value specified without attribute."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType asMimeType) { - StructuredDocument adv = StructuredDocumentFactory.newStructuredDocument(asMimeType, getAdvertisementType()); - - if (adv instanceof XMLDocument) { - XMLDocument xmlDoc = (XMLDocument) adv; - - xmlDoc.addAttribute("xmlns:jxta", "http://jxta.org"); - xmlDoc.addAttribute("xml:space", "preserve"); - } - - Element e; - - e = adv.createElement(typeTag, Integer.toString(getDiscoveryType())); - adv.appendChild(e); - - int threshold = getThreshold(); - - if (threshold < 0) { - throw new IllegalStateException("threshold must be >= 0"); - } - e = adv.createElement(thresholdTag, Integer.toString(threshold)); - adv.appendChild(e); - - PeerAdvertisement peerAdv = getPeerAdvertisement(); - - if ((peerAdv != null)) { - e = adv.createElement(peerAdvTag, peerAdv.toString()); - adv.appendChild(e); - } - - String attr = getAttr(); - - if ((attr != null) && (attr.length() > 0)) { - e = adv.createElement(queryAttrTag, attr.trim()); - adv.appendChild(e); - - String value = getValue(); - - if ((value != null) && (value.length() > 0)) { - e = adv.createElement(queryValueTag, value.trim()); - adv.appendChild(e); - } else { - if (threshold < 0) { - throw new IllegalStateException("Attribute specified, but no value was specified."); - } - } - } - return adv; - } - - /** - * return the string representaion of this doc - * - * @deprecated should not be used. use getDocument().toString() instead. - */ - @Override - @Deprecated - public String toString() { - - try { - StructuredTextDocument doc = (StructuredTextDocument) getDocument(MimeMediaType.XMLUTF8); - - return doc.toString(); - } catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new UndeclaredThrowableException(e); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/DiscoveryResponse.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/DiscoveryResponse.java deleted file mode 100644 index bfeba1ba..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/DiscoveryResponse.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.UndeclaredThrowableException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.Vector; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.TextElement; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.protocol.DiscoveryResponseMsg; -import net.jxta.protocol.PeerAdvertisement; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * DiscoveryResponse. - * - *

            This message is part of the standard JXTA Peer Discovery Protocol (PDP). - * - *

            - * <xs:element name="DiscoveryResponse" type="jxta:DiscoveryResponse"/>
            - *
            - * <xs:complexType name="DiscoveryResponse">
            - *   <xs:sequence>
            - *     <xs:element name="Type" type="jxta:DiscoveryQueryType"/>
            - *     <xs:element name="Count" type="xs:unsignedInt" minOccurs="0"/>
            - *     <xs:element name="Attr" type="xs:string" minOccurs="0"/>
            - *     <xs:element name="Value" type="xs:string" minOccurs="0"/>
            - *     <!-- The following should refer to a peer adv, but is instead a whole doc for historical reasons -->
            - *     <xs:element name="PeerAdv" minOccurs="0">
            - *     <xs:complexType>
            - *       <xs:simpleContent>
            - *         <xs:extension base="xs:string">
            - *           <xs:attribute name="Expiration" type="xs:unsignedLong"/>
            - *         </xs:extension>
            - *       </xs:simpleContent>
            - *     </xs:complexType>
            - *     </xs:element>
            - *     <xs:element name="Response" maxOccurs="unbounded">
            - *     <xs:complexType>
            - *       <xs:simpleContent>
            - *         <xs:extension base="xs:string">
            - *           <xs:attribute name="Expiration" type="xs:unsignedLong"/>
            - *         </xs:extension>
            - *       </xs:simpleContent>
            - *     </xs:complexType>
            - *     </xs:element>
            - *   </xs:sequence>
            - * </xs:complexType>
            - * 
            - * - *@see net.jxta.discovery.DiscoveryService - *@see net.jxta.impl.discovery.DiscoveryServiceImpl - *@see JXTA Protocols Specification : Peer Discovery Protocol - */ -public class DiscoveryResponse extends DiscoveryResponseMsg { - - private final static transient Logger LOG = Logger.getLogger(DiscoveryResponse.class.getName()); - - private final static String countTag = "Count"; - private final static String expirationTag = "Expiration"; - private final static String peerAdvTag = "PeerAdv"; - private final static String queryAttrTag = "Attr"; - private final static String queryValueTag = "Value"; - private final static String responsesTag = "Response"; - private final static String typeTag = "Type"; - - /** - * Constructor for new instances. - */ - public DiscoveryResponse() {} - - /** - * Construct from a StructuredDocument - * - *@param root Description of the Parameter - */ - public DiscoveryResponse(Element root) { - - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XMLElement"); - } - XMLElement doc = (XMLElement) root; - String docName = doc.getName(); - - if (!getAdvertisementType().equals(docName)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + " from doc containing a " + docName); - } - readIt(doc); - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType asMimeType) { - - StructuredTextDocument adv = (StructuredTextDocument) - StructuredDocumentFactory.newStructuredDocument(asMimeType, getAdvertisementType()); - - if (adv instanceof XMLDocument) { - ((XMLDocument) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - Element e; - - e = adv.createElement(countTag, Integer.toString(responses.size())); - adv.appendChild(e); - e = adv.createElement(typeTag, Integer.toString(type)); - adv.appendChild(e); - - PeerAdvertisement myPeerAdv = getPeerAdvertisement(); - - if (null != myPeerAdv) { - e = adv.createElement(peerAdvTag, myPeerAdv.toString()); - adv.appendChild(e); - } - - if ((attr != null) && (attr.length() > 0)) { - e = adv.createElement(queryAttrTag, getQueryAttr()); - adv.appendChild(e); - if ((value != null) && (value.length() > 0)) { - e = adv.createElement(queryValueTag, value); - adv.appendChild(e); - } - } - - Enumeration advs = getResponses(); - Enumeration exps = getExpirations(); - - try { - while (advs.hasMoreElements()) { - Long l = (Long) exps.nextElement(); - String response = advs.nextElement(); - - e = adv.createElement(responsesTag, response); - - adv.appendChild(e); - if (adv instanceof Attributable) { - ((Attributable) e).addAttribute(expirationTag, l.toString()); - } - } - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Got an Exception during doc creation", failed); - } - IllegalStateException failure = new IllegalStateException("Got an Exception during doc creation"); - - failure.initCause(failed); - throw failure; - } - return adv; - } - - /** - * Parses a document into this object - * - *@param doc Document - */ - private void readIt(XMLElement doc) { - Vector res = new Vector(); - Vector exps = new Vector(); - - try { - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (elem.getName().equals(typeTag)) { - type = Integer.parseInt(elem.getTextValue()); - continue; - } - - if (elem.getName().equals(peerAdvTag)) { - String peerString = elem.getTextValue(); - - if (null == peerString) { - continue; - } - - peerString = peerString.trim(); - if (peerString.length() > 0) { - XMLDocument xmlPeerAdv = (XMLDocument) StructuredDocumentFactory.newStructuredDocument( - MimeMediaType.XMLUTF8, new StringReader(peerString)); - - setPeerAdvertisement((PeerAdvertisement) AdvertisementFactory.newAdvertisement(xmlPeerAdv)); - } - continue; - } - - if (elem.getName().equals(queryAttrTag)) { - setQueryAttr(elem.getTextValue()); - continue; - } - - if (elem.getName().equals(queryValueTag)) { - setQueryValue(elem.getTextValue()); - continue; - } - - if (elem.getName().equals(responsesTag)) { - // get the response - String aResponse = elem.getTextValue(); - - if (null == aResponse) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Discarding an empty response tag"); - } - continue; - } - res.add(aResponse); - - long exp; - // get expiration associated with this response - Attribute attr = (elem).getAttribute(expirationTag); - - if (null != attr) { - exp = Long.parseLong(attr.getValue()); - } else { - // if there are no attribute use DEFAULT_EXPIRATION - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Received an old-style DiscoveryResponse.\n You received a response from a peer that does \nnot support advertisement aging. \nSetting expiration to DiscoveryService.DEFAULT_EXPIRATION "); - } - exp = DiscoveryService.DEFAULT_EXPIRATION; - } - - exps.add(exp); - } - } - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Got an Exception during Parse ", failed); - } - IllegalArgumentException failure = new IllegalArgumentException("Got an Exception during parse"); - - failure.initCause(failed); - throw failure; - } - - setResponses(res); - setExpirations(exps); - } - - /** - * Return a string representation of this message. The string will - * contain the message formated as a UTF-8 encoded XML Document. - * - * @return String a String containing the message. - */ - @Override - public String toString() { - - try { - XMLDocument doc = (XMLDocument) getDocument(MimeMediaType.XMLUTF8); - - return doc.toString(); - } catch (Throwable e) { - if (e instanceof Error) { - throw (Error) e; - } else if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new UndeclaredThrowableException(e); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/GroupConfig.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/GroupConfig.java deleted file mode 100644 index 6eef38cc..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/GroupConfig.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.XMLElement; -import net.jxta.logging.Logging; -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.jxta.id.ID; -import net.jxta.protocol.ConfigParams; - - -/** - * Configuration container for any Peer Group. - */ -public class GroupConfig extends ConfigParams implements Cloneable { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(GroupConfig.class.getName()); - - private static final String advType = "jxta:GroupConfig"; - - /** - * Instantiator for GroupConfig - */ - public final static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return advType; - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new GroupConfig(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - return new GroupConfig((XMLElement) root); - } - } - - /** - * Use the Instantiator through the factory - */ - GroupConfig() {} - - /** - * Use the Instantiator through the factory - * - * @param root the element - */ - GroupConfig(XMLElement doc) { - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - Element elem = (Element) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - } - - /** - * Make a safe clone of this GroupConfig. - * - * @return Object an object of class GroupConfig that is a deep-enough - * copy of this one. - */ - @Override - public GroupConfig clone() { - GroupConfig result = (GroupConfig) super.clone(); - - return result; - } - - /** - * returns the advertisement type - * - * @return string type - */ - public static String getAdvertisementType() { - return advType; - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public StructuredDocument getDocument(MimeMediaType encodeAs) { - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - addDocumentElements(adv); - - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return new String[0]; - } - - /** - * {@inheritDoc} - */ - @Override - public ID getID() { - return null; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/HTTPAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/HTTPAdv.java deleted file mode 100644 index e253c968..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/HTTPAdv.java +++ /dev/null @@ -1,561 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.protocol.TransportAdvertisement; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.util.Arrays; -import java.util.Enumeration; - - -/** - * Configuration parameters for HttpServelet Message Transport. - */ -public class HTTPAdv extends TransportAdvertisement { - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(HTTPAdv.class.getName()); - - private static final String CONFIGMODES[] = { "auto", "manual"}; - private static final String INDEXFIELDS[] = {/* none */}; - - private static final String ProtocolTag = "Protocol"; - private static final String ProxyTag = "Proxy"; - private static final String ServerTag = "Server"; - private static final String PortTag = "Port"; - private static final String IntfAddrTag = "InterfaceAddress"; - private static final String ConfModeTag = "ConfigMode"; - private static final String FlagsTag = "Flags"; - private static final String PublicAddressOnlyAttr = "PublicAddressOnly"; - private static final String ProxyOffTag = "ProxyOff"; - private static final String ServerOffTag = "ServerOff"; - private static final String ClientOffTag = "ClientOff"; - - private String proxy = null; - private String server = null; - private int listenPort = -1; // The real port a server listens to - - private String interfaceAddress = null; // What IP to bind to locally - - private String configMode = CONFIGMODES[0]; - private boolean publicAddressOnly = false; - - // These are for configuration; They get saved in the document only if they are - // off and the correspondig item has a non-null value. So that the value is not lost. - // When HttpTransport is done initializing, the unused values are set to null, and thus - // pruned from the published adv. - - private boolean proxyEnabled = true; - private boolean serverEnabled = true; - private boolean clientEnabled = true; - - /** - * Our instantiator. - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return HTTPAdv.getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new HTTPAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - return new HTTPAdv((XMLElement) root); - } - } - - /** - * Returns the identifying type of this Advertisement. - *

            - *

            Note: This is a static method. It cannot be used to determine - * the runtime type of an advertisement. ie. - *

            -     *      Advertisement adv = module.getSomeAdv();
            -     *      String advType = adv.getAdvertisementType();
            -     *  
            - *

            - *

            This is wrong and does not work the way you might expect. - * This call is not polymorphic and calls - * Advertisement.getAdvertisementType() no matter what the real type of the - * advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:HTTPTransportAdvertisement"; - } - - /** - * Private constructor for new instances. Use the instantiator. - */ - private HTTPAdv() { - } - - /** - * Private constructor for xml serialized instances. Use the instantiator. - * - * @param doc The XML serialization of the advertisement. - */ - private HTTPAdv(XMLElement doc) { - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Attribute attr = doc.getAttribute(FlagsTag); - - if (attr != null) { - String options = attr.getValue(); - - publicAddressOnly = (options.indexOf(PublicAddressOnlyAttr) != -1); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - - // For consistency we force the flags to "disabled" for items we do not - // have data for. However, the flags truely matter only when there is - // data. - if (proxy == null) { - proxyEnabled = false; - } - - if (serverEnabled && (0 == listenPort)) { - throw new IllegalArgumentException("Dynmaic port selection not supported with incoming connections."); - } - - if ((listenPort < -1) || (listenPort > 65535)) { - throw new IllegalArgumentException("Illegal Listen Port Value"); - } - - if (!Arrays.asList(CONFIGMODES).contains(configMode)) { - throw new IllegalArgumentException("Unsupported configuration mode."); - } - - // XXX 20050118 bondolo Some versions apparently don't initialize this field. Eventually make it required. - if (null == getProtocol()) { - setProtocol("http"); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - String tag = elem.getName(); - - if (tag.equals(ProxyOffTag)) { - proxyEnabled = false; - return true; - } - - if (tag.equals(ServerOffTag)) { - serverEnabled = false; - return true; - } - - if (tag.equals(ClientOffTag)) { - clientEnabled = false; - return true; - } - - String value = elem.getTextValue(); - - if (null == value) { - return false; - } - - value = value.trim(); - - if (0 == value.length()) { - return false; - } - - if (tag.equals(ProtocolTag)) { - setProtocol(value); - return true; - } - - if (tag.equals(IntfAddrTag)) { - setInterfaceAddress(value); - return true; - } - - if (tag.equals(ConfModeTag)) { - setConfigMode(value); - return true; - } - - if (tag.equals(PortTag)) { - setPort(Integer.parseInt(value.trim())); - return true; - } - - if (tag.equals(ProxyTag)) { - proxy = value; - return true; - } - - if (tag.equals(ServerTag)) { - server = value; - return true; - } - - return false; - } - - /** - * {@inheritDoc} - *

            - *

            NB: we do not try to enforce dependency rules - * such as Proxy only when router, because we want to convey the complete - * configuration, even items corresponding to not currently enabled - * features. HttpTransport will gracefully disregard items that have - * no use in the current context. - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - if (serverEnabled && (0 == listenPort)) { - throw new IllegalStateException("Dynmaic port selection not supported with incoming connections."); - } - - if ((listenPort < -1) || (listenPort > 65535)) { - throw new IllegalStateException("Illegal Listen Port Value"); - } - - if (!Arrays.asList(CONFIGMODES).contains(configMode)) { - throw new IllegalStateException("Unsupported configuration mode."); - } - - // XXX 20050118 bondolo Some versions apparently don't initialize this field. Eventually make it required. - if (null == getProtocol()) { - setProtocol("http"); - } - - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - if (adv instanceof Attributable) { - // Only one flag for now. Easy. - if (publicAddressOnly) { - ((Attributable) adv).addAttribute(FlagsTag, PublicAddressOnlyAttr); - } - } - - Element e1 = adv.createElement(ProtocolTag, getProtocol()); - - adv.appendChild(e1); - - if (null != getInterfaceAddress()) { - Element e2 = adv.createElement(IntfAddrTag, getInterfaceAddress()); - - adv.appendChild(e2); - } - - Element e3 = adv.createElement(ConfModeTag, getConfigMode()); - - adv.appendChild(e3); - - Element e4 = adv.createElement(PortTag, Integer.toString(getPort())); - - adv.appendChild(e4); - - Element ext; - - if (proxy != null) { - ext = adv.createElement(ProxyTag, proxy); - adv.appendChild(ext); - } - - // If disabled, say it; otherwise it is assumed on. In published - // advs, we only keep data for items that are ON, so we do not - // have to clutter them with the flag. - if (!proxyEnabled) { - ext = adv.createElement(ProxyOffTag); - adv.appendChild(ext); - } - - if (server != null) { - ext = adv.createElement(ServerTag, server); - adv.appendChild(ext); - } - - // If disabled, say it; otherwise it is assumed on. In published - // advs, we only keep data for items that are ON, so we do not - // have to clutter them with the flag. - if (!serverEnabled) { - ext = adv.createElement(ServerOffTag); - adv.appendChild(ext); - } - - // If disabled, say it; otherwise it is assumed on. In published - // advs, we only keep data for items that are ON, so we do not - // have to clutter them with the flag. - if (!clientEnabled) { - ext = adv.createElement(ClientOffTag); - adv.appendChild(ext); - } - - return adv; - } - - /** - * Returns the interfaceAddr. That is, the ip of the IF to which to bind - * locally created sockets. - * - * @return string The address. - */ - public String getInterfaceAddress() { - return interfaceAddress; - } - - /** - * Sets the interfaceAddr. That is, the ip of the IF to which to bind - * locally created sockets. - * - * @param address The address - */ - public void setInterfaceAddress(String address) { - this.interfaceAddress = address; - } - - public boolean getPublicAddressOnly() { - return publicAddressOnly; - } - - public void setPublicAddressOnly(boolean only) { - publicAddressOnly = only; - } - - /** - * returns the config mode. That is, how the user prefers to configure - * the interface address: "auto", "manual" - * - * @return string config mode - */ - public String getConfigMode() { - return configMode; - } - - /** - * set the config mode. That is, how the user prefers to configure - * the interface address: "auto", "manual" - *

            - * This is just a pure config item. It is never in published advs. The TCP - * transport strips it when it initializes. - * - * @param mode Can be "auto", "manual" other settings will act as the default - * which is "auto". - */ - public void setConfigMode(String mode) { - if (!Arrays.asList(CONFIGMODES).contains(mode)) { - throw new IllegalArgumentException("Unsupported configuration mode."); - } - - configMode = mode; - } - - /** - * Returns the port number to which server sockets are locally bound. - * - * @return String the port - */ - public int getPort() { - return listenPort; - } - - /** - * Sets the port number to which server sockets are locally bound. - * - * @param newPort the port - */ - public void setPort(int newPort) { - listenPort = newPort; - } - - /** - * @return the proxy string - * @deprecated This has been deprecated. Set your proxy directly with the JVM - */ - @Deprecated - public String getProxy() { - return proxy; - } - - public String getServer() { - return server; - } - - /** - * @return true if proxy enabled - * @deprecated This has been deprecated. Set your proxy directly with the JVM - */ - @Deprecated - public boolean isProxyEnabled() { - return proxyEnabled; - } - - public boolean isServerEnabled() { - return serverEnabled; - } - - public boolean isClientEnabled() { - return clientEnabled; - } - - // If one of proxy, server, or router is cleared, the corresponding - // enabled flag should be false (the opposite is not true). - - /** - * @param name the proxy string - * @deprecated This has been deprecated. Set your proxy directly with the JVM - */ - @Deprecated - public void setProxy(String name) { - proxy = name; - if (name == null) { - proxyEnabled = false; - } - } - - public void setServer(String name) { - server = name; - } - - /** - * @param enabled true if proxy is enabled - * @deprecated This has been deprecated. Set your proxy directly with the JVM - */ - @Deprecated - public void setProxyEnabled(boolean enabled) { - proxyEnabled = enabled; - } - - public void setServerEnabled(boolean enabled) { - serverEnabled = enabled; - } - - public void setClientEnabled(boolean enabled) { - clientEnabled = enabled; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return INDEXFIELDS; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/LeaseRequestMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/LeaseRequestMsg.java deleted file mode 100644 index ae360786..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/LeaseRequestMsg.java +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.net.URI; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.UUID; - -import java.net.URISyntaxException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.document.Attribute; -import net.jxta.document.Attributable; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.protocol.PeerAdvertisement; - - -/** - * A Leasing Protocol Request Message. - * - *

            
            - *  <xs:complexType name="LeaseRequestMessage">
            - *      <xs:sequence>
            - *          <xs:element name="Credential" type="jxta:Cred" />
            - *          <xs:element name="ClientAdv" minOccurs="0" >
            - *              <xs:complexType>
            - *                  <xs:complexContent>
            - *                      <xs:extension  base="jxta:PA">
            - *                          <xs:attribute name="expiration" use="required" type="xs:unsignedLong" />
            - *                      </xs:extension>
            - *                  </xs:complexContent>
            - *              </xs:complexType>
            - *          </xs:element>
            - *          <xs:element name="Option" minOccurs="0" maxOccurs="unbounded" type="xs:anyType" />
            - *      </xs:sequence>
            - *      <xs:attribute name="client_id" use="required" type="jxta:JXTAID" />
            - *      <xs:attribute name="requested_lease" type="xs:unsignedLong" />
            - *      <xs:attribute name="server_adv_gen" type="jxta:uuid" />
            - *      <xs:attribute name="referral_advs" type="xs:unsignedInt" />
            - *  </xs:complexType>
            - * 
            - * - * @since 2.5 - */ -public class LeaseRequestMsg { - - /** - * Log4J Logger - */ - private final static transient Logger LOG = Logger.getLogger(LeaseRequestMsg.class.getName()); - - private final static String LEASE_REQUEST_MSG = "LeaseRequestMessage"; - private final static String CLIENT_ID_ATTR = "client_id"; - private final static String REQUESTED_LEASE_ATTR = "requested_lease"; - private final static String SERVER_ADV_GEN_ATTR = "server_adv_gen"; - private final static String REFERRAL_ADVS_ATTR = "referral_advs"; - - private final static String CLIENT_CRED_TAG = "Credential"; - private final static String CLIENT_ADV_TAG = "ClientAdv"; - private final static String CLIENT_ADV_EXP_ATTR = "ClientAdv"; - - private final static String OPTION_TAG = "Options"; - - /** - * The ID of the client. - */ - private ID clientID = null; - - /** - * Length of lease to request. {@code Long.MIN_VALUE} means that no lease - * is being requested, instead the message is being sent to retrieve - * referrals. - */ - private long requestedLease = Long.MIN_VALUE; - - /** - * last UUID version of the server's advertisement that the client saw or - * {@code null} if client claims to have seen no pervious version. - */ - private UUID serverAdvGen = null; - - /** - * The number of referral advertisements being requested. - */ - private int referralAdvs = Integer.MIN_VALUE; - - /** - * The credential of the client. - */ - private XMLElement credential = null; - - /** - * The optional peer advertisement of the client. - */ - private PeerAdvertisement clientAdv = null; - - /** - * Expiration value for client peer advertisement. {@code Long.MIN_VALUE} - * means that no value has been specified. - */ - private long clientAdvExp = Integer.MIN_VALUE; - - /** - * Options - */ - private List options = new ArrayList(); - - /** - * New LeaseRequestMsg - */ - public LeaseRequestMsg() {} - - /** - * Construct from a XLMElement - **/ - public LeaseRequestMsg(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doc.getName().equals(getMessageType())) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + " from doc containing a '" + doc.getName() - + "'. Should be : " + getMessageType()); - } - - Enumeration eachAttr = doc.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute aLeaseReqAttr = (Attribute) eachAttr.nextElement(); - - if (REQUESTED_LEASE_ATTR.equals(aLeaseReqAttr.getName())) { - requestedLease = Long.valueOf(aLeaseReqAttr.getValue()); - } else if (SERVER_ADV_GEN_ATTR.equals(aLeaseReqAttr.getName())) { - serverAdvGen = UUID.fromString(aLeaseReqAttr.getValue()); - } else if (CLIENT_ID_ATTR.equals(aLeaseReqAttr.getName())) { - try { - URI srcURI = new URI(aLeaseReqAttr.getValue()); - ID srcID = IDFactory.fromURI(srcURI); - - setClientID(srcID); - } catch (URISyntaxException badID) { - IllegalArgumentException iae = new IllegalArgumentException("Bad ID in message"); - - iae.initCause(badID); - throw iae; - } - } else if ("type".equals(aLeaseReqAttr.getName())) { - ; - } else if ("xmlns:jxta".equals(aLeaseReqAttr.getName())) { - ; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + aLeaseReqAttr.getName()); - } - } - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - - if (null == getClientID()) { - throw new IllegalArgumentException("Missing client ID value."); - } - - if ((getRequestedLease() < 0) && (getRequestedLease() != Long.MIN_VALUE)) { - throw new IllegalArgumentException("Invalid requested lease duration."); - } - - if ((getReferralAdvs() < 0) && (getReferralAdvs() != Integer.MIN_VALUE)) { - throw new IllegalArgumentException("Invalid referral advertisements request value."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Object clone() throws CloneNotSupportedException { - LeaseRequestMsg clone = (LeaseRequestMsg) super.clone(); - - clone.setClientID(getClientID()); - clone.setServerAdvGen(getServerAdvGen()); - clone.setRequestedLease(getRequestedLease()); - clone.setReferralAdvs(getReferralAdvs()); - clone.setCredential(getCredential()); - return clone; - } - - /** - * Returns the ID of the client making this request. - * - * @return ID of the client. - */ - public ID getClientID() { - return clientID; - } - - /** - * Sets the ID of the client making this request. - * - * @param clientID ID of the client. - */ - public void setClientID(ID clientID) { - this.clientID = clientID; - } - - /** - * Returns the advertisement generation of the server advertisement which - * is known to the client. May be {@code null} to indicate that the client - * does not have a previous version of the server advertisement. - * - * @return The server advertisement generation. - */ - public UUID getServerAdvGen() { - return serverAdvGen; - } - - /** - * Sets the advertisement generation of the server advertisement which is - * known to the client. May be {@code null} to indicate that the client - * does not have a previous version of the server advertisement. - * - * @param serverAdvGen The server advertisement generation. - */ - public void setServerAdvGen(UUID serverAdvGen) { - this.serverAdvGen = serverAdvGen; - } - - /** - * Return the duration of the lease being requested. The duration must be - * a positive integer or {@code Long.MIN_VALUE} which indicates that no - * lease is being requested. - * - * @return The duration of the lease being requested. - */ - public long getRequestedLease() { - return requestedLease; - } - - /** - * Set the duration of the lease being requested. The duration must be - * a positive integer or {@code Long.MIN_VALUE} which indicates that no - * lease is being requested. - * - * @param requestedLease The duration of the lease being requested. - */ - public void setRequestedLease(long requestedLease) { - this.requestedLease = requestedLease; - } - - /** - * Returns the number of referral advertisements requested by the client. - * Must be a positive integer or {@code Integer.MIN_VALUE} which indicates - * that the default number is requested. - * @return the number of referral advertisements requested by the client. - */ - public int getReferralAdvs() { - return referralAdvs; - } - - /** - * Sets the number of referral advertisements requested by the client. - * Must be a positive integer or {@code Integer.MIN_VALUE} which indicates - * that the default number is requested. - * - * @param referralAdvs The number of referral advertisements requested. - */ - public void setReferralAdvs(int referralAdvs) { - this.referralAdvs = referralAdvs; - } - - /** - * Returns the credential of the client making this request in XML format. - * - * @return The credential associated with this request if any. May be - * {@code null} to indicate that no credential was provided. - */ - public XMLElement getCredential() { - return (XMLElement) ((null != credential) ? StructuredDocumentUtils.copyAsDocument(credential) : null); - } - - /** - * Sets the credential of the client making this request in XML format. - * - * @param newCred The credential associated with this request if any. May - * be {@code null} to indicate that no credential is being provided. - */ - public void setCredential(XMLElement newCred) { - this.credential = (XMLElement) ((null != newCred) ? StructuredDocumentUtils.copyAsDocument(newCred) : null); - } - - /** - * Our DOCTYPE - * - * @return the type of this message. - **/ - public static String getMessageType() { - return "jxta:LeaseRequestMsg"; - } - - protected boolean handleElement(XMLElement elem) { - - if (CLIENT_CRED_TAG.equals(elem.getName())) { - credential = (XMLElement) StructuredDocumentUtils.copyAsDocument(elem); - - return true; - } - - String value = elem.getTextValue(); - - if (null != value) { - value = value.trim(); - - if (0 == value.length()) { - value = null; - } - } - - if (null == value) { - return false; - } - - return false; - } - - /** - * {@inheritDoc} - **/ - public Document getDocument(MimeMediaType mediaType) { - - if (null == getClientID()) { - throw new IllegalStateException("Missing client ID value."); - } - - if ((getRequestedLease() < 0) && (getRequestedLease() != Long.MIN_VALUE)) { - throw new IllegalStateException("Invalid requested lease duration."); - } - - if ((getReferralAdvs() < 0) && (getReferralAdvs() != Integer.MIN_VALUE)) { - throw new IllegalStateException("Invalid referral advertisements request value."); - } - - StructuredDocument msg = StructuredDocumentFactory.newStructuredDocument(mediaType, getMessageType()); - - if (!(msg instanceof Attributable)) { - throw new UnsupportedOperationException("Only 'Attributable' document types are supported."); - } - - if (msg instanceof XMLDocument) { - ((XMLDocument) msg).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - ((Attributable) msg).addAttribute(CLIENT_ID_ATTR, getClientID().toString()); - - if (Long.MIN_VALUE != getRequestedLease()) { - ((Attributable) msg).addAttribute(REQUESTED_LEASE_ATTR, Long.toString(getRequestedLease())); - } - - if (null != getServerAdvGen()) { - ((Attributable) msg).addAttribute(SERVER_ADV_GEN_ATTR, getServerAdvGen().toString()); - } - - if (null != credential) { - StructuredDocumentUtils.copyElements(msg, msg, credential, CLIENT_CRED_TAG); - } - - return msg; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/LeaseResponseMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/LeaseResponseMsg.java deleted file mode 100644 index b0297458..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/LeaseResponseMsg.java +++ /dev/null @@ -1,626 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.UUID; - -import java.net.URISyntaxException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.Attributable; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.protocol.RdvAdvertisement; - - -/** - * A Leasing Protocol Response Message. - * - *

            
            - * 
            - *   
            - *     
            - *     
            - *       
            - *         
            - *           
            - *              
            - *             
            - *           
            - *         
            - *       
            - *     
            - *     
            - *       
            - *         
            - *           
            - *             
            - *           
            - *         
            - *       
            - *     
            - *   
            - *   
            - *   
            - * 
            - * 
            - * - * @since JXTA 2.4 - */ -public class LeaseResponseMsg { - - /** - * Log4J Logger - **/ - private final static transient Logger LOG = Logger.getLogger(LeaseResponseMsg.class.getName()); - - private final static String OFFERED_LEASE_ATTR = "offeredLease"; - - private final static String SERVER_ID_ATTR = "serverID"; - - private final static String SERVER_ADV_TAG = "serverAdv"; - private final static String ADV_GEN_ATTR = "advGen"; - private final static String ADV_EXP_ATTR = "expiration"; - private final static String REFERRAL_ADV_TAG = "referralAdv"; - - private final static String SERVER_CRED_TAG = "credential"; - - /** - * ID of the server providing this response. - */ - private ID serverID = null; - - /** - * The advertisement of the server providing this response. - */ - private RdvAdvertisement serverAdv = null; - - /** - * The expiration duration of the server advertisement. - */ - private long serverAdvExp = Long.MIN_VALUE; - - /** - * The advertisement generation of the server advertisement. - */ - private UUID serverAdvGen = null; - - /** - * Credential of the server. - */ - private XMLElement credential = null; - - /** - * Ordered list of referral advertisements. - */ - private List referralAdvs = new ArrayList(); - - /** - * Ordered list of referral advertisement expirations. The order matches - * the order of advertisements in {@link #referralAdvs}. - */ - private List referralAdvExps = new ArrayList(); - - /** - * The duration of the offered lease. May also be {@code Long.MIN_VALUE} to - * indicate that no lease is being offered. - */ - private long offeredLease = Long.MIN_VALUE; - - /** - * New LeaseResponseMsg - */ - public LeaseResponseMsg() {} - - /** - * Construct from a StructuredDocument - * @param root the element - */ - public LeaseResponseMsg(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doc.getName().equals(getMessageType())) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + " from doc containing a '" + doc.getName() - + "'. Should be : " + getMessageType()); - } - - Enumeration eachAttr = doc.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute aRdvAttr = (Attribute) eachAttr.nextElement(); - - if (SERVER_ID_ATTR.equals(aRdvAttr.getName())) { - try { - URI srcURI = new URI(aRdvAttr.getValue()); - ID srcID = IDFactory.fromURI(srcURI); - - setServerID(srcID); - } catch (URISyntaxException badID) { - IllegalArgumentException iae = new IllegalArgumentException("Bad server ID in message"); - - iae.initCause(badID); - throw iae; - } - } else if (OFFERED_LEASE_ATTR.equals(aRdvAttr.getName())) { - offeredLease = Long.valueOf(aRdvAttr.getValue()); - } else if ("type".equals(aRdvAttr.getName())) { - ; - } else if ("xmlns:jxta".equals(aRdvAttr.getName())) { - ; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + aRdvAttr.getName()); - } - } - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - - if (null == serverID) { - throw new IllegalArgumentException("Missing Server ID."); - } - - if ((null != serverAdv) && (null == serverAdvGen)) { - throw new IllegalArgumentException("Missing Server Advertisement Generation."); - } - - if ((null != serverAdv) && (Long.MIN_VALUE == serverAdvExp)) { - throw new IllegalArgumentException("Missing Server Advertisement Expiration."); - } - - if ((null != serverAdv) && (serverAdvExp <= 0)) { - throw new IllegalArgumentException("Illegal Server Advertisement Expiration."); - } - - if ((offeredLease < 0) && (Long.MIN_VALUE != offeredLease)) { - throw new IllegalArgumentException("Illegal Lease offered."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Object clone() throws CloneNotSupportedException { - LeaseResponseMsg clone = (LeaseResponseMsg) super.clone(); - - clone.setServerID(getServerID()); - clone.setServerAdv(getServerAdv(), getServerAdvGen(), getServerAdvExp()); - clone.setCredential(getCredential()); - clone.addReferralAdvs(Arrays.asList(getReferralAdvs()), Arrays.asList(getReferralAdvExps())); - clone.setOfferedLease(getOfferedLease()); - return clone; - } - - /** - * Returns the ID of the server providing this response. - * - * @return ID of the server. - */ - public ID getServerID() { - return serverID; - } - - /** - * Sets the ID of the server providing this response. - * - * @param serverID ID of the server. - */ - public void setServerID(ID serverID) { - this.serverID = serverID; - } - - /** - * Returns the advertisement of the server providing this response. - * - * @return The servers advertisement. - */ - public RdvAdvertisement getServerAdv() { - return serverAdv; - } - - /** - * Returns the advertisement generation of the server's advertisement. - * - * @return The advertisement generation of the server's advertisement. - */ - public UUID getServerAdvGen() { - return serverAdvGen; - } - - /** - * Returns the advertisement expiration duration of the server's - * advertisement. Must be a positive integer. - * - * @return The advertisement expiration duration of the server's advertisement. - */ - public long getServerAdvExp() { - return serverAdvExp; - } - - /** - * Sets the server advertisement and the associated advertisement - * generation and expiration. - * - * @param serverAdv The servers advertisement. - * @param serverAdvGen The advertisement generation of the server's - * advertisement. Must be a positive integer. - * @param serverAdvExp The advertisement expiration duration of the - * server's advertisement. - */ - public void setServerAdv(RdvAdvertisement serverAdv, UUID serverAdvGen, long serverAdvExp) { - this.serverAdv = serverAdv; - this.serverAdvGen = serverAdvGen; - this.serverAdvExp = serverAdvExp; - } - - /** - * Returns an ordered list of the referral advertisements. - * - * @return An ordered list of the referral advertisements. - */ - public RdvAdvertisement[] getReferralAdvs() { - return referralAdvs.toArray(new RdvAdvertisement[referralAdvs.size()]); - } - - /** - * Returns an ordered list of the referral advertisements expirations. The - * order of the expirations matches the order of advertisements returned - * by {@link #getReferralAdvs()}. Each entry is a positive integer. - * - * @return An ordered list of the referral advertisements expirations. - */ - public Long[] getReferralAdvExps() { - return referralAdvExps.toArray(new Long[referralAdvExps.size()]); - } - - /** - * Adds a referral advertisement to the collection of referral - * advertisements. The advertisement is added at the end of the ordered - * list. - * - * @param referralAdv The referral advertisement. - * @param referralAdvExp The expiration time of the referral advertisement. - * The value must be a positive integer. - */ - public void addReferralAdv(RdvAdvertisement referralAdv, long referralAdvExp) { - referralAdvs.add(referralAdv); - referralAdvExps.add(referralAdvExp); - } - - /** - * Adds referral advertisements to the collection of referral - * advertisements. The advertisements are added at the end of the ordered - * list. - * - * @param referralAdvs The referral advertisements. - * @param referralAdvExps The expiration times of the referral advertisement. - * The values must be a positive integer. - */ - public void addReferralAdvs(List referralAdvs, List referralAdvExps) { - this.referralAdvs.addAll(referralAdvs); - this.referralAdvExps.addAll(referralAdvExps); - } - - /** - * Clears the list of referral advertisements. - */ - public void clearReferralAdvs() { - referralAdvs.clear(); - referralAdvExps.clear(); - } - - /** - * Returns the lease being offered. The value must be greater than or - * equal to zero or the constant {@code Long.MIN_VALUE} which indicates - * that no lease is being offered. - * - * @return The lease being offered. - */ - public long getOfferedLease() { - return offeredLease; - } - - /** - * Sets the lease being offered. The value must be greater than or - * equal to zero or the constant {@code Long.MIN_VALUE} which indicates - * that no lease is being offered. - * - * @param offeredLease The lease being offered. - */ - public void setOfferedLease(long offeredLease) { - this.offeredLease = offeredLease; - } - - /** - * Returns the credential of the server providing this response in XML - * format. - * - * @return The credential associated with this response if any. May be - * {@code null} to indicate that no credential was provided. - */ - public XMLElement getCredential() { - return (XMLElement) ((null != credential) ? StructuredDocumentUtils.copyAsDocument(credential) : null); - } - - /** - * Sets the credential of the server providing this response in XML - * format. - * - * @param newCred The credential associated with this response if any. May - * be {@code null} to indicate that no credential is being provided. - */ - public void setCredential(XMLElement newCred) { - this.credential = (XMLElement) ((null != newCred) ? StructuredDocumentUtils.copyAsDocument(newCred) : null); - } - - /** - * Our DOCTYPE - * - * @return the type of this message. - */ - public static String getMessageType() { - return "jxta:LeaseResponseMsg"; - } - - /** - * Process an element of the message XML document. - * - * @param elem The element to process. - * @return If {@code true} then the element was processed otherwise {@code false}. - */ - protected boolean handleElement(XMLElement elem) { - - if (SERVER_ADV_TAG.equals(elem.getName())) { - Enumeration eachAttr = elem.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute anAdvAttr = (Attribute) eachAttr.nextElement(); - - if (ADV_GEN_ATTR.equals(anAdvAttr.getName())) { - serverAdvGen = UUID.fromString(anAdvAttr.getValue()); - } else if (ADV_EXP_ATTR.equals(anAdvAttr.getName())) { - serverAdvExp = Long.valueOf(anAdvAttr.getValue()); - } else if ("type".equals(anAdvAttr.getName())) { - ; - } else if ("xmlns:jxta".equals(anAdvAttr.getName())) { - ; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + anAdvAttr.getName()); - } - } - } - - serverAdv = (RdvAdvertisement) AdvertisementFactory.newAdvertisement(elem); - return true; - } else if (REFERRAL_ADV_TAG.equals(elem.getName())) { - long expiration = Long.MIN_VALUE; - - Enumeration eachAttr = elem.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute anAdvAttr = (Attribute) eachAttr.nextElement(); - - if (ADV_EXP_ATTR.equals(anAdvAttr.getName())) { - expiration = Long.valueOf(anAdvAttr.getValue()); - } else if ("type".equals(anAdvAttr.getName())) { - ; - } else if ("xmlns:jxta".equals(anAdvAttr.getName())) { - ; - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + anAdvAttr.getName()); - } - } - } - - if (Long.MIN_VALUE == expiration) { - throw new IllegalArgumentException("Missing Referral Advertisement Expiration."); - } - - if (expiration <= 0) { - throw new IllegalArgumentException("Illegal Referral Advertisement Expiration."); - } - - RdvAdvertisement referralAdv = (RdvAdvertisement) AdvertisementFactory.newAdvertisement(elem); - - // Fix the embedded Route Adv. Often it does not contain a PeerID - // in the route because its redundant. - referralAdv.getRouteAdv().setDestPeerID(referralAdv.getPeerID()); - - referralAdvs.add(referralAdv); - referralAdvExps.add(expiration); - return true; - } else if (SERVER_CRED_TAG.equals(elem.getName())) { - credential = (XMLElement) StructuredDocumentUtils.copyAsDocument(elem); - - return true; - } - - return false; - } - - /** - * {@inheritDoc} - */ - public Document getDocument(MimeMediaType mediaType) { - if (null == serverID) { - throw new IllegalStateException("Missing Server ID."); - } - - if ((null != serverAdv) && (null == serverAdvGen)) { - throw new IllegalStateException("Missing Server Advertisement Generation."); - } - - if ((null != serverAdv) && (Long.MIN_VALUE == serverAdvExp)) { - throw new IllegalStateException("Missing Server Advertisement Expiration."); - } - - if ((null != serverAdv) && (serverAdvExp <= 0)) { - throw new IllegalStateException("Illegal Server Advertisement Expiration."); - } - - if ((offeredLease < 0) && (Long.MIN_VALUE != offeredLease)) { - throw new IllegalStateException("Illegal Lease offered."); - } - - StructuredDocument msg = StructuredDocumentFactory.newStructuredDocument(mediaType, getMessageType()); - - if (!(msg instanceof Attributable)) { - throw new UnsupportedOperationException("Only 'Attributable' document types are supported."); - } - - if (msg instanceof XMLDocument) { - ((XMLDocument) msg).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - ((Attributable) msg).addAttribute(SERVER_ID_ATTR, getServerID().toString()); - - if (Long.MIN_VALUE != offeredLease) { - ((Attributable) msg).addAttribute(OFFERED_LEASE_ATTR, Long.toString(getOfferedLease())); - } - - if (null != credential) { - StructuredDocumentUtils.copyElements(msg, msg, credential, SERVER_CRED_TAG); - } - - Element e; - - if (null != serverAdv) { - e = StructuredDocumentUtils.copyElements(msg, msg, (StructuredDocument) serverAdv.getDocument(mediaType) - , - SERVER_ADV_TAG); - - if (null != getServerAdvGen()) { - ((Attributable) e).addAttribute(ADV_GEN_ATTR, getServerAdvGen().toString()); - } - - if (Long.MIN_VALUE != getServerAdvExp()) { - ((Attributable) e).addAttribute(ADV_EXP_ATTR, Long.toString(getServerAdvExp())); - } - } - - Iterator eachReferralAdvExp = referralAdvExps.iterator(); - - for (RdvAdvertisement aReferralAdv : referralAdvs) { - e = StructuredDocumentUtils.copyElements(msg, msg, (StructuredDocument) aReferralAdv.getDocument(mediaType) - , - REFERRAL_ADV_TAG); - - long expiration = eachReferralAdvExp.next(); - - if (Long.MIN_VALUE == expiration) { - throw new IllegalStateException("Missing Referral Advertisement Expiration."); - } - - if (expiration <= 0) { - throw new IllegalStateException("Illegal Referral Advertisement Expiration."); - } - - ((Attributable) e).addAttribute(ADV_EXP_ATTR, Long.toString(expiration)); - } - - return msg; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/LimitedRangeRdvMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/LimitedRangeRdvMsg.java deleted file mode 100644 index 57b3d747..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/LimitedRangeRdvMsg.java +++ /dev/null @@ -1,473 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - - -/** - * The LimitedRangeRdv walk header message. - *

            - *

            
            - * <xs:simpleType name="WalkDirection">
            - *   <xs:restriction base="xs:unsignedInt">
            - *     <!-- UP -->
            - *     <xs:enumeration value="1" />
            - *     <!-- DOWN -->
            - *     <xs:enumeration value="2" />
            - *     <!-- BOTH -->
            - *     <xs:enumeration value="3" />
            - *   </xs:restriction>
            - * </xs:simpleType>
            - * 

            - * <xs:complexType name="LimitedRangeRdvMessage"> - * <xs:sequence> - * <xs:element name="TTL" type="xs:unsignedInt" /> - * <xs:element name="Dir" type="jxta:WalkDirection" /> - * <xs:element name="SrcPeerID" type="jxta:JXTAID" /> - * <xs:element name="SrcSvcName" type="xs:string" /> - * <xs:element name="SrcSvcParams" minOccurs="0" type="xs:string" /> - * </xs:sequence> - * </xs:complexType> - *

            - * - * @see net.jxta.impl.rendezvous.limited.LimitedRangeWalk - * @see net.jxta.impl.rendezvous.limited.LimitedRangeWalker - * @see net.jxta.impl.rendezvous.limited.LimitedRangeGreeter - * @since JXTA 2.0 - */ -public class LimitedRangeRdvMsg { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(LimitedRangeRdvMsg.class.getName()); - - private final static String TTL_ELEMENT = "TTL"; - private final static String DIRECTION_ELEMENT = "Dir"; - private final static String SRCPEERID_ELEMENT = "SrcPeerID"; - private final static String SRCSVCNAME_ELEMENT = "SrcSvcName"; - private final static String SRCSVCPARAM_ELEMENT = "SrcSvcParams"; - - private int ttl = 0; - private WalkDirection direction = null; - private PeerID srcPeerID = null; - private String srcSvcName = null; - private String srcSvcParams = null; - - /** - * Enumeration of possible walk directions. - */ - public enum WalkDirection { - UP(1), DOWN(2), BOTH(3); - - /** - * The protocol integer value associated with this direction. - */ - private final int proto_direction; - - private WalkDirection(int direction) { - proto_direction = direction; - } - - /** - * Convert a walk code as used by the standard walker protocol to a - * direction object. - * - * @param code the protocol code - * @return A direction object. - * @throws IllegalArgumentException For illegal protocol codes. - */ - public static WalkDirection toWalkDirection(int code) { - switch (code) { - case 1: - return UP; - - case 2: - return DOWN; - - case 3: - return BOTH; - - default: - throw new IllegalArgumentException("Illegal direction"); - } - } - - /** - * Return the protocol code used by the standard walker protocol for - * this WalkDirection. - * - * @return the walk direction as a numeric value for use in protocol - * messages. - */ - public int toProtocolCode() { - return proto_direction; - } - } - - /** - * Constructor - */ - public LimitedRangeRdvMsg() {} - - /** - * Construct from a StructuredDocument - * - * @param root the element - */ - public LimitedRangeRdvMsg(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XMLElement"); - } - - XMLElement doc = (XMLElement) root; - - if (!doc.getName().equals(getMessageType())) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + " from doc containing a '" + doc.getName() - + "'. Should be : " + getMessageType()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem); - } - } - } - - // Sanity check time! - if (getTTL() < 1) { - throw new IllegalArgumentException("Illegal TTL value."); - } - - if (null == getDirection()) { - throw new IllegalArgumentException("No Direction specified."); - } - - if (null == getSrcPeerID()) { - throw new IllegalArgumentException("No source peer id specified."); - } - - if (null == getSrcSvcName()) { - throw new IllegalArgumentException("No source service name specified."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public LimitedRangeRdvMsg clone() { - - try { - LimitedRangeRdvMsg clone = (LimitedRangeRdvMsg) super.clone(); - - clone.setSrcPeerID(getSrcPeerID()); - clone.setDirection(getDirection()); - clone.setTTL(getTTL()); - clone.setSrcSvcName(getSrcSvcName()); - clone.setSrcSvcParams(getSrcSvcParams()); - - return clone; - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - } - - /** - * Get the TTL - * - * @return Time To Live - */ - public int getTTL() { - return ttl; - } - - /** - * set the TTL - * - * @param ttl TTL - */ - public void setTTL(int ttl) { - this.ttl = ttl; - } - - /** - * Get the direction the message will take - * - * @return UP, DOWN or BOTH - */ - public WalkDirection getDirection() { - return direction; - } - - /** - * Set the direction the message will take - * - * @param dir direction - */ - public void setDirection(WalkDirection dir) { - direction = dir; - } - - /** - * Get the Source Service Name (listening for the response) - * - * @return Source Service Name - */ - public String getSrcSvcName() { - return srcSvcName; - } - - /** - * Set the Source Service Name (listening for the response) - * - * @param srcSvcName Source Service Name - */ - public void setSrcSvcName(String srcSvcName) { - this.srcSvcName = srcSvcName; - } - - /** - * Get the Source Service Param (listening for the response) - * - * @return Source Service Param - */ - public String getSrcSvcParams() { - return srcSvcParams; - } - - /** - * Set the Source Service Params (listening for the response) - * - * @param srcSvcParams Source Service Params - */ - public void setSrcSvcParams(String srcSvcParams) { - this.srcSvcParams = srcSvcParams; - } - - /** - * Get the Source PeerID (walk originiator) - * - * @return Source PeerID - */ - public ID getSrcPeerID() { - return srcPeerID; - } - - /** - * Set the Source PeerID (walk originiator) - * - * @param srcPeerID Source PeerID - */ - public void setSrcPeerID(ID srcPeerID) { - this.srcPeerID = (PeerID) srcPeerID; - } - - /** - * Our DOCTYPE - * - * @return the type of this message. - */ - public static String getMessageType() { - return "jxta:LimitedRangeRdvMessage"; - } - - /** - * Process an individual element from the document during parse. Normally, - * implementations will allow the base advertisments a chance to handle the - * element before attempting ot handle the element themselves. ie. - *

            - *

            
            -     *  protected boolean handleElement( Element elem ) {
            -     * 

            - * if ( super.handleElement() ) { - * // it's been handled. - * return true; - * } - *

            - * ... handle elements here ... - *

            - * // we don't know how to handle the element - * return false; - * } - *

            - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - */ - protected boolean handleElement(XMLElement elem) { - - String value = elem.getTextValue(); - - if (null != value) { - value = value.trim(); - - if (0 == value.length()) { - value = null; - } - } - - if (null == value) { - return false; - } - - if (elem.getName().equals(TTL_ELEMENT)) { - setTTL(Integer.parseInt(value)); - return true; - } - - if (elem.getName().equals(DIRECTION_ELEMENT)) { - int direction = Integer.parseInt(value); - - setDirection(LimitedRangeRdvMsg.WalkDirection.toWalkDirection(direction)); - return true; - } - - if (elem.getName().equals(SRCPEERID_ELEMENT)) { - try { - URI srcURI = new URI(value); - ID srcID = IDFactory.fromURI(srcURI); - - setSrcPeerID(srcID); - } catch (URISyntaxException badID) { - IllegalArgumentException iae = new IllegalArgumentException("Bad ID in message"); - - iae.initCause(badID); - throw iae; - } - return true; - } - - if (elem.getName().equals(SRCSVCNAME_ELEMENT)) { - setSrcSvcName(value); - return true; - } - - if (elem.getName().equals(SRCSVCPARAM_ELEMENT)) { - setSrcSvcParams(value); - return true; - } - - return false; - } - - /** - * @inheritDoc - */ - public Document getDocument(MimeMediaType mediaType) { - - if (getTTL() < 1) { - throw new IllegalStateException("Illegal TTL value."); - } - - if (null == getDirection()) { - throw new IllegalStateException("No Direction specified."); - } - - if (null == getSrcPeerID()) { - throw new IllegalStateException("No source peer id specified."); - } - - if (null == getSrcSvcName()) { - throw new IllegalStateException("No source service name specified."); - } - - StructuredDocument msg = StructuredDocumentFactory.newStructuredDocument(mediaType, getMessageType()); - - if (msg instanceof XMLDocument) { - ((XMLDocument) msg).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - Element e = msg.createElement(TTL_ELEMENT, Integer.toString(getTTL())); - - msg.appendChild(e); - - e = msg.createElement(DIRECTION_ELEMENT, Integer.toString(getDirection().toProtocolCode())); - msg.appendChild(e); - - e = msg.createElement(SRCPEERID_ELEMENT, getSrcPeerID().toString()); - msg.appendChild(e); - - e = msg.createElement(SRCSVCNAME_ELEMENT, getSrcSvcName()); - msg.appendChild(e); - - if (getSrcSvcParams() != null) { - e = msg.createElement(SRCSVCPARAM_ELEMENT, getSrcSvcParams()); - msg.appendChild(e); - } - - return msg; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ModuleClassAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ModuleClassAdv.java deleted file mode 100644 index 0575bd2b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ModuleClassAdv.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.id.IDFactory; -import net.jxta.platform.ModuleClassID; -import net.jxta.protocol.ModuleClassAdvertisement; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - - -/** - * Provides XML serialization support for ModuleClassAdvertisement matching the - * schema defined by the JXTA Core Specification. - *

            - *

            - *  <xs:complexType name="MCA">
            - *    <xs:sequence>
            - *      <xs:element name="MCID" type="jxta:JXTAID" />
            - *      <xs:element name="Name" type="xs:string" minOccurs="0" />
            - *      <xs:element name="Desc" type="xs:anyType" minOccurs="0" />
            - *    </xs:sequence>
            - *  </xs:complexType>
            - *  
            - * - * @see net.jxta.document.Advertisement - * @see net.jxta.protocol.ModuleSpecAdvertisement - * @see elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - if (null == getModuleClassID()) { - throw new IllegalArgumentException("Module Class ID was not specified."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (elem.getName().equals(nameTag)) { - setName(elem.getTextValue()); - return true; - } - - if (elem.getName().equals(descTag)) { - setDesc(elem); - return true; - } - - if (elem.getName().equals(idTag)) { - try { - URI clID = new URI(elem.getTextValue()); - - setModuleClassID((ModuleClassID) IDFactory.fromURI(clID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad mcid in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Unusable mcid in advertisement"); - } - return true; - } - - return false; - - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - if (null == getModuleClassID()) { - throw new IllegalStateException("Module Class ID was not specified."); - } - - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - Element e; - - e = adv.createElement(idTag, getModuleClassID().toString()); - adv.appendChild(e); - - // name is optional - String name = getName(); - - if (null != name) { - e = adv.createElement(nameTag, name); - adv.appendChild(e); - } - - // desc is optional - StructuredDocument desc = getDesc(); - - if (desc != null) { - StructuredDocumentUtils.copyElements(adv, adv, desc); - } - - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return fields; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ModuleImplAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ModuleImplAdv.java deleted file mode 100644 index 6dea104d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ModuleImplAdv.java +++ /dev/null @@ -1,344 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleImplAdvertisement; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - - -/** - * Provides XML serialization support for ModuleImplAdvertisement matching the - * schema defined by the JXTA Core Specification. - *

            - *

            - * <xs:complexType name="MIA">
            - *   <xs:sequence>
            - *     <xs:element name="MSID" type="jxta:JXTAID"/>
            - *     <xs:element name="Comp" type="xs:anyType"/>
            - *     <xs:element name="Code" type="xs:anyType"/>
            - *     <xs:element name="PURI" type="xs:anyURI" minOccurs="0"/>
            - *     <xs:element name="Prov" type="xs:string" minOccurs="0"/>
            - *     <xs:element name="Desc" type="xs:anyType" minOccurs="0"/>
            - *     <xs:element name="Parm" type="xs:anyType" minOccurs="0"/>
            - *   </xs:sequence>
            - * </xs:complexType>
            - * 
            - * - * @see net.jxta.document.Advertisement - * @see net.jxta.protocol.ModuleImplAdvertisement - * @see
            for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.id.IDFactory; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleSpecAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - - -/** - * Provides XML serialization support for ModuleSpecAdvertisement matching the - * schema defined by the JXTA Core Specification. - *

            - *

            - *  <xs:complexType name="MSA">
            - *    <xs:sequence>
            - *      <xs:element name="MSID" type="jxta:JXTAID" />
            - *      <xs:element name="Name" type="xs:string" minOccurs="0" />
            - *      <xs:element name="Desc" type="xs:anyType" minOccurs="0" />
            - *      <xs:element name="Crtr" type="xs:string" minOccurs="0" />
            - *      <xs:element name="SURI" type="xs:anyURI" minOccurs="0" />
            - *      <xs:element name="Vers" type="xs:string" />
            - *      <xs:element name="Parm" type="xs:anyType" minOccurs="0" />
            - *      <xs:element ref="jxta:PipeAdvertisement" minOccurs="0" />
            - *      <xs:element name="Proxy" type="xs:anyURI" minOccurs="0" />
            - *      <xs:element name="Auth" type="jxta:JXTAID" minOccurs="0" />
            - *    </xs:sequence>
            - *  </xs:complexType>
            - * 
            - * - * @see net.jxta.document.Advertisement - * @see net.jxta.protocol.ModuleSpecAdvertisement - * @see
            for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.StringReader; -import java.net.URI; -import java.security.PrivateKey; -import java.security.cert.X509Certificate; -import java.security.cert.CertificateFactory; -import java.util.Enumeration; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.List; -import javax.crypto.EncryptedPrivateKeyInfo; - -import java.io.IOException; -import java.lang.reflect.UndeclaredThrowableException; -import java.net.URISyntaxException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.membership.pse.PSEUtils; -import net.jxta.peergroup.PeerGroupID; - - -/** - * Contains parameters for configuration of the PSE Membership Service. - * - *

            The configuration advertisement can include an optional seed certificate - * chain and encrypted private key. If this seed information is present the PSE - * Membership Service will require an initial authentication to unlock the - * encrypted private key before creating the PSE keystore. The newly created - * PSE keystore will be "seeded" with the certificate chain and the private key. - * - *

            This mechanism allows for out-of-band distribution of JXTA identity - * information and avoids the need for remote authentication. - * - *

            Note: This implementation contemplates multiple root certs in its - * schema, but the API has not yet been extended to include this functionality. - */ -public final class PSEConfigAdv extends ExtendableAdvertisement implements Cloneable { - - /** - * Log4J Logger - */ - private final static transient Logger LOG = Logger.getLogger(PSEConfigAdv.class.getName()); - - /** - * Our DOCTYPE - */ - private final static String advType = "jxta:PSEConfig"; - - /** - * Instantiator for PSEConfigAdv - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return advType; - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new PSEConfigAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - return new PSEConfigAdv(root); - } - } - - private final static String ROOT_CERT_TAG = "RootCert"; - private final static String CERT_TAG = "Certificate"; - private final static String ENCRYPTED_PRIVATE_KEY_TAG = "EncryptedPrivateKey"; - private final static String KEY_STORE_TYPE_ATTR = "KeyStoreType"; - private final static String KEY_STORE_PROVIDER_ATTR = "KeyStoreProvider"; - private final static String KEY_STORE_LOCATION_TAG = "KeyStoreLocation"; - - private final static String[] INDEX_FIELDS = {}; - - private final List certs = new ArrayList(); - - private EncryptedPrivateKeyInfo encryptedPrivateKey = null; - - private String privAlgorithm = null; - - private String keyStoreType = null; - - private String keyStoreProvider = null; - - private URI keyStoreLocation = null; - - /** - * Returns the identifying type of this Advertisement. - * - *

            Note: This is a static method. It cannot be used to determine - * the runtime type of an advertisement. ie. - *

            -     *      Advertisement adv = module.getSomeAdv();
            -     *      String advType = adv.getAdvertisementType();
            -     *  
            - * - *

            This is wrong and does not work the way you might expect. - * This call is not polymorphic and calls - * {@code Advertisement.getAdvertisementType()} no matter what the real - * type of the advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return advType; - } - - /** - * Use the Instantiator through the factory - */ - private PSEConfigAdv() {} - - /** - * Use the Instantiator through the factory - * - * @param root The XMLElement which is the root element of the PSEConfigAdv. - */ - private PSEConfigAdv(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration eachAttr = doc.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute anAttr = (Attribute) eachAttr.nextElement(); - - if (super.handleAttribute(anAttr)) { - // nothing to do - ; - } else if (KEY_STORE_TYPE_ATTR.equals(anAttr.getName())) { - keyStoreType = anAttr.getValue().trim(); - } else if (KEY_STORE_PROVIDER_ATTR.equals(anAttr.getName())) { - keyStoreProvider = anAttr.getValue().trim(); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + anAttr.getName()); - } - } - } - - certs.clear(); - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - } - - /** - * {@inheritDoc} - */ - @Override - public PSEConfigAdv clone() { - - PSEConfigAdv result; - - try { - result = (PSEConfigAdv) super.clone(); - } catch (CloneNotSupportedException e) { - throw new Error("Object.clone() threw CloneNotSupportedException", e); - } - - result.setKeyStoreLocation(getKeyStoreLocation()); - result.setKeyStoreType(getKeyStoreType()); - result.setKeyStoreProvider(getKeyStoreProvider()); - - result.setEncryptedPrivateKey(getEncryptedPrivateKey(), getEncryptedPrivateKeyAlgo()); - result.setCertificateChain(getCertificateChain()); - - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public ID getID() { - InputStream data = new ByteArrayInputStream(getCert().getBytes()); - - try { - return IDFactory.newCodatID(PeerGroupID.worldPeerGroupID, new byte[16], data); - } catch (IOException failed) { - throw new UndeclaredThrowableException(failed, "Could not generate id"); - } - } - - /** - * Returns the seed certificate. If present, this certificate will be used - * to initialize the PSE keystore and will be stored using the peer id of - * the authenticating peer. - * - * @return The seed certificate or {@code null} if there is no seed - * certificate defined. - */ - public X509Certificate getCertificate() { - if (certs.isEmpty()) { - return null; - } else { - return certs.get(0); - } - } - - /** - * Returns the seed certificate chain. If present, this certificate chain - * will be used to initialize the PSE keystore and will be stored using the - * peer id of the authenticating peer. - * - * @return the seed certificate chain for this peer or {@code null} if - * there is no seed certificate chain defined. - */ - public X509Certificate[] getCertificateChain() { - return certs.toArray(new X509Certificate[certs.size()]); - } - - /** - * Returns the seed certificate encoded as a BASE64 String. - * - * @return the seed certificate encoded as a BASE64 String. - */ - public String getCert() { - X509Certificate rootCert = getCertificate(); - - if (null != rootCert) { - try { - return PSEUtils.base64Encode(getCertificate().getEncoded()); - } catch (Throwable failed) { - throw new IllegalStateException("Failed to process seed cert"); - } - } else { - return null; - } - } - - /** - * Sets the seed certificate for this peer from a BASE64 String. - * - * @param newCert The seed certificate for this peer as a BASE64 String. - */ - public void setCert(String newCert) { - try { - byte[] cert_der = PSEUtils.base64Decode(new StringReader(newCert)); - - CertificateFactory cf = CertificateFactory.getInstance("X509"); - - setCertificate((X509Certificate) cf.generateCertificate(new ByteArrayInputStream(cert_der))); - } catch (Exception failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failed to process seed cert", failed); - } - - IllegalArgumentException failure = new IllegalArgumentException("Failed to process seed cert"); - - failure.initCause(failed); - - throw failure; - } - } - - /** - * Sets the seed certificate for this peer. If {@code null} then the - * Private Key is also cleared. - * - * @param newCert The seed certificate for this PSE instance or {@code null} - * to clear the seed certificates and private key. - */ - public void setCertificate(X509Certificate newCert) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("setCert : " + newCert); - } - - certs.clear(); - - if (null == newCert) { - encryptedPrivateKey = null; - } else { - certs.add(newCert); - } - } - - /** - * Sets the seed Certificate chain for this peer. If {@code null} then the - * Private Key is also cleared. - * - * @param newCerts The seed certificate chain or {@code null} - * to clear the seed certificates and private key. - */ - public void setCertificateChain(X509Certificate[] newCerts) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("setCert : " + newCerts); - } - - certs.clear(); - - if (null == newCerts) { - encryptedPrivateKey = null; - } else { - certs.addAll(Arrays.asList(newCerts)); - } - } - - /** - * Get the seed private key from this advertisement. The private key is - * retrieved from the advertisement using the provided password. - * - * @param password the password to use in attempting to decrypt the private - * key. - * @return the decrypted private key. - */ - public PrivateKey getPrivateKey(char[] password) { - - return PSEUtils.pkcs5_Decrypt_pbePrivateKey(password, privAlgorithm, encryptedPrivateKey); - } - - /** - * Get the encrypted seed private key from this advertisement. - * - * @return the encrypted seed private key. - */ - public EncryptedPrivateKeyInfo getEncryptedPrivateKey() { - - return encryptedPrivateKey; - } - - /** - * Get the encrypted seed private key algorithm from this advertisement. - * - * @return the decrypted seed private key algorithm. - */ - public String getEncryptedPrivateKeyAlgo() { - - return privAlgorithm; - } - - /** - * Get the encrypted seed private key from this advertisement. - * - * @return the encoded encrypted private key, a BASE64 String of a DER - * encoded PKCS8 EncrpytePrivateKeyInfo. - */ - public String getEncryptedPrivKey() { - try { - if (null == encryptedPrivateKey) { - return null; - } - - return PSEUtils.base64Encode(encryptedPrivateKey.getEncoded()); - } catch (Exception failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failed to process private key", failed); - } - - IllegalStateException failure = new IllegalStateException("Failed to process private key"); - - failure.initCause(failed); - throw failure; - } - } - - /** - * Return the JCE Keystore type which the PSE Membership Service should use. - * This value should be the name of valid JCE Keystore or {@code null} if - * the default Keystore type should be used. The PSE Membership Service - * will create the keystore via - * {@code KeyStore.getInstance(keystore_type)}. - * - * @return The name of the Keystore type which the PSE Membership Service - * will use or {@code null} if the default keystore type should be used. - */ - public String getKeyStoreType() { - return keyStoreType; - } - - /** - * Set the JCE Keystore type which the PSE Membership Service - * should use. This value should be the name of valid JCE Keystore or - * {@code null} if the default Keystore type should be used. The PSE - * Membership Service will create the keystore via - * {@code KeyStore.getInstance(keystore_type)}. - * - * @param type The JCE Keystore type which the PSE Membership Service - * should use. This value should be the name of valid JCE Keystore or - * {@code null} if the default Keystore type should be used. - */ - public void setKeyStoreType(String type) { - keyStoreType = type; - } - - /** - * Return the JCE provider which the PSE Membership Service - * should use for Keystores. This value should be the name of valid JCE - * provider or {@code null} if the default provider should be used. The PSE - * Membership Service will create the keystore via - * {@code KeyStore.getInstance(keystore_type, provider)}. - * - * @return The JCE provider which the PSE Membership Service - * should use for Keystores. This value should be the name of valid JCE - * provider or {@code null} if the default provider should be used. - */ - public String getKeyStoreProvider() { - return keyStoreProvider; - } - - /** - * Set the JCE provider which the PSE Membership Service - * should use for Keystores. This value should be the name of valid JCE - * provider or {@code null} if the default provider should be used. The PSE - * Membership Service will create the keystore via - * {@code KeyStore.getInstance(keystore_type, provider)}. - * - * @param provider The JCE provider which the PSE Membership Service - * should use for Keystores. This value should be the name of valid JCE - * provider or {@code null} if the default provider should be used. - */ - public void setKeyStoreProvider(String provider) { - keyStoreProvider = provider; - } - - /** - * Return the location of the Keystore or {@code null} if the PSE - * Membership Service should use the default location. The actual default - * location may vary depending upon they Keystore type and provider and not - * all location values may be valid for all Keystore types and providers. - * - * @return The location of the Keystore or {@code null} if the PSE - * Membership Service should use the default location. - */ - public URI getKeyStoreLocation() { - return keyStoreLocation; - } - - /** - * Set the location of the Keystore or {@code null} if the PSE - * Membership Service should use the default location. The actual default - * location may vary depending upon they Keystore type and provider and not - * all location values may be valid for all Keystore types and providers. - * - * @param location The location of the Keystore or {@code null} if the PSE - * Membership Service should use the default location. - */ - public void setKeyStoreLocation(URI location) { - keyStoreLocation = location; - } - - /** - * Set the encrypted private key for this advertisement. The private key - * is provided as a BASE64 String of a DER encoded PKCS8 - * EncrpytePrivateKeyInfo. - * - * @param newPriv a BASE64 String of a DER encoded PKCS8 - * EncrpytePrivateKeyInfo. - * @param algorithm The public key algorithm used by this private key. - * Currently only "RSA" is supported. - */ - public void setEncryptedPrivateKey(String newPriv, String algorithm) { - try { - byte[] key_der = PSEUtils.base64Decode(new StringReader(newPriv)); - - EncryptedPrivateKeyInfo newEncryptedPriv = new EncryptedPrivateKeyInfo(key_der); - - setEncryptedPrivateKey(newEncryptedPriv, algorithm); - } catch (Exception failed) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failed to process private key", failed); - } - - IllegalArgumentException failure = new IllegalArgumentException("Failed to process private key"); - - failure.initCause(failed); - - throw failure; - } - } - - /** - * Set the encrypted seed private key for this advertisement. - * - * @param newPriv The encrypted seed private key. - * @param algorithm The public key algorithm used by this private key. - * Currently only "RSA" is supported. - */ - public void setEncryptedPrivateKey(EncryptedPrivateKeyInfo newPriv, String algorithm) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("setPrivateKey : " + newPriv); - } - - encryptedPrivateKey = newPriv; - privAlgorithm = algorithm; - } - - /** - * Set the encrypted seed private key for this advertisement. - * - * @param password The password to be used in encrypting the private key - * @param newPriv The private key to be stored in encrypted form. - */ - public void setPrivateKey(PrivateKey newPriv, char[] password) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("setPrivateKey : " + newPriv); - } - - EncryptedPrivateKeyInfo encypted = PSEUtils.pkcs5_Encrypt_pbePrivateKey(password, newPriv, 500); - - setEncryptedPrivateKey(encypted, newPriv.getAlgorithm()); - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (ROOT_CERT_TAG.equals(elem.getName())) { - - Enumeration elements = elem.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement eachcertelem = (XMLElement) elements.nextElement(); - - if (CERT_TAG.equals(eachcertelem.getName())) { - // XXX bondolo 20040415 backwards compatibility - eachcertelem.addAttribute("type", net.jxta.impl.protocol.Certificate.getMessageType()); - - net.jxta.impl.protocol.Certificate certChain = new net.jxta.impl.protocol.Certificate(eachcertelem); - - setCertificateChain(certChain.getCertificates()); - - continue; - } - - if (ENCRYPTED_PRIVATE_KEY_TAG.equals(eachcertelem.getName())) { - String value = eachcertelem.getTextValue(); - - if (null == value) { - throw new IllegalArgumentException("Empty Private Key element"); - } - - value = value.trim(); - - Attribute algo = eachcertelem.getAttribute("algorithm"); - - if (null == algo) { - throw new IllegalArgumentException("Private Key element must include algorithm attribute"); - } - - setEncryptedPrivateKey(value, algo.getValue()); - continue; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + eachcertelem.getName()); - } - - } - - return true; - } - - if (KEY_STORE_LOCATION_TAG.equals(elem.getName())) { - try { - keyStoreLocation = new URI(elem.getTextValue()); - } catch (URISyntaxException badURI) { - IllegalArgumentException iae = new IllegalArgumentException("Bad key store location URI"); - - iae.initCause(badURI); - - throw iae; - } - - return true; - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - if (adv instanceof Attributable) { - Attributable attrDoc = (Attributable) adv; - - if (null != keyStoreType) { - attrDoc.addAttribute(KEY_STORE_TYPE_ATTR, keyStoreType); - - if (null != keyStoreProvider) { - attrDoc.addAttribute(KEY_STORE_PROVIDER_ATTR, keyStoreProvider); - } - } - } - - if (null != keyStoreLocation) { - Element keyStoreLocationURI = adv.createElement(KEY_STORE_LOCATION_TAG, keyStoreLocation.toString()); - - adv.appendChild(keyStoreLocationURI); - } - - String encodedRoot = getCert(); - String encodedPrivateKey = getEncryptedPrivKey(); - - if ((null != encodedRoot) && (null != encodedPrivateKey)) { - Element rootcert = adv.createElement(ROOT_CERT_TAG, null); - - adv.appendChild(rootcert); - - // FIXME bondolo 20040501 needs to write certificate chain. - - Element cert = adv.createElement(CERT_TAG, encodedRoot); - - rootcert.appendChild(cert); - - Element privatekey = adv.createElement(ENCRYPTED_PRIVATE_KEY_TAG, encodedPrivateKey); - - rootcert.appendChild(privatekey); - - if (privatekey instanceof Attributable) { - ((Attributable) privatekey).addAttribute("algorithm", privAlgorithm); - } - } - - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return INDEX_FIELDS; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerAdv.java deleted file mode 100644 index 39c8a0a6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerAdv.java +++ /dev/null @@ -1,364 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.net.URI; -import java.util.Enumeration; -import java.util.Hashtable; - -import java.net.URISyntaxException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.platform.ModuleClassID; -import net.jxta.protocol.PeerAdvertisement; - - -/** - * Implementation of {@link PeerAdvertisement} matching the standard JXTA - * Protocol Specification. - * - * It implements Peer Advertisement using the following schema: - * - *

            
            - * <xs:complexType name="PA">
            - *   <xs:sequence>
            - *     <xs:element name="PID" type="JXTAID"/>
            - *     <xs:element name="GID" type="JXTAID"/>
            - *     <xs:element name="Name" type="xs:string" minOccurs="0"/>
            - *     <xs:element name="Desc" type="xs:anyType" minOccurs="0"/>
            - *     <xs:element name="Svc" type="jxta:serviceParams" minOccurs="0" maxOccurs="unbounded"/>
            - *   <xs:sequence>
            - * </xs:complexType>
            - * 
            - * - * @see net.jxta.protocol.PeerAdvertisement - * @see
            JXTA Protocols Specification : Peer Advertisement - **/ -public class PeerAdv extends PeerAdvertisement { - - /** - * Logger - **/ - private static final Logger LOG = Logger.getLogger(PeerAdv.class.getName()); - - private static final String pidTag = "PID"; - private static final String gidTag = "GID"; - private static final String nameTag = "Name"; - private static final String descTag = "Desc"; - private static final String svcTag = "Svc"; - private static final String mcidTag = "MCID"; - private static final String paramTag = "Parm"; - private static final String[] fields = { nameTag, pidTag }; - - /** - * Creates instances of PeerAdvertisement. - **/ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - **/ - public String getAdvertisementType() { - return PeerAdvertisement.getAdvertisementType(); - } - - /** - * {@inheritDoc} - **/ - public Advertisement newInstance() { - return new PeerAdv(); - } - - /** - * {@inheritDoc} - **/ - public Advertisement newInstance(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - return new PeerAdv((XMLElement) root); - } - } - - /** - * Private constructor for new instances. Use the instantiator. - */ - private PeerAdv() {} - - /** - * Private constructor for xml serialized instances. Use the instantiator. - * - * @param doc The XML serialization of the advertisement. - */ - private PeerAdv(XMLElement doc) { - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - - // sanity check time! - if (null == getPeerID()) { - throw new IllegalArgumentException("Peer Advertisement did not contain a peer id."); - } - - if (null == getPeerGroupID()) { - throw new IllegalArgumentException("Peer Advertisement did not contain a peer group id."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - **/ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (elem.getName().equals(pidTag)) { - try { - URI pID = new URI(elem.getTextValue()); - - setPeerID((PeerID) IDFactory.fromURI(pID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerID ID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a peer id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals(gidTag)) { - try { - URI gID = new URI(elem.getTextValue()); - - setPeerGroupID((PeerGroupID) IDFactory.fromURI(gID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerGroupID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a group id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals(nameTag)) { - setName(elem.getTextValue()); - return true; - } - - if (elem.getName().equals(descTag)) { - setDesc(elem); - return true; - } - - if (elem.getName().equals(svcTag)) { - Enumeration elems = elem.getChildren(); - ModuleClassID classID = null; - Element param = null; - - while (elems.hasMoreElements()) { - XMLElement e = (XMLElement) elems.nextElement(); - - if (e.getName().equals(mcidTag)) { - try { - URI mcid = new URI(e.getTextValue()); - - classID = (ModuleClassID) IDFactory.fromURI(mcid); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Unusable ModuleClassID in advertisement: " + e.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a ModuleClassID: " + e.getTextValue()); - } - continue; - } - if (e.getName().equals(paramTag)) { - param = e; - } - } - if (classID != null && param != null) { - // Add this param to the table. putServiceParam() - // clones param into a standalone document automatically. - // (classID gets cloned too). - putServiceParam(classID, param); - } - return true; - } - - // element was not handled - return false; - } - - /** - * {@inheritDoc} - **/ - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - PeerID peerID = getPeerID(); - - if ((null == peerID) || ID.nullID.equals(peerID)) { - throw new IllegalStateException("Cannot generate Peer Advertisement with no Peer ID!"); - } - Element e = adv.createElement(pidTag, peerID.toString()); - - adv.appendChild(e); - - PeerGroupID groupID = getPeerGroupID(); - - if ((null == groupID) || ID.nullID.equals(groupID)) { - throw new IllegalStateException("Cannot generate Peer Advertisement with no group ID!"); - } else { - e = adv.createElement(gidTag, groupID.toString()); - adv.appendChild(e); - } - - // name is optional - if (getName() != null) { - e = adv.createElement(nameTag, getName()); - adv.appendChild(e); - } - - // desc is optional - StructuredDocument desc = getDesc(); - - if (desc != null) { - StructuredDocumentUtils.copyElements(adv, adv, desc); - } - - // service params are optional - // FIXME: this is inefficient - we force our base class to make - // a deep clone of the table. - Hashtable serviceParams = getServiceParams(); - Enumeration classIds = serviceParams.keys(); - - while (classIds.hasMoreElements()) { - ModuleClassID classId = (ModuleClassID) classIds.nextElement(); - - Element s = adv.createElement(svcTag); - - adv.appendChild(s); - - e = adv.createElement(mcidTag, classId.toString()); - s.appendChild(e); - - e = (Element) serviceParams.get(classId); - StructuredDocumentUtils.copyElements(adv, s, e, paramTag); - } - return adv; - } - - /** - * {@inheritDoc} - **/ - @Override - public String[] getIndexFields() { - return fields; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerGroupAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerGroupAdv.java deleted file mode 100644 index c700407d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerGroupAdv.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.TextElement; -import net.jxta.document.XMLElement; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.PeerGroupAdvertisement; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.logging.Level; -import java.util.logging.Logger; - - -public class PeerGroupAdv extends PeerGroupAdvertisement { - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(PeerGroupAdv.class.getName()); - - private static final String nameTag = "Name"; - private static final String gidTag = "GID"; - private static final String descTag = "Desc"; - private static final String msidTag = "MSID"; - private static final String svcTag = "Svc"; - private static final String mcidTag = "MCID"; - private static final String paramTag = "Parm"; - private static final String[] fields = { nameTag, gidTag, descTag, msidTag}; - - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - - public String getAdvertisementType() { - return PeerGroupAdv.getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new PeerGroupAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(net.jxta.document.Element root) { - return new PeerGroupAdv(root); - } - } - - /** - * Use the Instantiator method to construct Peer Group Advs. - */ - private PeerGroupAdv() {} - - /** - * Use the Instantiator method to construct Peer Group Advs. - * - * @param root the element - */ - private PeerGroupAdv(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - if (null == getPeerGroupID()) { - throw new IllegalArgumentException("Peer Group Advertisement did not contain a peer group id."); - } - - if (null == getModuleSpecID()) { - throw new IllegalArgumentException("Peer Group Advertisement did not contain a module spec id."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (elem.getName().equals(nameTag)) { - setName(elem.getTextValue()); - return true; - } - - if (elem.getName().equals(descTag)) { - setDesc(elem); - return true; - } - - if (elem.getName().equals(gidTag)) { - try { - URI grID = new URI(elem.getTextValue()); - - setPeerGroupID((PeerGroupID) IDFactory.fromURI(grID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad peer group ID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a group id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals(msidTag)) { - try { - URI specID = new URI(elem.getTextValue()); - - setModuleSpecID((ModuleSpecID) IDFactory.fromURI(specID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad msid in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a module spec id: " + elem.getTextValue()); - } - return true; - } - - if (elem.getName().equals(svcTag)) { - Enumeration elems = elem.getChildren(); - String classID = null; - Element param = null; - - while (elems.hasMoreElements()) { - TextElement e = (TextElement) elems.nextElement(); - - if (e.getName().equals(mcidTag)) { - classID = e.getTextValue(); - continue; - } - if (e.getName().equals(paramTag)) { - param = e; - } - } - if (classID != null && param != null) { - // Add this param to the table. putServiceParam() - // clones param into a standalone document automatically. - // (classID gets cloned too). - try { - putServiceParam(IDFactory.fromURI(new URI(classID)), param); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad mcid in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a module class id: " + elem.getTextValue()); - } - } - return true; - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - if (null == getPeerGroupID()) { - throw new IllegalStateException("Peer Group Advertisement did not contain a peer group id."); - } - - if (null == getModuleSpecID()) { - throw new IllegalStateException("Peer Group Advertisement did not contain a module spec id."); - } - - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - Element e; - - e = adv.createElement(gidTag, getPeerGroupID().toString()); - adv.appendChild(e); - - e = adv.createElement(msidTag, getModuleSpecID().toString()); - adv.appendChild(e); - - // name is optional - if (null != getName()) { - e = adv.createElement(nameTag, getName()); - adv.appendChild(e); - } - - // desc is optional - StructuredDocument desc = getDesc(); - - if (desc != null) { - StructuredDocumentUtils.copyElements(adv, adv, desc); - } - - // FIXME: this is inefficient - we force our base class to make - // a deep clone of the table. - Hashtable serviceParams = getServiceParams(); - Enumeration classIds = serviceParams.keys(); - - while (classIds.hasMoreElements()) { - ModuleClassID classId = (ModuleClassID) classIds.nextElement(); - - Element s = adv.createElement(svcTag); - - adv.appendChild(s); - - e = adv.createElement(mcidTag, classId.toString()); - s.appendChild(e); - - e = (Element) serviceParams.get(classId); - StructuredDocumentUtils.copyElements(adv, s, e, paramTag); - - } - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return fields; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerGroupConfigAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerGroupConfigAdv.java deleted file mode 100644 index c4684595..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerGroupConfigAdv.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Defines Peer Group Runtime Configuration parameters. - *

            - * This typically includes the peer group ID to use, the peer group name (if any) to use, and optional descriptive - * meta-data. - *

            - *

            
            - *   NetPeerGroupID=uuid-59313231343132314A484431544E504702
            - *   PeerGroupName=Network Infrastructure PeerGroup
            - *   PeerGroupDesc=Infrastructure Group Description
            - * 
            - */ -public final class PeerGroupConfigAdv extends ExtendableAdvertisement implements Cloneable { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(PeerGroupConfigAdv.class.getName()); - - /** - * The advertisement index fields. (currently none). - */ - private final static String[] INDEX_FIELDS = {}; - - /** - * The DOCTYPE - */ - private final static String advType = "jxta:PeerGroupConfigAdv"; - - private final static String PEERGROUP_ID_TAG = "PeerGroupID"; - private final static String PEERGROUP_NAME_TAG = "PeerGroupName"; - private final static String PEERGROUP_DESC_TAG = "PeerGroupDesc"; - - /** - * Instantiator for PeerGroupConfigAdv - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return advType; - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new PeerGroupConfigAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - return new PeerGroupConfigAdv((XMLElement) root); - } - } - - /** - * ID for the peer group. - */ - private ID gid = null; - - /** - * Informal, non-canonical name of this peer group - */ - private String name = null; - - /** - * Descriptive meta-data about this peer group. - */ - private Element description = null; - - /** - * Returns the identifying type of this Advertisement. - *

            - * Note: This is a static method. It cannot be used to determine - * the runtime type of an advertisement. ie. - *

            -     *      Advertisement adv = module.getSomeAdv();
            -     *      String advType = adv.getAdvertisementType();
            -     *  
            - *

            - * This is wrong and does not work the way you might expect. - * This call is not polymorphic and calls - * Advertisement.getAdvertisementType() no matter what the real type of the - * advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return advType; - } - - /** - * Use the Instantiator through the factory - */ - private PeerGroupConfigAdv() {} - - /** - * Use the Instantiator method to construct Peer Group Config Advs. - * - * @param doc the element - */ - private PeerGroupConfigAdv(XMLElement doc) { - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - - // Validate group id - if (null == getPeerGroupID()) { - throw new IllegalArgumentException("Peer Group Config Advertisement does not contain a peer group id."); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (PEERGROUP_ID_TAG.equals(elem.getName())) { - try { - URI grID = new URI(elem.getTextValue()); - - setPeerGroupID(IDFactory.fromURI(grID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Invalid peer group ID in advertisement: " + elem.getTextValue()); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Invalid group ID: " + elem.getTextValue()); - } - return true; - } - - if (PEERGROUP_NAME_TAG.equals(elem.getName())) { - setName(elem.getTextValue()); - return true; - } - - if (PEERGROUP_DESC_TAG.equals(elem.getName())) { - setDesc(elem); - return true; - } - - return false; - } - - /** - * Make a safe clone of this PeerGroupConfigAdv. - * - * @return Object A copy of this PeerGroupConfigAdv - */ - @Override - public PeerGroupConfigAdv clone() { - try { - PeerGroupConfigAdv clone = (PeerGroupConfigAdv) super.clone(); - - clone.setPeerGroupID(getPeerGroupID()); - clone.setName(getName()); - clone.setDesc(getDesc()); - - return clone; - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public ID getID() { - return ID.nullID; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - if (null == getPeerGroupID()) { - throw new IllegalStateException("Peer Group Config Advertisement does not contain a peer group id."); - } - - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - Element e = adv.createElement(PEERGROUP_ID_TAG, getPeerGroupID().toString()); - - adv.appendChild(e); - - // name is optional - if (null != getName()) { - e = adv.createElement(PEERGROUP_NAME_TAG, getName()); - adv.appendChild(e); - } - - // desc is optional - StructuredDocument desc = getDesc(); - - if (desc != null) { - StructuredDocumentUtils.copyElements(adv, adv, desc); - } - - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return INDEX_FIELDS; - } - - /** - * Returns the id of the peer group. - * - * @return ID the group id - */ - - public ID getPeerGroupID() { - return gid; - } - - /** - * Sets the id of the peer group. - * - * @param gid The id of this group. - */ - - public void setPeerGroupID(ID gid) { - this.gid = gid; - } - - /** - * Gets the name to use for the peer group. - * - * @return The name value - */ - public String getName() { - return name; - } - - /** - * Sets the name to use for the peer group. - * - * @param name The new name value - */ - public void setName(String name) { - this.name = name; - } - - /** - * returns the description - * - * @return String the description - */ - public String getDescription() { - if (description != null) { - return (String) description.getValue(); - } else { - return null; - } - } - - /** - * sets the description - * - * @param description the description - */ - public void setDescription(String description) { - - if (null != description) { - XMLDocument newdoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8 - , - PEERGROUP_DESC_TAG, description); - - setDesc(newdoc); - } else { - this.description = null; - } - } - - /** - * returns the description - * - * @return the description - */ - public XMLDocument getDesc() { - XMLDocument newDoc = null; - - if (description != null) { - newDoc = (XMLDocument) StructuredDocumentUtils.copyAsDocument(description); - } - return newDoc; - } - - /** - * Sets the description - * - * @param desc the description - */ - public void setDesc(XMLElement desc) { - - if (desc != null) { - this.description = StructuredDocumentUtils.copyAsDocument(desc); - } else { - this.description = null; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerInfoQueryMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerInfoQueryMsg.java deleted file mode 100644 index 1d292917..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerInfoQueryMsg.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.protocol.PeerInfoQueryMessage; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - - -/** - * This class implements {@link net.jxta.protocol.PeerInfoQueryMessage}. - *

            - *

            This message is part of the Peer PeerInfoService protocol - *

            - *

            - * <xs:element name="PeerInfoQueryMessage" type="jxta:PeerInfoQueryMessage"/>
            - * 

            - * <xs:complexType name="PeerInfoQueryMessage"> - * <xs:element name="sourcePid" type="xs:anyURI"/> - * <xs:element name="targetPid" type="xs:anyURI"/> - * <!-- if no present then the response is the general peerinfo --> - * <xs:element name="request" type="xs:anyType" minOccurs="0"/> - * </xs:complexType> - *

            - * - * @since JXTA 1.0 - */ -public class PeerInfoQueryMsg extends PeerInfoQueryMessage { - - public PeerInfoQueryMsg() { - super(); - } - - public PeerInfoQueryMsg(Element root) { - initialize(root); - } - - public void initialize(Element root) { - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports TextElement"); - } - - setSourcePid(null); - setTargetPid(null); - - TextElement doc = (TextElement) root; - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - TextElement element = (TextElement) elements.nextElement(); - String elementName = element.getName(); - - if (elementName.equals("sourcePid")) { - try { - URI peerid = new URI(element.getTextValue()); - ID id = IDFactory.fromURI(peerid); - - setSourcePid((PeerID) id); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad peerid ID in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Unusable ID in advertisement"); - } - continue; - } - - if (elementName.equals("targetPid")) { - try { - URI peerid = new URI(element.getTextValue()); - ID id = IDFactory.fromURI(peerid); - - setTargetPid((PeerID) id); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad peerid ID in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Unusable ID in advertisement"); - } - } else if (elementName.equals("request")) { - Enumeration elems = element.getChildren(); - - if (elems.hasMoreElements()) { - setRequest(StructuredDocumentUtils.copyAsDocument((Element) elems.nextElement())); - } - } - } - } - - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredTextDocument doc = (StructuredTextDocument) - StructuredDocumentFactory.newStructuredDocument(encodeAs, getMessageType()); - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - Element e = doc.createElement("sourcePid", getSourcePid().toString()); - - doc.appendChild(e); - - e = doc.createElement("targetPid", getTargetPid().toString()); - doc.appendChild(e); - - Element request = getRequest(); - - if (null != request) { - e = doc.createElement("request"); - doc.appendChild(e); - - StructuredDocumentUtils.copyElements(doc, e, request); - } - - return doc; - } - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerInfoResponseMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerInfoResponseMsg.java deleted file mode 100644 index 5a54cb38..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PeerInfoResponseMsg.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.protocol.PeerInfoResponseMessage; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - - -/** - * This class implements {@link net.jxta.protocol.PeerInfoResponseMessage}. - *

            - *

            This message is part of the Peer PeerInfoService protocol - *

            - *

            - * <xs:element name="PeerInfoResponse" type="jxta:PeerInfoResponse"/>
            - * 

            - * <xs:complexType name="PeerInfoResponse"> - * <xs:element name="sourcePid" type="xs:anyURI"/> - * <xs:element name="targetPid" type="xs:anyURI"/> - * <xs:element name="uptime" type="xs:unsignedLong" minOccurs="0"/> - * <xs:element name="timestamp" type="xs:unsignedLong" minOccurs="0"/> - * <xs:element name="response" type="xs:anyType" minOccurs="0"/> - * </xs:complexType> - *

            - * - * @since JXTA 1.0 - */ -public class PeerInfoResponseMsg extends PeerInfoResponseMessage { - - public PeerInfoResponseMsg() {} - - /** - * @param spid source PeerID - * @param tpid target PeerID - * @param uptime uotime in millis - * @param timestamp TimeStamp - * @deprecated Please use the individual setters - */ - @Deprecated - public PeerInfoResponseMsg(PeerID spid, PeerID tpid, long uptime, long timestamp) { - setSourcePid(spid); - setTargetPid(tpid); - setUptime(uptime); - setTimestamp(timestamp); - } - - public PeerInfoResponseMsg(Element root) { - initialize(root); - } - - private void initialize(Element root) { - - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports TextElement"); - } - - setSourcePid(null); - setTargetPid(null); - setUptime(0); - setTimestamp(0); - - TextElement doc = (TextElement) root; - - Enumeration elements; - - elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - TextElement element = (TextElement) elements.nextElement(); - String elementName = element.getName(); - - if (elementName.equals("sourcePid")) { - try { - URI peerid = new URI(element.getTextValue()); - ID id = IDFactory.fromURI(peerid); - - if (!(id instanceof PeerID)) { - throw new IllegalArgumentException("Bad ID in advertisement, not a PeerID"); - } - setSourcePid((PeerID) id); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad peerid ID in advertisement"); - } - continue; - } - - if (elementName.equals("targetPid")) { - try { - URI peerid = new URI(element.getTextValue()); - PeerID id = (PeerID) IDFactory.fromURI(peerid); - - setTargetPid(id); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad peerid ID in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Bad ID in advertisement, not a PeerID"); - } - } - - if (elementName.equals("uptime")) { - setUptime(Long.parseLong(element.getTextValue())); - continue; - } - - if (elementName.equals("timestamp")) { - setTimestamp(Long.parseLong(element.getTextValue())); - continue; - } - - if (elementName.equals("response")) { - Enumeration elems = element.getChildren(); - - if (elems.hasMoreElements()) { - setResponse(StructuredDocumentUtils.copyAsDocument((Element) elems.nextElement())); - } - } - - } - } - - @Override - public Document getDocument(MimeMediaType encodeAs) { - - StructuredTextDocument doc = (StructuredTextDocument) - StructuredDocumentFactory.newStructuredDocument(encodeAs, getMessageType()); - TextElement e; - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - e = doc.createElement("sourcePid", getSourcePid().toString()); - doc.appendChild(e); - - e = doc.createElement("targetPid", getTargetPid().toString()); - doc.appendChild(e); - - Element response = getResponse(); - - if (null != response) { - e = doc.createElement("response"); - doc.appendChild(e); - - StructuredDocumentUtils.copyElements(doc, e, response); - } - - e = doc.createElement("uptime", String.valueOf(getUptime())); - doc.appendChild(e); - - e = doc.createElement("timestamp", String.valueOf(getTimestamp())); - doc.appendChild(e); - - return doc; - } - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PipeAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PipeAdv.java deleted file mode 100644 index ca0916c9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PipeAdv.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.net.URI; -import java.util.Enumeration; -import java.net.URISyntaxException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.PipeAdvertisement; - - -/** - * This class implements the Pipe Advertisement according to the schema used by - * the standard Pipe Binding Protocol. (PBP) - * - *

            - * <xs:complexType name="PipeAdvertisement">
            - *   <xs:sequence>
            - *     <xs:element name="Id" type="jxta:JXTAID"/>
            - *     <xs:element name="Type" type="xs:string"/>
            - *     <xs:element name="Name" type="xs:string" minOccurs="0"/>
            - *     <xs:element name="Desc" type="xs:anyType" minOccurs="0"/>
            - *   </xs:sequence>
            - * </xs:complexType>
            - * 
            - * - * @see net.jxta.protocol.PipeAdvertisement - * @see net.jxta.pipe.PipeService - * @see JXTA Protocols Specification : Pipe Binding Protocol - */ -public class PipeAdv extends PipeAdvertisement { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(PipeAdv.class.getName()); - - /** - * Fields which will be returned by {@link #getIndexFields()} - **/ - private static final String[] INDEX_FIELDS = { PipeAdvertisement.NameTag, PipeAdvertisement.IdTag}; - - /** - * AvertisementFactory instantiator for our type. - */ - public final static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return PipeAdv.getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new PipeAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - return new PipeAdv((XMLElement) root); - } - } - - /** - * Private constructor for new instances. Use the instantiator. - */ - private PipeAdv() {} - - /** - * Private constructor for xml serialized instances. Use the instantiator. - * - * @param doc The XML serialization of the advertisement. - */ - private PipeAdv(XMLElement doc) { - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem); - } - } - } - - // Sanity Check!!! - if ((null == getPipeID()) || getPipeID().equals(ID.nullID)) { - throw new IllegalArgumentException("Bad pipe ID in advertisement"); - } - - if ((null == getType()) || (0 == getType().length())) { - throw new IllegalArgumentException("Bad pipe type in advertisement"); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (PipeAdvertisement.descTag.equals(elem.getName())) { - setDesc(elem); - return true; - } - - String value = elem.getTextValue(); - - if ((null == value) || (0 == value.trim().length())) { - return false; - } - - value = value.trim(); - - if (PipeAdvertisement.IdTag.equals(elem.getName())) { - try { - URI pipeID = new URI(value); - - setPipeID(IDFactory.fromURI(pipeID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad pipe ID in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("ID is not a pipe ID"); - } - return true; - } - - if (PipeAdvertisement.NameTag.equals(elem.getName())) { - setName(value); - return true; - } - - if (PipeAdvertisement.TypeTag.equals(elem.getName())) { - setType(value); - return true; - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - ID itsID = getPipeID(); - - if ((null == itsID) || itsID.equals(ID.nullID)) { - throw new IllegalStateException("Pipe has no assigned ID"); - } - - Element e = adv.createElement(PipeAdvertisement.IdTag, itsID.toString()); - - adv.appendChild(e); - - if ((null == getType()) || (0 == getType().length())) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Pipe type not set. Defaulting to " + PipeService.UnicastType + "." - + "\n This default is deprecated. Please set the pipe type in your code."); - } - - setType(PipeService.UnicastType); - // throw new IllegalArgumentException("Pipe type missing in advertisement"); - } - - e = adv.createElement(PipeAdvertisement.TypeTag, getType()); - adv.appendChild(e); - - // name is optional - if (getName() != null) { - e = adv.createElement(PipeAdvertisement.NameTag, getName()); - adv.appendChild(e); - } - - // desc is optional - StructuredDocument desc = getDesc(); - - if (desc != null) { - StructuredDocumentUtils.copyElements(adv, adv, desc); - } - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return INDEX_FIELDS; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PipeResolverMsg.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PipeResolverMsg.java deleted file mode 100644 index 10e82bfc..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PipeResolverMsg.java +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.pipe.PipeID; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeResolverMessage; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.IOException; -import java.io.StringReader; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.Set; - - -/** - * This class implements {@link net.jxta.protocol.PipeResolverMessage} by - * providing {@link #initialize(Element)} and {@link #getDocument(MimeMediaType)} - * implementations. - *

            - *

            It implements the PipeResolver message for the standard Pipe - * Binding Protocol (PBP) with the following schema: - *

            - *

            
            - * <xs:element name="jxta:PipeResolver" type="jxta:PipeResolver"/>
            - * 

            - * <xs:simpleType name="PipeResolverMsgType"> - * <xs:restriction base="xs:string"> - * <!-- QUERY --> - * <xs:enumeration value="Query"/> - * <!-- ANSWER --> - * <xs:enumeration value="Answer"/> - * </xs:restriction> - * </xs:simpleType> - *

            - * <xs:complexType name="PipeResolver"> - * <xs:sequence> - * <xs:element name="MsgType" type="jxta:PipeResolverMsgType"/> - * <xs:element name="PipeId" type="jxta:JXTAID"/> - * <xs:element name="Type" type="xs:string"/> - *

            - * <!-- used in the query --> - * <xs:element name="Cached" type="xs:boolean" default="true" minOccurs="0"/> - * <xs:element name="Peer" type="jxta:JXTAID" minOccurs="0" maxOccurs="unbounded"/> - *

            - * <!-- used in the answer --> - * <xs:element name="Found" minOccurs="0" type="xs:boolean"/> - * <!-- This should refer to a peer adv, but is instead a whole doc --> - * <xs:element name="PeerAdv" minOccurs="0" type="xs:string" /> - * </xs:sequence> - * </xs:complexType> - *

            - * - * @see net.jxta.pipe.PipeService - * @see net.jxta.impl.pipe.PipeServiceImpl - * @see JXTA Protocols Specification : Pipe Binding Protocol - */ -public class PipeResolverMsg extends PipeResolverMessage { - - /** - * Log4J Logger - */ - private final static transient Logger LOG = Logger.getLogger(PipeResolverMsg.class.getName()); - - private final static String MsgTypeTag = "MsgType"; - private final static String PipeIdTag = "PipeId"; - private final static String PipeTypeTag = "Type"; - private final static String PeerIdTag = "Peer"; - private final static String PeerAdvTag = "PeerAdv"; - private final static String FoundTag = "Found"; - - private final static String QueryMsgType = "Query"; - private final static String AnswerMsgType = "Answer"; - - public PipeResolverMsg() {} - - public PipeResolverMsg(Element root) { - initialize(root); - } - - private void initialize(Element root) { - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports TextElement"); - } - - TextElement doc = (TextElement) root; - - String docName = doc.getName(); - - if (!docName.equals(getMessageType())) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + docName); - } - - Enumeration each = doc.getChildren(); - - while (each.hasMoreElements()) { - TextElement elem = (TextElement) each.nextElement(); - - if (elem.getName().equals(MsgTypeTag)) { - String msgtype = elem.getTextValue(); - - if (msgtype.equals(QueryMsgType)) { - setMsgType(PipeResolverMessage.MessageType.QUERY); - } else if (msgtype.equals(AnswerMsgType)) { - setMsgType(PipeResolverMessage.MessageType.ANSWER); - } else { - throw new IllegalArgumentException("Unexpected Message Type in parsing."); - } - continue; - } - - if (elem.getName().equals(PipeIdTag)) { - try { - URI pipeID = new URI(elem.getTextValue()); - - setPipeID(IDFactory.fromURI(pipeID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad pipe ID in message"); - } - continue; - } - - if (elem.getName().equals(PipeTypeTag)) { - setPipeType(elem.getTextValue()); - continue; - } - - if (elem.getName().equals(PeerIdTag)) { - try { - URI peerID = new URI(elem.getTextValue()); - - addPeerID(IDFactory.fromURI(peerID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad peer ID in message"); - } - continue; - } - - if (elem.getName().equals(FoundTag)) { - setFound(Boolean.valueOf(elem.getTextValue())); - continue; - } - - // let's check whether the responder sent us a adv - if (elem.getName().equals(PeerAdvTag)) { - String peerAdv = elem.getTextValue(); - - try { - setInputPeerAdv( - (PeerAdvertisement) AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8 - , - new StringReader(peerAdv))); - } catch (IOException caught) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Malformed peer adv in message", caught); - } - throw new IllegalArgumentException("Malformed peer adv in message : " + caught.getMessage()); - } - } - - } - - // Begin validation - PipeResolverMessage.MessageType msgType = getMsgType(); - - if (null == msgType) { - throw new IllegalArgumentException("Message type was never set!"); - } - - ID pipeID = getPipeID(); - - if ((null == pipeID) || ID.nullID.equals(pipeID) || !(pipeID instanceof PipeID)) { - throw new IllegalArgumentException("Input Pipe ID not set or invalid"); - } - - if (null == getPipeType()) { - throw new IllegalArgumentException("Pipe type was never set!"); - } - - // Response extra checks - if (PipeResolverMessage.MessageType.ANSWER.equals(msgType)) { - if (getPeerIDs().isEmpty()) { - throw new IllegalArgumentException("An answer without responses is invalid"); - } - } - } - - /** - * Creates a document out of the message. - * - * @param encodeAs The document representation format requested. - * @return the message as a document. - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredTextDocument doc = (StructuredTextDocument) - StructuredDocumentFactory.newStructuredDocument(encodeAs, getMessageType()); - - if (doc instanceof Attributable) { - ((Attributable) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - PipeResolverMessage.MessageType msgType = getMsgType(); - - if (null == msgType) { - throw new IllegalStateException("Message type was never set!"); - } - - ID pipeID = getPipeID(); - - if ((null == pipeID) || ID.nullID.equals(pipeID) || !(pipeID instanceof PipeID)) { - throw new IllegalStateException("Pipe ID not set or invalid."); - } - - String pipeType = getPipeType(); - - if ((null == pipeType) || (0 == pipeType.trim().length())) { - throw new IllegalStateException("Pipe type was never set or is invalid."); - } - - Element element; - - if (PipeResolverMessage.MessageType.QUERY.equals(msgType)) { - element = doc.createElement(MsgTypeTag, QueryMsgType); - } else if (PipeResolverMessage.MessageType.ANSWER.equals(msgType)) { - element = doc.createElement(MsgTypeTag, AnswerMsgType); - } else { - throw new IllegalStateException("Unknown message type :" + msgType.toString()); - } - doc.appendChild(element); - - element = doc.createElement(PipeIdTag, pipeID.toString()); - doc.appendChild(element); - - if ((pipeType != null) && (0 != pipeType.length())) { - element = doc.createElement(PipeTypeTag, pipeType); - doc.appendChild(element); - } - - // Write the peer ids. - Set peers = getPeerIDs(); - - if (PipeResolverMessage.MessageType.ANSWER.equals(msgType) && peers.isEmpty()) { - throw new IllegalStateException("An ANSWER message must contain at least one peer as part of the response."); - } - - for (Object peer : peers) { - ID aPeer = (ID) peer; - - element = doc.createElement(PeerIdTag, aPeer.toString()); - doc.appendChild(element); - } - - if (PipeResolverMessage.MessageType.QUERY.equals(msgType)) {// nothing for now... - } else if (PipeResolverMessage.MessageType.ANSWER.equals(msgType)) { - element = doc.createElement(FoundTag, (isFound() ? Boolean.TRUE : Boolean.FALSE).toString()); - doc.appendChild(element); - - PeerAdvertisement peerAdv = getInputPeerAdv(); - - if (peerAdv != null) { - if (!peers.contains(peerAdv.getPeerID())) { - throw new IllegalStateException( - "Provided Peer Advertisement does not refer to one of the peers in the response list."); - } - - StructuredTextDocument asDoc = (StructuredTextDocument) peerAdv.getDocument(MimeMediaType.XMLUTF8); - - element = doc.createElement(PeerAdvTag, asDoc.toString()); - doc.appendChild(element); - } - } else { - throw new IllegalStateException("Unknown message type :" + msgType.toString()); - } - return doc; - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PlatformConfig.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PlatformConfig.java deleted file mode 100644 index 181d0fb6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/PlatformConfig.java +++ /dev/null @@ -1,441 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.protocol.ConfigParams; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Configuration container for the World Peer Group. For historical reasons the - * same configuration container and instance is also used for the Net Peer Group. - */ -public final class PlatformConfig extends GroupConfig implements Cloneable { - - private static final String advType = "jxta:PlatformConfig"; - - /** - * Instantiator for PlatformConfig - */ - public final static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return advType; - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new PlatformConfig(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(advType + " only supports XLMElement"); - } - - return new PlatformConfig((XMLElement) root); - } - } - - private static final Logger LOG = Logger.getLogger(PlatformConfig.class.getName()); - - private static final String PID_TAG = "PID"; - private static final String NAME_TAG = "Name"; - private static final String DESC_TAG = "Desc"; - - /** - * The id of this peer. - */ - private PeerID pid = null; - - /** - * The name of this peer. Not guaranteed to be unique in any way. May be - * empty or null. - */ - private String name = null; - - /** - * Descriptive meta-data about this peer. - */ - private Element description = null; - - /** - * Use the Instantiator through the factory - */ - PlatformConfig() {} - - /** - * Use the Instantiator through the factory - * - * @param doc the element - */ - PlatformConfig(XMLElement doc) { - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - } - - /** - * Make a safe clone of this PlatformConfig. - * - * @return Object an object of class PlatformConfig that is a deep-enough - * copy of this one. - */ - @Override - public PlatformConfig clone() { - PlatformConfig result = (PlatformConfig) super.clone(); - - result.setPeerID(getPeerID()); - result.setName(getName()); - result.setDesc(getDesc()); - - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object other) { - if(this == other) { - return true; - } - - if(other instanceof PlatformConfig) { - PlatformConfig likeMe = (PlatformConfig) other; - - boolean se = super.equals(likeMe); - - boolean ne = ((null == name) && (null == likeMe.name)) || ((null != name) && name.equals(likeMe.name)); - boolean ie = ((null == pid) && (null == likeMe.pid)) || ((null != pid) && pid.equals(likeMe.pid)); - boolean de = ((null == description) && (null == likeMe.description)) || ((null != description) && description.equals(likeMe.description)); - - return se && ne && ie && de; - } - - return false; - } - - /** - * returns the advertisement type - * - * @return string type - */ - public static String getAdvertisementType() { - return advType; - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * returns the name of the peer. - * - * @return String name of the peer. - */ - public String getName() { - return name; - } - - /** - * sets the name of the peer. - * - * @param name name of the peer. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the id of the peer. - * - * @return PeerID the peer id - */ - public PeerID getPeerID() { - return pid; - } - - /** - * Sets the peer ID to use for this peer. - * - * @param pid The peer ID to use for this peer. - */ - public void setPeerID(PeerID pid) { - this.pid = pid; - } - - /** - * Returns a unique ID for that peer X group intersection. This is for - * indexing purposes only. - */ - @Override - public ID getID() { - return pid; - } - - /** - * returns the description - * - * @return String the description - */ - public String getDescription() { - return (null == description) ? null : (String) description.getValue(); - } - - /** - * Sets the description - * - * @param description the description - */ - public void setDescription(String description) { - StructuredDocument newdoc = null; - - if (null != description) { - newdoc = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, DESC_TAG, description); - } - setDesc(newdoc); - } - - /** - * Returns the description - * - * @return the description - */ - public StructuredDocument getDesc() { - StructuredDocument newDoc = null; - - if (null != description) { - newDoc = StructuredDocumentUtils.copyAsDocument(description); - } - return newDoc; - } - - /** - * Sets the description - * - * @param desc the description - */ - public void setDesc(Element desc) { - if (null != desc) { - this.description = StructuredDocumentUtils.copyAsDocument(desc); - } else { - this.description = null; - } - } - - /** - * returns the debugLevel - * - * @deprecated The debug level is no longer set via this api. See - * {@link net.jxta.logging.Logging}. - * - * @return String the debugLevel - */ - @Deprecated - public String getDebugLevel() { - return "user default"; - } - - /** - * Sets the debugLevel - * - * @deprecated The debug level is no longer set via this api. See - * {@link net.jxta.logging.Logging}. - * - * @param debugLevel the debugLevel - */ - @Deprecated - public void setDebugLevel(String debugLevel) {} - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - String elName = elem.getName(); - - if (DESC_TAG.equals(elName)) { - setDesc(elem); - return true; - } - - String value = elem.getTextValue(); - - if (null == value) { - return false; - } - value = value.trim(); - - if (0 == value.length()) { - return false; - } - - if (PID_TAG.equals(elName)) { - try { - URI asURI = new URI(value); - PeerID pID = (PeerID) IDFactory.fromURI(asURI); - - setPeerID(pID); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Invalid PeerID in advertisement: " + value); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Invalid PeerID: " + value); - } - return true; - } - - if (NAME_TAG.equals(elName)) { - setName(value); - return true; - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean addDocumentElements(StructuredDocument adv) { - - Element e; - // peer ID is optional. (at least for the PlatformConfig it is) - PeerID peerID = getPeerID(); - - if ((null != peerID) && !ID.nullID.equals(peerID)) { - e = adv.createElement(PID_TAG, peerID.toString()); - adv.appendChild(e); - } - - // name is optional - if (getName() != null) { - e = adv.createElement(NAME_TAG, getName()); - adv.appendChild(e); - } - - // desc is optional - StructuredDocument desc = getDesc(); - - if (desc != null) { - StructuredDocumentUtils.copyElements(adv, adv, desc); - } - - super.addDocumentElements(adv); - - return true; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RdvAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RdvAdv.java deleted file mode 100644 index 05d12b56..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RdvAdv.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.net.URI; -import java.util.Enumeration; - -import java.net.URISyntaxException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.XMLElement; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - - -/** - * This class implements the RdvAdvertisement. - * - *

            - *   <xs:complexType name="RdvAdvertisement">
            - *     <xs:sequence>
            - *       <xs:element name="RdvGroupId" type="jxta:JXTAID"/>
            - *       <xs:element name="RdvPeerId" type="jxta:JXTAID"/>
            - *       <xs:element name="RdvServiceName" type="xs:string"/>
            - *       <xs:element name="Name" type="xs:string" minOccurs="0"/>
            - *       <!-- This should be a route -->
            - *       <xs:element name="RdvRoute" type="xs:anyType" minOccurs="0"/>
            - *     </xs:sequence>
            - *   </xs:complexType>
            - * 
            - **/ -public class RdvAdv extends RdvAdvertisement { - - /** - * Log4J Logger - **/ - private final static transient Logger LOG = Logger.getLogger(RdvAdv.class.getName()); - - private static final String[] INDEX_FIELDS = { PeerIDTag, ServiceNameTag, GroupIDTag }; - - /** - * Instantiator for our advertisement - **/ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - **/ - public String getAdvertisementType() { - return RdvAdv.getAdvertisementType(); - } - - /** - * {@inheritDoc} - **/ - public Advertisement newInstance() { - return new RdvAdv(); - } - - /** - * {@inheritDoc} - **/ - public Advertisement newInstance(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - return new RdvAdv((XMLElement) root); - } - } - - /** - * Private constructor for new instances. Use the instantiator. - */ - private RdvAdv() { - } - - /** - * Private constructor for xml serialized instances. Use the instantiator. - * - * @param doc The XML serialization of the advertisement. - */ - private RdvAdv(XMLElement doc) { - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - if (null == getGroupID()) { - throw new IllegalArgumentException("Missing peer group ID"); - } - - if (null == getPeerID()) { - throw new IllegalArgumentException("Missing peer ID"); - } - - if (null == getServiceName()) { - throw new IllegalArgumentException("Missing service name"); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - **/ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (elem.getName().equals(RdvAdvertisement.GroupIDTag)) { - try { - URI groupID = new URI(elem.getTextValue().trim()); - - setGroupID((PeerGroupID) IDFactory.fromURI(groupID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad group ID in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("ID is not a group ID"); - } - return true; - } - - if (elem.getName().equals(RdvAdvertisement.PeerIDTag)) { - try { - URI peerID = new URI(elem.getTextValue().trim()); - - setPeerID((PeerID) IDFactory.fromURI(peerID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad group ID in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("ID is not a group ID"); - } - return true; - } - - if (elem.getName().equals(RdvAdvertisement.ServiceNameTag)) { - setServiceName(elem.getTextValue()); - return true; - } - - if (elem.getName().equals(RdvAdvertisement.RouteTag)) { - for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements();) { - - XMLElement aXpt = (XMLElement) eachXpt.nextElement(); - - RouteAdvertisement xptAdv = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(aXpt); - - setRouteAdv(xptAdv); - } - return true; - } - - if (elem.getName().equals(RdvAdvertisement.NameTag)) { - setName(elem.getTextValue()); - return true; - } - - return false; - } - - /** - * {@inheritDoc} - **/ - @Override - public Document getDocument(MimeMediaType encodeAs) { - - // Sanity Check!!! - if (null == getGroupID()) { - throw new IllegalStateException("Missing peer group ID"); - } - - if (null == getPeerID()) { - throw new IllegalStateException("Missing peer ID"); - } - - if (null == getServiceName()) { - throw new IllegalStateException("Missing service name"); - } - - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - Element e = adv.createElement(RdvAdvertisement.GroupIDTag, getGroupID().toString()); - - adv.appendChild(e); - - e = adv.createElement(RdvAdvertisement.PeerIDTag, getPeerID().toString()); - adv.appendChild(e); - - e = adv.createElement(RdvAdvertisement.ServiceNameTag, getServiceName()); - adv.appendChild(e); - - String peerName = getName(); - - if (null != peerName) { - e = adv.createElement(RdvAdvertisement.NameTag, getName()); - adv.appendChild(e); - } - - if (getRouteAdv() != null) { - Element el = adv.createElement(RdvAdvertisement.RouteTag); - - adv.appendChild(el); - - StructuredTextDocument xptDoc = (StructuredTextDocument) - getRouteAdv().getDocument(encodeAs); - - StructuredDocumentUtils.copyElements(adv, el, xptDoc); - } - - return adv; - } - - /** - * {@inheritDoc} - **/ - @Override - public String[] getIndexFields() { - return INDEX_FIELDS; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RdvConfigAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RdvConfigAdv.java deleted file mode 100644 index b743e16b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RdvConfigAdv.java +++ /dev/null @@ -1,948 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.XMLElement; -import net.jxta.id.ID; -import net.jxta.logging.Logging; - -import java.net.URI; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Contains parameters for configuration of the Reference Implementation - * Rendezvous Service. - *

            - *

            
            - * <xs:complexType name="RdvConfig">
            - *   <xs:sequence>
            - *     <xs:element name="seeds" minOccurs="0" maxOccurs="1">
            - *       <xs:complexType>
            - *         <xs:sequence>
            - *           <xs:element name="addr" minOccurs="1" maxOccurs="unbounded">
            - *             <xs:complexType>
            - *               <xs:simpleContent>
            - *                 <xs:extension base="jxta:JXTAID">
            - *                   <xs:attribute name="seeding" type="xs:boolean" default="false"/>
            - *                 </xs:extension>
            - *               </xs:simpleContent>
            - *             </xs:complexType>
            - *           </xs:element>
            - *         </xs:sequence>
            - *         <xs:attribute name="useOnlySeeds" type="xs:boolean" default="false"/>
            - *         <xs:attribute name="connectDelay" type="xs:unsignedLong"/>
            - *       </xs:complexType>
            - *     </xs:element>
            - *   </xs:sequence>
            - *   <xs:attribute name="config" type="jxta:RdvConfiguration"/>
            - *   <xs:attribute name="maxTTL" type="xs:unsignedInt"/>
            - *   <xs:attribute name="autoRendezvousInterval" type="xs:unsignedInt"/>
            - *   <xs:attribute name="probeRelays" type="xs:boolean" default="true"/>
            - *   <xs:attribute name="maxClients" type="xs:unsignedInt"/>
            - *   <xs:attribute name="leaseDuration" type="xs:unsignedLong"/>
            - *   <xs:attribute name="leaseMargin" type="xs:unsignedLong"/>
            - *   <xs:attribute name="minHappyPeerView" type="xs:unsignedInt"/>
            - * </xs:complexType>
            - * 
            - * - * @since JXTA 2.2 - */ -public final class RdvConfigAdv extends ExtendableAdvertisement implements Cloneable { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(RdvConfigAdv.class.getName()); - - /** - * Instantiator for RdvConfigAdv - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return advType; - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new RdvConfigAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - return new RdvConfigAdv((XMLElement) root); - } - } - - /** - * Our DOCTYPE - */ - private static final String advType = "jxta:RdvConfig"; - - private static final String RDV_CONFIG_ATTR = "config"; - private static final String MAX_TTL_ATTR = "maxTTL"; - private static final String AUTO_RDV_INTERVAL_ATTR = "autoRendezvousInterval"; - private static final String PROBE_RELAYS_ATTR = "probeRelays"; - private static final String MAX_CLIENTS_ATTR = "maxClients"; - private static final String LEASE_DURATION_ATTR = "leaseDuration"; - private static final String LEASE_MARGIN_ATTR = "leaseMargin"; - private static final String MIN_HAPPY_PEERVIEW_ATTR = "minHappyPeerView"; - - private static final String SEEDS_RDV_ELEMENT = "seeds"; - private static final String USE_ONLY_SEEDS_ATTR = "useOnlySeeds"; - private static final String CONNECT_DELAY_ATTR = "connectDelay"; - - private static final String SEED_RDV_ADDR_ELEMENT = "addr"; - private static final String SEED_RDV_ADDR_SEEDING_ATTR = "seeding"; - private static final String ACL_URI = "acl"; - - // This one is deprecated. - private static final String PROPAGATE_RESPOND_ATTR = "propagateRespondProbability"; - - private static final String[] INDEXFIELDS = {}; - - /** - * Configuration for this peer. - */ - private RendezVousConfiguration configuration = RendezVousConfiguration.EDGE; - - /** - * The interval in relative milliseconds at which this peer will re-evaluate - * it's state as a rendezvous. If 0 (zero), the default, then - * the peer will remain in the state of isRendezvous. - */ - private long autoRendezvousCheckInterval = 0L; - - /** - * If true then rendezvous clients will probe relay servers for rendezvous. - */ - private boolean probeRelays = true; - - /** - * Max Clients - */ - private int maxClients = -1; - - /** - * Maximum TTL - */ - private int maximumTTL = -1; - - /** - * Lease Duration - */ - private long leaseDuration = 0L; - - /** - * Lease Margin - */ - private long leaseMargin = 0L; - - /** - * Minimum desirable peerview size. - */ - private int minHappyPeerView = -1; - - /** - * If true then this peer will use only seed rendezvous when configured as - * an edge peer. - */ - private boolean useOnlySeeds = false; - - /** - * The interval in relative milliseconds before which this peer will - * attempt to contact the the seed peers. - */ - private long seedRendezvousConnectDelay = 0L; - - /** - * The set of seed rendezvous. - */ - private final Set seedRendezvous = new HashSet(); - - /** - * The set of seeding resources. - */ - private final Set seedingURIs = new HashSet(); - - /** - * Access control URI - */ - private URI aclURI = null; - - /** - * Possible Rendezvous configurations. - */ - public enum RendezVousConfiguration { - - /** - * Connectionless - */ - AD_HOC, - - /** - * Edge peer - */ - EDGE, - - /** - * Rendezvous peer - */ - RENDEZVOUS - } - - /** - * Returns the identifying type of this Advertisement. - *

            - *

            Note: This is a static method. It cannot be used to determine - * the runtime type of an advertisement. ie. - *

            -     *      Advertisement adv = module.getSomeAdv();
            -     *      String advType = adv.getAdvertisementType();
            -     *  
            - *

            - *

            This is wrong and does not work the way you might expect. - * This call is not polymorphic and calls - * Advertisement.getAdvertisementType() no matter what the real type of the - * advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return advType; - } - - /** - * Private constructor for new instances. Use the instantiator. - */ - private RdvConfigAdv() {} - - /** - * Private constructor for xml serialized instances. Use the instantiator. - * - * @param doc The XML serialization of the advertisement. - */ - private RdvConfigAdv(XMLElement doc) { - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration eachAttr = doc.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute aRdvAttr = (Attribute) eachAttr.nextElement(); - - if (super.handleAttribute(aRdvAttr)) {// nothing to do - } else if (RDV_CONFIG_ATTR.equals(aRdvAttr.getName())) { - String config = aRdvAttr.getValue().trim(); - - if ("adhoc".equals(config)) { - configuration = RendezVousConfiguration.AD_HOC; - } else if ("client".equals(config)) { - configuration = RendezVousConfiguration.EDGE; - } else if ("rendezvous".equals(config)) { - configuration = RendezVousConfiguration.RENDEZVOUS; - } else { - throw new IllegalArgumentException("Unrecognized Rendezvous configuration :" + config); - } - } else if (MAX_TTL_ATTR.equals(aRdvAttr.getName())) { - maximumTTL = Integer.parseInt(aRdvAttr.getValue().trim()); - } else if (AUTO_RDV_INTERVAL_ATTR.equals(aRdvAttr.getName())) { - autoRendezvousCheckInterval = Long.parseLong(aRdvAttr.getValue().trim()); - } else if (PROBE_RELAYS_ATTR.equals(aRdvAttr.getName())) { - probeRelays = Boolean.valueOf(aRdvAttr.getValue().trim()); - } else if (MAX_CLIENTS_ATTR.equals(aRdvAttr.getName())) { - maxClients = Integer.parseInt(aRdvAttr.getValue().trim()); - } else if (LEASE_DURATION_ATTR.equals(aRdvAttr.getName())) { - leaseDuration = Long.parseLong(aRdvAttr.getValue().trim()); - } else if (LEASE_MARGIN_ATTR.equals(aRdvAttr.getName())) { - leaseMargin = Long.parseLong(aRdvAttr.getValue().trim()); - } else if (MIN_HAPPY_PEERVIEW_ATTR.equals(aRdvAttr.getName())) { - minHappyPeerView = Integer.parseInt(aRdvAttr.getValue().trim()); - } else if (PROPAGATE_RESPOND_ATTR.equals(aRdvAttr.getName())) {// Ignored; deprecated. - } else if ("Flags".equals(aRdvAttr.getName())) { // deprecated - boolean onlySeeds = (aRdvAttr.getValue().indexOf("UseOnlySeeds") != -1); - - setUseOnlySeeds(onlySeeds); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + aRdvAttr.getName()); - } - } - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - - if ((maximumTTL != -1) && (maximumTTL < 0)) { - throw new IllegalArgumentException("Maximum TTL must be >= 0"); - } - - if (autoRendezvousCheckInterval < 0) { - throw new IllegalArgumentException("Auto Rendezvous Check Interval must be >= 0"); - } - - if (seedRendezvousConnectDelay < 0) { - throw new IllegalArgumentException("Seed Rendezvous Connect Delay must be >= 0"); - } - - if ((-1 != minHappyPeerView) && (minHappyPeerView <= 0)) { - throw new IllegalArgumentException("Min Happy Peer View must be > 0"); - } - - if ((seedingURIs.isEmpty() && seedRendezvous.isEmpty() && useOnlySeeds) && (configuration == RendezVousConfiguration.EDGE)) { - throw new IllegalArgumentException("Must specify rendezvous if 'useOnlySeeds' is enabled and configured as client"); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public ID getID() { - return ID.nullID; - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (SEEDS_RDV_ELEMENT.equals(elem.getName())) { - - Enumeration eachSeedElem = elem.getChildren(); - - while (eachSeedElem.hasMoreElements()) { - XMLElement aSeedElem = (XMLElement) eachSeedElem.nextElement(); - - if (SEED_RDV_ADDR_ELEMENT.equals(aSeedElem.getName())) { - String endpAddrString = aSeedElem.getTextValue(); - - if (null != endpAddrString) { - URI endpAddr = URI.create(endpAddrString.trim()); - - Attribute seedingAttr = aSeedElem.getAttribute(SEED_RDV_ADDR_SEEDING_ATTR); - - if ((null != seedingAttr) && Boolean.valueOf(seedingAttr.getValue().trim())) { - seedingURIs.add(endpAddr); - } else { - seedRendezvous.add(endpAddr); - } - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Element: " + aSeedElem.getName()); - } - } - } - - Enumeration eachAttr = elem.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute aSeedAttr = (Attribute) eachAttr.nextElement(); - - if (USE_ONLY_SEEDS_ATTR.equals(aSeedAttr.getName())) { - useOnlySeeds = Boolean.valueOf(aSeedAttr.getValue().trim()); - } else if (CONNECT_DELAY_ATTR.equals(aSeedAttr.getName())) { - seedRendezvousConnectDelay = Long.parseLong(aSeedAttr.getValue().trim()); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + aSeedAttr.getName()); - } - } - } - - return true; - } else if (ACL_URI.equals(elem.getName())) { - String addrElement = elem.getTextValue(); - - if (null != addrElement) { - aclURI = URI.create(addrElement.trim()); - } - - return true; - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - if (!(adv instanceof Attributable)) { - throw new IllegalStateException("Only Attributable documents are supported."); - } - - Attributable attrDoc = (Attributable) adv; - - if (RendezVousConfiguration.AD_HOC == configuration) { - attrDoc.addAttribute(RDV_CONFIG_ATTR, "adhoc"); - } else if (RendezVousConfiguration.EDGE == configuration) { - attrDoc.addAttribute(RDV_CONFIG_ATTR, "client"); - } else if (RendezVousConfiguration.RENDEZVOUS == configuration) { - attrDoc.addAttribute(RDV_CONFIG_ATTR, "rendezvous"); - } - - if (maximumTTL != -1) { - if (maximumTTL < 0) { - throw new IllegalStateException("Maximum TTL must be >= 0"); - } - - attrDoc.addAttribute(MAX_TTL_ATTR, Integer.toString(maximumTTL)); - } - - if ((seedingURIs.isEmpty() && seedRendezvous.isEmpty() && useOnlySeeds) && (configuration == RendezVousConfiguration.EDGE)) { - throw new IllegalStateException("Must specify rendezvous if 'useOnlySeeds' is enabled and configured as client"); - } - - if (0 != autoRendezvousCheckInterval) { - if (autoRendezvousCheckInterval < 0) { - throw new IllegalStateException("Auto Rendezvous Check Interval must be >= 0"); - } - - attrDoc.addAttribute(AUTO_RDV_INTERVAL_ATTR, Long.toString(autoRendezvousCheckInterval)); - } - - if (!probeRelays) { - attrDoc.addAttribute(PROBE_RELAYS_ATTR, Boolean.toString(probeRelays)); - } - - if (-1 != maxClients) { - if (maxClients < 0) { - throw new IllegalStateException("Max Clients must be >= 0"); - } - - attrDoc.addAttribute(MAX_CLIENTS_ATTR, Integer.toString(maxClients)); - } - - if (0 != leaseDuration) { - if (leaseDuration < 0) { - throw new IllegalStateException("Lease Duration must be >= 0"); - } - - attrDoc.addAttribute(LEASE_DURATION_ATTR, Long.toString(leaseDuration)); - } - - if (0 != leaseMargin) { - if (leaseMargin < 0) { - throw new IllegalStateException("Lease Margin must be >= 0"); - } - - attrDoc.addAttribute(LEASE_MARGIN_ATTR, Long.toString(leaseMargin)); - } - - if (-1 != minHappyPeerView) { - if (minHappyPeerView < 0) { - throw new IllegalStateException("Min Happy Peer View must be > 0"); - } - - attrDoc.addAttribute(MIN_HAPPY_PEERVIEW_ATTR, Integer.toString(minHappyPeerView)); - } - - if (!seedRendezvous.isEmpty() || !seedingURIs.isEmpty()) { - Element seedsElem = adv.createElement(SEEDS_RDV_ELEMENT); - - adv.appendChild(seedsElem); - - Attributable attrSeeds = (Attributable) seedsElem; - - if (useOnlySeeds) { - attrSeeds.addAttribute(USE_ONLY_SEEDS_ATTR, Boolean.toString(useOnlySeeds)); - } - - if (0 != seedRendezvousConnectDelay) { - if (seedRendezvousConnectDelay < 0) { - throw new IllegalStateException("Seed Rendezvous Connect Delay must be >= 0"); - } - - attrSeeds.addAttribute(CONNECT_DELAY_ATTR, Long.toString(seedRendezvousConnectDelay)); - } - - for (URI seedRendezvou : seedRendezvous) { - Element aSeed = adv.createElement(SEED_RDV_ADDR_ELEMENT, seedRendezvou.toString()); - - seedsElem.appendChild(aSeed); - } - - for (URI seedingURI : seedingURIs) { - Element aSeed = adv.createElement(SEED_RDV_ADDR_ELEMENT, seedingURI.toString()); - - seedsElem.appendChild(aSeed); - - Attributable seedAttr = (Attributable) aSeed; - - seedAttr.addAttribute(SEED_RDV_ADDR_SEEDING_ATTR, Boolean.TRUE.toString()); - } - if (aclURI != null) { - Element acl = adv.createElement(ACL_URI, aclURI.toString()); - - adv.appendChild(acl); - } - } - - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return INDEXFIELDS; - } - - /** - * True if this peer is to default to act as a rendezvous. - * - * @return True if this peer is to be a rendezvous - */ - public RendezVousConfiguration getConfiguration() { - return configuration; - } - - /** - * Set the default rendezvous state of this peer. - * - * @param newstate if true then this peer should default to acting as a - * rendezvous. - */ - public void setConfiguration(RendezVousConfiguration newstate) { - configuration = newstate; - } - - /** - * The interval in relative milliseconds at which this peer will re-evaluate - * it's state as a rendezvous. If 0 (zero), the default, then - * the peer will remain in the state of isRendezvous. - * - * @return The interval in relative milliseconds at which this peer will re-evaluate - * it's state as a rendezvous. If 0 (zero), the default, then - * the peer will remain in the state of isRendezvous. - */ - public long getAutoRendezvousCheckInterval() { - return autoRendezvousCheckInterval; - } - - /** - * Sets the interval in relative milliseconds at which this peer will re-evaluate - * it's state as a rendezvous. If 0 (zero), the default, then - * the peer will remain in the state of isRendezvous. - * - * @param newvalue The interval in relative milliseconds at which this peer - * will re-evaluate it's state as a rendezvous. If 0 (zero), - * the default, then the peer will remain in the state of - * isRendezvous. - */ - public void setAutoRendezvousCheckInterval(long newvalue) { - if (newvalue < 0) { - throw new IllegalArgumentException("Auto Rendezvous Check Interval must be >= 0"); - } - - autoRendezvousCheckInterval = newvalue; - } - - /** - * If true then rendezvous clients will probe relay servers for rendezvous. - * - * @return If true then rendezvous clients will probe relay servers for rendezvous. - */ - public boolean getProbeRelays() { - return probeRelays; - } - - /** - * Set whether rendezvous clients will probe relay servers for rendezvous. - * - * @param doProbe If true then rendezvous clients will probe relay servers for rendezvous. - */ - public void setProbeRelays(boolean doProbe) { - probeRelays = doProbe; - } - - public URI[] getSeedRendezvous() { - return seedRendezvous.toArray(new URI[seedRendezvous.size()]); - } - - public void addSeedRendezvous(URI addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - seedRendezvous.add(addr); - } - - public void addSeedRendezvous(String addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - seedRendezvous.add(URI.create(addr)); - } - - public boolean removeSeedRendezvous(URI addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - return seedRendezvous.remove(addr); - } - - public void clearSeedRendezvous() { - seedRendezvous.clear(); - } - - public URI[] getSeedingURIs() { - return seedingURIs.toArray(new URI[seedingURIs.size()]); - } - - public void addSeedingURI(URI addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - seedingURIs.add(addr); - } - - public void addSeedingURI(String addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - seedingURIs.add(URI.create(addr)); - } - - public boolean removeSeedingURI(URI addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - return seedingURIs.remove(addr); - } - - public void clearSeedingURIs() { - seedingURIs.clear(); - } - - /** - * If true then this peer will use only seed rendezvous when configured as - * an edge peer. - * - * @return If true then this peer will use only seed rendezvous when - * configured as an edge peer. - */ - public boolean getUseOnlySeeds() { - return useOnlySeeds; - } - - /** - * Set whether this peer will use only seed rendezvous when configured as - * an edge peer. - * - * @param onlySeeds If true then this peer will use only seed rendezvous - * when configured as an edge peer. - */ - public void setUseOnlySeeds(boolean onlySeeds) { - useOnlySeeds = onlySeeds; - } - - /** - * The interval in relative milliseconds before which this peer will - * attempt to contact the the seed peers. - * - * @return The interval in relative milliseconds before which this peer will - * attempt to contact the the seed peers. - */ - public long getSeedRendezvousConnectDelay() { - return seedRendezvousConnectDelay; - } - - /** - * Sets the interval in relative milliseconds before which this peer will - * attempt to contact the the seed peers. - * - * @param newvalue The interval in relative milliseconds before which this peer will - * attempt to contact the the seed peers or - * -1 for the default value. - */ - public void setSeedRendezvousConnectDelay(long newvalue) { - if ((-1 != newvalue) && (newvalue < 0)) { - throw new IllegalArgumentException("Seed Rendezvous Connect Delay must be >= 0"); - } - - seedRendezvousConnectDelay = newvalue; - } - - /** - * The interval in relative milliseconds of leases offered by rendezvous - * peers. - * - * @return The interval in relative milliseconds of leases offered by rendezvous - * peers. - */ - public long getLeaseDuration() { - return leaseDuration; - } - - /** - * Sets interval in relative milliseconds of leases to be offered by rendezvous - * peers. - * - * @param newvalue The interval in relative milliseconds of leases to be offered by rendezvous - * peers or -1 for the default value. - */ - public void setLeaseDuration(long newvalue) { - if ((-1 != newvalue) && (newvalue < 0)) { - throw new IllegalArgumentException("Lease Duration must be >= 0"); - } - - leaseDuration = newvalue; - } - - /** - * The interval in relative milliseconds of leases offered by rendezvous - * peers. - * - * @return The interval in relative milliseconds of leases offered by rendezvous - * peers. - */ - public long getLeaseMargin() { - return leaseMargin; - } - - /** - * Sets interval in relative milliseconds of leases to be offered by rendezvous - * peers. - * - * @param newvalue The interval in relative milliseconds of leases to be offered by rendezvous - * peers or - * -1 for the default value. - */ - public void setLeaseMargin(long newvalue) { - if ((-1 != newvalue) && (newvalue < 0)) { - throw new IllegalArgumentException("Lease Margin must be >= 0"); - } - - leaseMargin = newvalue; - } - - /** - * Return the maximum number of clients. - * - * @return The maximum number of clients. - */ - public int getMaxClients() { - return maxClients; - } - - /** - * Sets he maximum number of clients. - * - * @param newvalue The maximum number of clients or - * -1 for the default value. - */ - public void setMaxClients(int newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Max Clients must be > 0"); - } - - maxClients = newvalue; - } - - /** - * Returns the maximum TTL for messages propagated by this peer or - * -1 for the default value. - * - * @return the maximum TTL for messages propagated by this peer or - * -1 for the default value. - */ - public int getMaxTTL() { - return maximumTTL; - } - - /** - * Sets the maximum TTL for messages propagated by this peer. - * - * @param newvalue the maximum TTL for messages propagated by this peer or - * -1 for the default value. - */ - public void setMaxTTL(int newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Max TTL must be >= 0"); - } - - maximumTTL = newvalue; - } - - /** - * Returns the minimum peerview size which the rendezvous service will - * find sufficient. - * - * @return the minimum peerview size. - */ - public int getMinHappyPeerView() { - return minHappyPeerView; - } - - /** - * Sets the minimum peerview size which the rendezvous service will find - * sufficient. If the peerview size is below that threshold, the peerview - * will more aggressively try to discover additional members. If permitted, - * the local peer may eventually decide to become a rendezvous in order for - * the peerview to reach that size. - * - * @param newvalue the minimum peerview size, which must be > 0 or - * -1 for the default value. - */ - public void setMinHappyPeerView(int newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Min Happy Peer View size must be > 0"); - } - minHappyPeerView = newvalue; - } - - /** - * Return ACL URI if set - * - * @return ACL URI if set, null otherwise - */ - public URI getAclUri() { - return aclURI; - } - - /** - * Sets ACL URI - * - * @param uri URI if set, null otherwise - */ - public void setAclUri(URI uri) { - aclURI = uri; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RelayConfigAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RelayConfigAdv.java deleted file mode 100644 index 8707da7f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RelayConfigAdv.java +++ /dev/null @@ -1,997 +0,0 @@ -/* - * Copyright (c) 2004-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.id.ID; -import net.jxta.impl.util.TimeUtils; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.net.URI; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; - - -/** - * Contains parameters for configuration of the Reference Implemenation - * Relay Service. - *

            - *

            
            - * 

            - *

            - */ -public final class RelayConfigAdv extends ExtendableAdvertisement implements Cloneable { - - /** - * Log4J Logger - */ - private static final Logger LOG = Logger.getLogger(RelayConfigAdv.class.getName()); - - /** - * Our DOCTYPE - */ - private static final String advType = "jxta:RelayConfig"; - - private static final String RELAY_CLIENT_ATTR = "client"; - private static final String RELAY_SERVER_ATTR = "server"; - - private static final String RELAY_CLIENT_ELEMENT = "client"; - private static final String RELAY_CLIENT_SERVERS_ATTR = "maxRelays"; - private static final String RELAY_CLIENT_LEASE_ATTR = "maxLease"; - private static final String RELAY_CLIENT_POLL_ATTR = "messengerPollInterval"; - - private static final String RELAY_CLIENT_SEEDS_ELEMENT = "seeds"; - private static final String USE_ONLY_SEEDS_ATTR = "useOnlySeeds"; - - private static final String SEED_RELAY_ADDR_ELEMENT = "addr"; - private static final String SEED_RELAY_ADDR_SEEDING_ATTR = "seeding"; - - private static final String RELAY_SERVER_ELEMENT = "server"; - private static final String RELAY_SERVER_CLIENTS_ATTR = "maxClients"; - private static final String RELAY_SERVER_QUEUE_ATTR = "clientQueue"; - private static final String RELAY_SERVER_LEASE_ATTR = "leaseDuration"; - private static final String RELAY_SERVER_STALL_ATTR = "stallTimeout"; - private static final String RELAY_SERVER_ANNOUNCE_ATTR = "announceInterval"; - private static final String ACL_URI = "acl"; - - private static final String[] fields = {}; - - /** - * Are we configured as a relay client? - */ - private boolean clientEnabled = false; - - /** - * Max Relays - */ - private int maxRelays = -1; - - /** - * Max clients lease in relative milliseconds. - */ - private long maxClientLeaseDuration = -1; - - /** - * Messenger poll interval in relative milliseconds. - */ - private long messengerPollInterval = -1; - - /** - * Use only seeded relays. - */ - private boolean useOnlySeeds = false; - - /** - * Seed Relays - *

            - *

              - *
            • Elements are {@link net.jxta.endpoint.EndpointAddress}
            • - *
            - */ - private Set seedRelays = new HashSet(); - - /** - * The list of seeding resources. - *

            - *

              - *
            • The values are {@link java.net.URI}.
            • - *
            - */ - private Set seedingURIs = new HashSet(); - - /** - * Are we configured as a relay server? - */ - private boolean serverEnabled = false; - - /** - * Max Clients - */ - private int maxClients = -1; - - /** - */ - private int maxClientMessageQueue = -1; - - /** - * Max Lease offered by server in relative milliseconds. - */ - private long maxServerLeaseDuration = -1; - - /** - * Stall timeout in relative milliseconds. - */ - private long stallTimeout = -1; - - /** - * Announce interval in relative milliseconds. - */ - private long announceInterval = -1; - - /** - * Access control URI - */ - private URI aclURI = null; - - /** - * Instantiator for RelayConfigAdv - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return advType; - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new RelayConfigAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - return new RelayConfigAdv(root); - } - } - - /** - * Returns the identifying type of this Advertisement. - *

            - *

            Note: This is a static method. It cannot be used to determine - * the runtime type of an advertisment. ie. - *

            -     *      Advertisement adv = module.getSomeAdv();
            -     *      String advType = adv.getAdvertisementType();
            -     *  
            - *

            - *

            This is wrong and does not work the way you might expect. - * This call is not polymorphic and calls - * Advertiement.getAdvertisementType() no matter what the real type of the - * advertisment. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return advType; - } - - private RelayConfigAdv() {} - - private RelayConfigAdv(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration eachAttr = doc.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute aRelayAttr = (Attribute) eachAttr.nextElement(); - - if (super.handleAttribute(aRelayAttr)) { - // nothing to do - ; - } else if (RELAY_CLIENT_ATTR.equals(aRelayAttr.getName())) { - clientEnabled = Boolean.valueOf(aRelayAttr.getValue().trim()); - } else if (RELAY_SERVER_ATTR.equals(aRelayAttr.getName())) { - serverEnabled = Boolean.valueOf(aRelayAttr.getValue().trim()); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + aRelayAttr.getName()); - } - } - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - if ((-1 != maxRelays) && (maxRelays <= 0)) { - throw new IllegalArgumentException("Max relays must not be negative or zero."); - } - - if ((-1 != maxClientLeaseDuration) && (maxClientLeaseDuration <= 0)) { - throw new IllegalArgumentException("Max lease duration must not be negative or zero."); - } - - if ((-1 != messengerPollInterval) && (messengerPollInterval <= 0)) { - throw new IllegalArgumentException("Messenger poll interval must not be negative or zero."); - } - - if (useOnlySeeds && clientEnabled && seedRelays.isEmpty() && seedingURIs.isEmpty()) { - throw new IllegalArgumentException("Cannot specify 'useOnlySeeds' and no seed relays"); - } - - if ((-1 != maxClients) && (maxClients <= 0)) { - throw new IllegalArgumentException("Max clients must not be negative or zero."); - } - - if ((-1 != maxClientMessageQueue) && (maxClientMessageQueue <= 0)) { - throw new IllegalArgumentException("Max client queue must not be negative or zero."); - } - - if ((-1 != maxServerLeaseDuration) && (maxServerLeaseDuration <= 0)) { - throw new IllegalArgumentException("Max lease duration must not be negative or zero."); - } - - if ((-1 != stallTimeout) && (stallTimeout <= 0)) { - throw new IllegalArgumentException("Client stall timeout duration must not be negative or zero."); - } - - if ((-1 != announceInterval) && (announceInterval <= 0)) { - throw new IllegalArgumentException("Announce interval must not be negative or zero."); - } - } - - /** - * {@inheritDoc} - */ - @Override - public RelayConfigAdv clone() { - - RelayConfigAdv result; - - try { - result = (RelayConfigAdv) super.clone(); - } catch (CloneNotSupportedException impossible) { - throw new Error("Object.clone() threw CloneNotSupportedException", impossible); - } - - result.setAnnounceInterval(getAnnounceInterval()); - result.setClientEnabled(isClientEnabled()); - result.setClientLeaseDuration(getClientLeaseDuration()); - result.setClientMessageQueueSize(getClientMessageQueueSize()); - result.setMaxClients(getMaxClients()); - result.setMaxRelays(getMaxRelays()); - result.setMessengerPollInterval(getMessengerPollInterval()); - result.setServerEnabled(isServerEnabled()); - result.setServerLeaseDuration(getServerLeaseDuration()); - result.setStallTimeout(getStallTimeout()); - result.setUseOnlySeeds(getUseOnlySeeds()); - - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public final String getBaseAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public ID getID() { - return ID.nullID; - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (RELAY_CLIENT_ELEMENT.equals(elem.getName())) { - Enumeration eachAttr = elem.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute aRelayAttr = (Attribute) eachAttr.nextElement(); - - if (RELAY_CLIENT_SERVERS_ATTR.equals(aRelayAttr.getName())) { - maxRelays = Integer.parseInt(aRelayAttr.getValue().trim()); - } else if (RELAY_CLIENT_LEASE_ATTR.equals(aRelayAttr.getName())) { - maxClientLeaseDuration = Long.parseLong(aRelayAttr.getValue().trim()); - } else if (RELAY_CLIENT_POLL_ATTR.equals(aRelayAttr.getName())) { - messengerPollInterval = Long.parseLong(aRelayAttr.getValue().trim()); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + aRelayAttr.getName()); - } - } - } - - Enumeration elements = elem.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement seedsElem = (XMLElement) elements.nextElement(); - - if (RELAY_CLIENT_SEEDS_ELEMENT.equals(seedsElem.getName())) { - Enumeration eachSeedsAttr = seedsElem.getAttributes(); - - while (eachSeedsAttr.hasMoreElements()) { - Attribute aRelayAttr = (Attribute) eachSeedsAttr.nextElement(); - - if (USE_ONLY_SEEDS_ATTR.equals(aRelayAttr.getName())) { - useOnlySeeds = Boolean.valueOf(aRelayAttr.getValue().trim()); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + aRelayAttr.getName()); - } - } - } - - Enumeration addrElements = seedsElem.getChildren(); - - while (addrElements.hasMoreElements()) { - XMLElement addrElem = (XMLElement) addrElements.nextElement(); - - if (SEED_RELAY_ADDR_ELEMENT.equals(addrElem.getName())) { - String endpAddrString = addrElem.getTextValue(); - - if (null != endpAddrString) { - URI endpURI = URI.create(endpAddrString.trim()); - - Attribute seedingAttr = addrElem.getAttribute(SEED_RELAY_ADDR_SEEDING_ATTR); - - if ((null != seedingAttr) && Boolean.valueOf(seedingAttr.getValue().trim())) { - seedingURIs.add(endpURI); - } else { - seedRelays.add(new EndpointAddress(endpURI)); - } - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Element: " + elem.toString()); - } - } - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Element: " + elem.toString()); - } - } - } - - return true; - } else if (RELAY_SERVER_ELEMENT.equals(elem.getName())) { - Enumeration eachAttr = elem.getAttributes(); - - while (eachAttr.hasMoreElements()) { - Attribute aRelayAttr = (Attribute) eachAttr.nextElement(); - - if (RELAY_SERVER_CLIENTS_ATTR.equals(aRelayAttr.getName())) { - maxClients = Integer.parseInt(aRelayAttr.getValue().trim()); - } else if (RELAY_SERVER_QUEUE_ATTR.equals(aRelayAttr.getName())) { - maxClientMessageQueue = Integer.parseInt(aRelayAttr.getValue().trim()); - } else if (RELAY_SERVER_LEASE_ATTR.equals(aRelayAttr.getName())) { - maxServerLeaseDuration = Long.parseLong(aRelayAttr.getValue().trim()); - } else if (RELAY_SERVER_STALL_ATTR.equals(aRelayAttr.getName())) { - stallTimeout = Long.parseLong(aRelayAttr.getValue().trim()); - } else if (RELAY_SERVER_ANNOUNCE_ATTR.equals(aRelayAttr.getName())) { - announceInterval = Long.parseLong(aRelayAttr.getValue().trim()); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Attribute: " + aRelayAttr.getName()); - } - } - } - - return true; - } else if (ACL_URI.equals(elem.getName())) { - String addrElement = elem.getTextValue(); - - if (null != addrElement) { - aclURI = URI.create(addrElement.trim()); - } - - return true; - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - if (!(adv instanceof Attributable)) { - throw new IllegalStateException("Only Attributable documents are supported."); - } - - if ((-1 != maxRelays) && (maxRelays <= 0)) { - throw new IllegalStateException("Max relays must not be negative or zero."); - } - - if ((-1 != maxClientLeaseDuration) && (maxClientLeaseDuration <= 0)) { - throw new IllegalStateException("Max lease duration must not be negative or zero."); - } - - if ((-1 != messengerPollInterval) && (messengerPollInterval <= 0)) { - throw new IllegalStateException("Messenger poll interval must not be negative or zero."); - } - - if (useOnlySeeds && clientEnabled && seedRelays.isEmpty() && seedingURIs.isEmpty()) { - throw new IllegalStateException("Cannot specify 'useOnlySeeds' and no seed relays"); - } - - if ((-1 != maxClients) && (maxClients <= 0)) { - throw new IllegalStateException("Max clients must not be negative or zero."); - } - - if ((-1 != maxClientMessageQueue) && (maxClientMessageQueue <= 0)) { - throw new IllegalStateException("Max client queue must not be negative or zero."); - } - - if ((-1 != maxServerLeaseDuration) && (maxServerLeaseDuration <= 0)) { - throw new IllegalStateException("Max lease duration must not be negative or zero."); - } - - if ((-1 != stallTimeout) && (stallTimeout <= 0)) { - throw new IllegalStateException("Client stall timeout duration must not be negative or zero."); - } - - if ((-1 != announceInterval) && (announceInterval <= 0)) { - throw new IllegalStateException("Announce interval must not be negative or zero."); - } - - Attributable attrDoc = (Attributable) adv; - - if (clientEnabled) { - attrDoc.addAttribute(RELAY_CLIENT_ATTR, Boolean.TRUE.toString()); - } - - if (serverEnabled) { - attrDoc.addAttribute(RELAY_SERVER_ATTR, Boolean.TRUE.toString()); - } - - Element clientElem = adv.createElement(RELAY_CLIENT_ELEMENT); - - adv.appendChild(clientElem); - - Attributable attrElem = (Attributable) clientElem; - - if (-1 != maxRelays) { - attrElem.addAttribute(RELAY_CLIENT_SERVERS_ATTR, Integer.toString(maxRelays)); - } - - if (-1 != maxClientLeaseDuration) { - attrElem.addAttribute(RELAY_CLIENT_LEASE_ATTR, Long.toString(maxClientLeaseDuration)); - } - - if (-1 != messengerPollInterval) { - attrElem.addAttribute(RELAY_CLIENT_POLL_ATTR, Long.toString(messengerPollInterval)); - } - - if (!seedRelays.isEmpty() || !seedingURIs.isEmpty()) { - Element seedsElem = adv.createElement(RELAY_CLIENT_SEEDS_ELEMENT); - - clientElem.appendChild(seedsElem); - - attrElem = (Attributable) seedsElem; - - if (useOnlySeeds) { - attrElem.addAttribute(USE_ONLY_SEEDS_ATTR, Boolean.TRUE.toString()); - } - - for (EndpointAddress seedRelay : seedRelays) { - Element addrElement = adv.createElement(SEED_RELAY_ADDR_ELEMENT, seedRelay.toString()); - - seedsElem.appendChild(addrElement); - } - - for (URI seedingURI : seedingURIs) { - Element addrElement = adv.createElement(SEED_RELAY_ADDR_ELEMENT, seedingURI.toString()); - - seedsElem.appendChild(addrElement); - - ((Attributable) addrElement).addAttribute(SEED_RELAY_ADDR_SEEDING_ATTR, Boolean.TRUE.toString()); - } - } - - Element serverElem = adv.createElement(RELAY_SERVER_ELEMENT); - - adv.appendChild(serverElem); - - attrElem = (Attributable) serverElem; - - if (-1 != maxClients) { - attrElem.addAttribute(RELAY_SERVER_CLIENTS_ATTR, Integer.toString(maxClients)); - } - - if (-1 != maxClientMessageQueue) { - attrElem.addAttribute(RELAY_SERVER_QUEUE_ATTR, Integer.toString(maxClientMessageQueue)); - } - - if (-1 != maxServerLeaseDuration) { - attrElem.addAttribute(RELAY_SERVER_LEASE_ATTR, Long.toString(maxServerLeaseDuration)); - } - - if (-1 != stallTimeout) { - attrElem.addAttribute(RELAY_SERVER_STALL_ATTR, Long.toString(stallTimeout)); - } - - if (-1 != announceInterval) { - attrElem.addAttribute(RELAY_SERVER_ANNOUNCE_ATTR, Long.toString(announceInterval)); - } - if (aclURI != null) { - Element acl = adv.createElement(ACL_URI, aclURI.toString()); - - adv.appendChild(acl); - } - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return fields; - } - - /** - * If true then this peer will act as a relay client. - * - * @return If true then this peer will act as a relay client. - */ - public boolean isClientEnabled() { - return clientEnabled; - } - - /** - * If true then this peer will act as a relay client. - * - * @param enabled If true then this peer will act as a relay client. - */ - public void setClientEnabled(boolean enabled) { - clientEnabled = enabled; - } - - /** - * Return the maximum number of relay clients. - * - * @return The maximum number of relay clients or -1 for - * default value. - */ - public int getMaxRelays() { - return maxRelays; - } - - /** - * Sets the maximum number of relay clients. - * - * @param newvalue The maximum number of relay clients or -1 - * for default value or -1 for default value. - */ - public void setMaxRelays(int newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Max Relays must be > 0"); - } - - maxRelays = newvalue; - } - - /** - * The interval in relative milliseconds of leases accepted by clients. - * - * @return The interval in relative milliseconds of leases accepted by - * clients or -1 for default value. - */ - public long getClientLeaseDuration() { - return maxClientLeaseDuration; - } - - /** - * Sets interval in relative milliseconds of leases accepted by clients. - * - * @param newvalue The interval in relative milliseconds of leases accepted - * by clients or -1 for default value. - */ - public void setClientLeaseDuration(long newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Lease Duration must be > 0"); - } - - maxClientLeaseDuration = newvalue; - } - - /** - * The interval in relative milliseconds of at which clients will poll for - * messengers - * - * @return The interval in relative milliseconds of at which clients will - * poll for messengers or -1 for default value. - */ - public long getMessengerPollInterval() { - return messengerPollInterval; - } - - /** - * Sets interval in relative milliseconds of at which clients will poll for - * messengers. - * - * @param newvalue The interval in relative milliseconds of at which clients - * will poll for messengers or -1 for default value. - */ - public void setMessengerPollInterval(long newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Poll interval must be > 0"); - } - - messengerPollInterval = newvalue; - } - - /** - * If true then this peer will use only seed rendezvous when configured as - * an edge peer. - * - * @return If true then this peer will use only seed rendezvous when configured as - * an edge peer. - */ - public boolean getUseOnlySeeds() { - return useOnlySeeds; - } - - /** - * Set whether this peer will use only seed rendezvous when configured as - * an edge peer. - * - * @param onlySeeds If true then this peer will use only seed rendezvous when configured as - * an edge peer. - */ - public void setUseOnlySeeds(boolean onlySeeds) { - useOnlySeeds = onlySeeds; - } - - public EndpointAddress[] getSeedRelays() { - return seedRelays.toArray(new EndpointAddress[seedRelays.size()]); - } - - public void addSeedRelay(EndpointAddress addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - seedRelays.add(addr); - } - - public void addSeedRelay(String addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - seedRelays.add(new EndpointAddress(addr)); - } - - public boolean removeSeedRelay(EndpointAddress addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - return seedRelays.remove(addr); - } - - public void clearSeedRelays() { - seedRelays.clear(); - } - - public URI[] getSeedingURIs() { - return seedingURIs.toArray(new URI[seedingURIs.size()]); - } - - public void addSeedingURI(URI addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - seedingURIs.add(addr); - } - - public void addSeedingURI(String addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - seedingURIs.add(URI.create(addr)); - } - - public boolean removeSeedingURI(URI addr) { - if (null == addr) { - throw new IllegalArgumentException("addr may not be null"); - } - - return seedingURIs.remove(addr); - } - - public void clearSeedingURIs() { - seedingURIs.clear(); - } - - /** - * If true then this peer will act as a relay server. - * - * @return If true then this peer will act as a relay server. - */ - public boolean isServerEnabled() { - return serverEnabled; - } - - /** - * If true then this peer will act as a relay server. - * - * @param enabled If true then this peer will act as a relay server. - */ - public void setServerEnabled(boolean enabled) { - serverEnabled = enabled; - } - - /** - * Return the maximum number of relay clients. - * - * @return The maximum number of relay clients or -1 for - * default value. - */ - public int getMaxClients() { - return maxClients; - } - - /** - * Sets he maximum number of relay clients. - * - * @param newvalue The maximum number of relay clients or -1 - * for default value. - */ - public void setMaxClients(int newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Max Clients must be > 0"); - } - - maxClients = newvalue; - } - - /** - * Return the client message queue length size. - * - * @return The client message queue length size or -1 for default value. - */ - public int getClientMessageQueueSize() { - return maxClientMessageQueue; - } - - /** - * Sets the client message queue length size. - * - * @param newvalue The client message queue length size or -1 - * for default value. - */ - public void setClientMessageQueueSize(int newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Client Message Queue Size must be > 0"); - } - - maxClientMessageQueue = newvalue; - } - - /** - * The interval in relative milliseconds of leases offered by servers. - * - * @return The interval in relative milliseconds of leases offered by servers. - */ - public long getServerLeaseDuration() { - return maxServerLeaseDuration; - } - - /** - * Sets interval in relative milliseconds of leases offered by servers. - * - * @param newvalue The interval in relative milliseconds of leases offered - * by servers or -1 for default value. - */ - public void setServerLeaseDuration(long newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Lease Duration must be >= 0"); - } - - maxServerLeaseDuration = newvalue; - } - - /** - * The interval in relative milliseconds after which a client is assumed to - * no longer be connected if it fails to request messages. - * - * @return The interval in relative milliseconds after which a client is - * assumed to no longer be connected if it fails to request messages or - * -1 for default value. - */ - public long getStallTimeout() { - return stallTimeout; - } - - /** - * Sets interval in relative milliseconds after which a client is assumed to - * no longer be connected if it fails to request messages. - * - * @param newvalue The interval in relative milliseconds after which a - * client is assumed to no longer be connected if it fails to request - * messages or -1 for default value. - */ - public void setStallTimeout(long newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Stall timeout must be > 0"); - } - - stallTimeout = newvalue; - } - - /** - * The interval in relative milliseconds at which relay server will - * announce its presence. - * - * @return The interval in relative milliseconds at which relay server will - * broadcast its presence or -1 for default value. - */ - public long getAnnounceInterval() { - return announceInterval; - } - - /** - * Sets interval in relative milliseconds at which relay server will - * announce its presence or -1 for default value. - * - * @param newvalue The interval in relative milliseconds at which relay server will - * announce its presence. - */ - public void setAnnounceInterval(long newvalue) { - if ((-1 != newvalue) && (newvalue <= 0)) { - throw new IllegalArgumentException("Announce Interval must be > 0"); - } - - announceInterval = newvalue; - } - - /** - * Return ACL URI if set - * - * @return ACL URI if set, null otherwise - */ - public URI getAclUri() { - return aclURI; - } - - /** - * Sets ACL URI - * - * @param uri URI if set, null otherwise - */ - public void setAclUri(URI uri) { - aclURI = uri; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ResolverQuery.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ResolverQuery.java deleted file mode 100644 index ac1ce007..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ResolverQuery.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.protocol; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import java.util.logging.Logger; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.TextElement; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.id.IDFactory; -import net.jxta.protocol.ResolverQueryMsg; -import net.jxta.protocol.ResolverResponseMsg; -import net.jxta.protocol.RouteAdvertisement; - -/** - * Implements the Resolver Query Message according to the - * schema defined by the core JXTA Peer Resolver Protocol (PRP). - *

            - *

            - * <xs:element name="ResolverQuery" type="jxta:ResolverQuery"/>
            - * 

            - * <xs:complexType name="ResolverQuery"> - * <xs:all> - * <xs:element ref="jxta:Cred" minOccurs="0"/> - * <xs:element name="SrcPeerID" type="jxta:JXTAID"/> - * <xs:element name="SrcPeerRoute" type="jxta:JXTA RouteAdv"/> - * <!-- This could be extended with a pattern restriction --> - * <xs:element name="HandlerName" type="xs:string"/> - * <xs:element name="QueryID" type="xs:string"/> - * <xs:element name="HC" type="xs:unsignedInt"/> - * <xs:element name="Query" type="xs:anyType"/> - * </xs:all> - * </xs:complexType> - *

            - *

            - *

            IMPORTANT: a ResolverQuery contains an internal - * state, the hopCount, which is incremented by various services that needs to. - * As a result, a ResolverQuery may have to be cloned when the hopCount state - * needs to be reset. - * - * @see net.jxta.resolver.ResolverService - * @see net.jxta.protocol.ResolverQueryMsg - * @see JXTA Protocols Specification : Peer Resolver Protocol - */ -public class ResolverQuery extends ResolverQueryMsg implements Cloneable { - - /** - * The logger - */ - private final static Logger LOG = Logger.getLogger(ResolverQuery.class.getName()); - - private static final String handlernameTag = "HandlerName"; - private static final String credentialTag = "jxta:Cred"; - private static final String queryIdTag = "QueryID"; - private static final String hopCountTag = "HC"; - private static final String srcPeerIdTag = "SrcPeerID"; - private static final String srcRouteTag = "SrcPeerRoute"; - private static final String queryTag = "Query"; - - /** - * Default constructor - */ - public ResolverQuery() { - super(); - } - - /** - * Construct a doc from strings - * - * @param HandlerName the handler name - * @param Credential credential document - * @param pId source PeerID - * @param Query opaque query string - * @param qid query ID - * @deprecated use the individual accessor methods instead. - */ - @Deprecated - public ResolverQuery(String HandlerName, StructuredDocument Credential, String pId, String Query, int qid) { - - this(); - setHandlerName(HandlerName); - setCredential(Credential); - setQueryId(qid); - setSrc(pId); - setQuery(Query); - } - - /** - * Construct from a StructuredDocument - * - * @param root the element - */ - public ResolverQuery(Element root) { - - this(); - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - String doctype = doc.getName(); - - if (!getAdvertisementType().equals(doctype)) { - throw new IllegalArgumentException("Could not construct : " + getClass().getName() + "from doc containing a " + doctype); - } - readIt(doc); - - // sanity check! - if (null == getHandlerName()) { - throw new IllegalArgumentException("Query message does not contain a handler name."); - } - - if (null == getQuery()) { - throw new IllegalArgumentException("Query message does not contain a query."); - } - - if (null == getSrcPeer()) { - throw new IllegalArgumentException("Query message does not define a source."); - } - - RouteAdvertisement ra = getSrcPeerRoute(); - - if ((null != ra) && (null == ra.getDestPeerID())) { - throw new IllegalArgumentException("Route does not define a destination."); - } - } - - /** - * parses an XML document into this object - * - * @param doc the element - */ - public void readIt(XMLElement doc) { - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - TextElement elem = (TextElement) elements.nextElement(); - - if (elem.getName().equals(handlernameTag)) { - setHandlerName(elem.getTextValue()); - continue; - } - // Set credential - if (elem.getName().equals(credentialTag)) { - setCredential(StructuredDocumentUtils.copyAsDocument(elem)); - continue; - } - // Set queryid - if (elem.getName().equals(queryIdTag)) { - queryid = Integer.parseInt(elem.getTextValue()); - continue; - } - - // Set source route - if (elem.getName().equals(srcRouteTag)) { - for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements();) { - XMLElement aXpt = (XMLElement) eachXpt.nextElement(); - RouteAdvertisement routeAdv = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(aXpt); - - if (null != routeAdv.getDestPeerID()) { - setSrcPeerRoute(routeAdv); - setSrcPeer(routeAdv.getDestPeerID()); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Incomplete Route Advertisement (missing peer id)."); - } - } - } - continue; - } - - // Set hopcount - if (elem.getName().equals(hopCountTag)) { - setHopCount(Integer.parseInt(elem.getTextValue())); - continue; - } - - // Set source peer - // FIXME tra 20031108 Since Peer Id is already part - // of the SrcRoute Tag. We should be able to remove - // processing this tag in the future. - if (elem.getName().equals(srcPeerIdTag)) { - try { - String value = elem.getTextValue(); - if (value != null && value.length() > 0) { - URI srcURI = new URI(elem.getTextValue()); - setSrcPeer(IDFactory.fromURI(srcURI)); - } - } catch (URISyntaxException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Bad ID in message", failed); - } - RuntimeException failure = new IllegalArgumentException("Bad ID in message"); - failure.initCause(failed); - throw failure; - } - continue; - } - // Set query - if (elem.getName().equals(queryTag)) { - setQuery(elem.getTextValue()); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - // sanity check! - if (null == getHandlerName()) { - throw new IllegalStateException("Query message does not contain a handler name."); - } - - if (null == getQuery()) { - throw new IllegalStateException("Query message does not contain a query."); - } - - if (null == getSrcPeer()) { - throw new IllegalStateException("Query message does not define a source."); - } - - RouteAdvertisement ra = getSrcPeerRoute(); - - if ((null != ra) && (null == ra.getDestPeerID())) { - throw new IllegalStateException("Route does not define a destination."); - } - - StructuredTextDocument adv = (StructuredTextDocument) - StructuredDocumentFactory.newStructuredDocument(encodeAs, getAdvertisementType()); - - if (adv instanceof XMLDocument) { - ((XMLDocument) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - } - Element e; - - e = adv.createElement(handlernameTag, getHandlerName()); - adv.appendChild(e); - if (getCredential() != null) { - StructuredDocumentUtils.copyElements(adv, adv, getCredential()); - } - e = adv.createElement(queryIdTag, Integer.toString(queryid)); - adv.appendChild(e); - e = adv.createElement(hopCountTag, Integer.toString(hopcount)); - adv.appendChild(e); - - // FIXME tra 20031108 Since Peer Id is already part of the SrcRoute Tag. - // We should stop emitting this tag in the future. - if (null != getSrcPeer()) { - e = adv.createElement(srcPeerIdTag, getSrcPeer().toString()); - adv.appendChild(e); - } - - RouteAdvertisement radv = this.getSrcPeerRoute(); - - if (radv != null) { - e = adv.createElement(srcRouteTag); - adv.appendChild(e); - StructuredTextDocument xptDoc = (StructuredTextDocument)radv.getDocument(encodeAs); - StructuredDocumentUtils.copyElements(adv, e, xptDoc); - } - - e = adv.createElement(queryTag, getQuery()); - adv.appendChild(e); - return adv; - } - - /** - * {@inheritDoc} - *

            Result is the query as an XML string. - */ - @Override - public String toString() { - return getDocument(MimeMediaType.XMLUTF8).toString(); - } - - /** - * {@inheritDoc} - */ - @Override - public ResolverQuery clone() { - ResolverQuery tmp; - - try { - tmp = (ResolverQuery) super.clone(); - } catch (CloneNotSupportedException e) { - throw new Error("Object.clone() threw CloneNotSupportedException", e); - } - - tmp.setHandlerName(getHandlerName()); - tmp.setCredential(getCredential()); - tmp.setSrcPeer(getSrcPeer()); - tmp.setQuery(getQuery()); - tmp.setQueryId(getQueryId()); - tmp.setHopCount(getHopCount()); - tmp.setSrcPeerRoute(getSrcPeerRoute()); - - return tmp; - } - - /** - * {@inheritDoc} - * - * @return ResolverResponse Msg - */ - @Override - public ResolverResponseMsg makeResponse() { - // construct a new response - ResolverResponse res = new ResolverResponse(); - - // transfer the query information - res.setHandlerName(this.getHandlerName()); - res.setQueryId(this.getQueryId()); - - // transfer optional route information available in the query - // to the response. - // - // NOTE: The route field is just attached to the response and - // will not be sent as part of the response. We just use this to - // pass information to the resolver. The other alternative will - // be to add a resolver or peergroup arg to makeResponse() as - // we don't have access to any peergroup info here to process - // the route information we just received. We will process - // the information just before we send the response. This - // may be better anyway as the service may never really respond. - res.setSrcPeerRoute(this.getSrcPeerRoute()); - - return res; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ResolverResponse.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ResolverResponse.java deleted file mode 100644 index 211d772e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ResolverResponse.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.util.Enumeration; - -import net.jxta.document.*; -import net.jxta.protocol.ResolverResponseMsg; -import net.jxta.protocol.RouteAdvertisement; - - -/** - * ResolverResponse provides an implementation for - * {@link net.jxta.protocol.ResolverResponseMsg} using the standard JXTA - * Peer Resolver Protocol. - * - *

            The message is implemented with the following schema: - * - *

            
            - * <xs:complexType name="ResolverResponse">
            - *   <xs:all>
            - *     <xs:element ref="jxta:Cred" minOccurs="0"/>
            - *     <xs:element name="HandlerName" type="xs:string"/>
            - *     <xs:element name="QueryID" type="xs:string"/>
            - *     <xs:element name="Response" type="xs:anyType"/>
            - *   </xs:all>
            - * </xs:complexType>
            - *
            - * - * @see JXTA Protocols Specification : Peer Resolver Protocol - */ -public class ResolverResponse extends ResolverResponseMsg { - - private static final String handlernameTag = "HandlerName"; - private static final String credentialTag = "jxta:Cred"; - private static final String queryIdTag = "QueryID"; - private static final String responseTag = "Response"; - - /** - * optional route information to send the response - */ - private RouteAdvertisement srcRoute = null; - - /** - * - * Standard Constructor for new instances. - */ - public ResolverResponse() {} - - /** - * Construct a doc from strings - * - * @deprecated use the individual accessor methods instead. - * @param HandlerName the handler name - * @param Credential the credential doc - * @param QueryId query ID - * @param Response the response - * - */ - @Deprecated - public ResolverResponse(String HandlerName, StructuredDocument Credential, int QueryId, String Response) { - setHandlerName(HandlerName); - setCredential(Credential); - setQueryId(QueryId); - setResponse(Response); - } - - /** - * Construct from a StructuredDocument - * - * @param root the element - */ - public ResolverResponse(Element root) { - - this(); - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - String doctype = doc.getName(); - - if (!getAdvertisementType().equals(doctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doctype); - } - - readIt(doc); - - // sanity check - if (null == getHandlerName()) { - throw new IllegalArgumentException("Response message does not contain a handler name"); - } - - if (null == getResponse()) { - throw new IllegalArgumentException("Response message does not contain a response"); - } - } - - public void readIt(TextElement doc) { - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - TextElement elem = (TextElement) elements.nextElement(); - - if (elem.getName().equals(handlernameTag)) { - setHandlerName(elem.getTextValue()); - continue; - } - // Set credential - if (elem.getName().equals(credentialTag)) { - setCredential(StructuredDocumentUtils.copyAsDocument(elem)); - continue; - } - // Set queryid - if (elem.getName().equals(queryIdTag)) { - queryid = Integer.parseInt(elem.getTextValue()); - continue; - } - // Set response - if (elem.getName().equals(responseTag)) { - setResponse(elem.getTextValue()); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType asMimeType) { - - StructuredTextDocument adv = (StructuredTextDocument) - StructuredDocumentFactory.newStructuredDocument(asMimeType, getAdvertisementType()); - - if (adv instanceof Attributable) { - ((Attributable) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - Element e; - - e = adv.createElement(handlernameTag, getHandlerName()); - adv.appendChild(e); - if (getCredential() != null) { - StructuredDocumentUtils.copyElements(adv, adv, getCredential()); - } - e = adv.createElement(queryIdTag, Integer.toString(queryid)); - adv.appendChild(e); - e = adv.createElement(responseTag, getResponse()); - adv.appendChild(e); - return adv; - } - - /** - * {@inheritDoc} - * - *

            Result is the response as an XML string. - */ - @Override - public String toString() { - return getDocument(MimeMediaType.XMLUTF8).toString(); - } - - /** - * Set optional route information as part of the response. - * This information is just attached to the response and - * will not be sent as part of the response - * - * @param route RouteAdvertisement to send the response - */ - - @Override - public void setSrcPeerRoute(RouteAdvertisement route) { - srcRoute = route; - } - - /** - * Get optional route information that may be attached to the - * response. This information is just attached to the response and will - * not be sent as part of the response - * - * @return RouteAdvertisement to send the response - */ - - @Override - public RouteAdvertisement getSrcPeerRoute() { - if (srcRoute != null) { - return srcRoute.clone(); - } else { - return null; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ResolverSrdiMsgImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ResolverSrdiMsgImpl.java deleted file mode 100644 index e061b8f0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/ResolverSrdiMsgImpl.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.protocol; - - -import java.util.Enumeration; - -import net.jxta.credential.Credential; -import net.jxta.document.*; -import net.jxta.membership.MembershipService; -import net.jxta.protocol.ResolverSrdiMsg; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * ResolverQuery provides the binding for the message to query other nodes - */ -public class ResolverSrdiMsgImpl extends ResolverSrdiMsg { - - private final static Logger LOG = Logger.getLogger(ResolverSrdiMsgImpl.class.getName()); - - /** - * Description of the Field - */ - public final static String handlernameTag = "HandlerName"; - - /** - * Description of the Field - */ - public final static String credentialTag = "jxta:Cred"; - - /** - * Description of the Field - */ - public final static String payloadTag = "Payload"; - - /** - * Constructor for the ResolverSrdiMsgImpl object - */ - public ResolverSrdiMsgImpl() {} - - /** - * Construct from a StructuredDocument - * - * @param root the underlying document - * @param membership membership service used to verify credentials - */ - public ResolverSrdiMsgImpl(Element root, MembershipService membership) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - String doctype = doc.getName(); - - if (!getMessageType().equals(doctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doctype); - } - readIt(doc, membership); - } - - /** - * Creates this object with a specific handler name, credential and payload - * - * @param handlerName the - * @param cred the credntial - * @param payload the payload - */ - public ResolverSrdiMsgImpl(String handlerName, Credential cred, String payload) { - - setHandlerName(handlerName); - setPayload(payload); - setCredential(cred); - } - - /** - * return the string representaion of this doc - * - * @return string representation of the message - */ - @Override - public String toString() { - - StructuredTextDocument doc = (StructuredTextDocument) getDocument(MimeMediaType.XMLUTF8); - - return doc.toString(); - } - - /** - * return a Document represetation of this object - * - * @param asMimeType type of message - * @return document - */ - @Override - public Document getDocument(MimeMediaType asMimeType) { - StructuredTextDocument adv = (StructuredTextDocument) StructuredDocumentFactory.newStructuredDocument(asMimeType - , - getMessageType()); - - if (adv instanceof XMLElement) { - ((XMLElement) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - Element e; - - e = adv.createElement(handlernameTag, getHandlerName()); - adv.appendChild(e); - if (getCredential() != null) { - try { - StructuredDocumentUtils.copyElements(adv, adv, (getCredential()).getDocument(asMimeType)); - } catch (Exception ce) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Got an Exception during credential creation ", ce); - } - } - } - e = adv.createElement(payloadTag, getPayload()); - adv.appendChild(e); - return adv; - } - - /** - * Parses an XML document into this object - * - * @param doc the underlying document - * @param membership used to parse credentails if any - */ - private void readIt(XMLElement doc, MembershipService membership) { - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (elem.getName().equals(handlernameTag)) { - setHandlerName(elem.getTextValue()); - continue; - } - // Set credential - if (elem.getName().equals(credentialTag)) { - Credential credential; - - if (elem.getTextValue() != null) { - try { - credential = membership.makeCredential(elem); - setCredential(credential); - } catch (Exception ce) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Credential creation failed", ce); - } - } - } - continue; - } - - // Set payload - if (elem.getName().equals(payloadTag)) { - setPayload(elem.getTextValue()); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RouteAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RouteAdv.java deleted file mode 100644 index fd233626..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RouteAdv.java +++ /dev/null @@ -1,332 +0,0 @@ -/* -Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLElement; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.protocol.AccessPointAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * This class implements the basic Route advertisement. - *

            - *

            - *    <xs:complexType name="RA">
            - *      <xs:sequence>
            - *          <xs:element name="DstPID" type="jxta:JXTAID" minOccurs="0"/>
            - *          <xs:element name="Dst">
            - *              <xs:complexType>
            - *            <xs:sequence>
            - *                      <xs:element ref="jxta:APA" />
            - *            </xs:sequence>
            - *              </xs:complexType>
            - *        </xs:element>
            - *        <xs:element name="Hops" minOccurs="0">
            - *              <xs:complexType>
            - *            <xs:sequence>
            - *                      <xs:element ref="jxta:APA" maxOccurs="unbounded" />
            - *            </xs:sequence>
            - *              </xs:complexType>
            - *        </xs:element>
            - *      </xs:sequence>
            - *    </xs:complexType>
            - * 
            - * - * @see net.jxta.protocol.RouteAdvertisement - */ -public class RouteAdv extends RouteAdvertisement implements Cloneable { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(RouteAdv.class.getName()); - - private static final String[] INDEX_FIELDS = {DEST_PID_TAG}; - - /** - * Instantiator for our advertisement - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return RouteAdv.getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new RouteAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getAdvertisementType() + " only supports XLMElement"); - } - - return new RouteAdv((XMLElement) root); - } - } - - /** - * Private constructor. Use instantiator - */ - private RouteAdv() {} - - /** - * Private constructor. Use instantiator - * - * @param doc the element - */ - private RouteAdv(XMLElement doc) { - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException("Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - - // Compatibility hack - setDestPeerID(getDestPeerID()); - - // Sanity Check!!! - if (hasALoop()) { - throw new IllegalArgumentException("Route contains a loop!"); - } - } - - /** - * {@inheritDoc} - */ - @Override - public RouteAdv clone() { - return (RouteAdv) super.clone(); - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (DEST_PID_TAG.equals(elem.getName())) { - try { - URI pID = new URI(elem.getTextValue()); - - setDestPeerID((PeerID) IDFactory.fromURI(pID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerID in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("ID in advertisement is not a peer id"); - } - return true; - } - - if ("Dst".equals(elem.getName())) { - for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements();) { - XMLElement aXpt = (XMLElement) eachXpt.nextElement(); - - AccessPointAdvertisement xptAdv = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(aXpt); - - setDest(xptAdv); - } - return true; - } - - if ("Hops".equals(elem.getName())) { - Vector hops = new Vector(); - - for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements();) { - XMLElement aXpt = (XMLElement) eachXpt.nextElement(); - - AccessPointAdvertisement xptAdv = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(aXpt); - - hops.addElement(xptAdv); - } - setHops(hops); - return true; - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - if (hasALoop()) { - throw new IllegalStateException("I won't write a doc for a route with a loop"); - } - - PeerID pid = getDestPeerID(); - - if (null != pid) { - Element e0 = adv.createElement(DEST_PID_TAG, pid.toString()); - - adv.appendChild(e0); - } - - Element e1 = adv.createElement("Dst"); - - adv.appendChild(e1); - - AccessPointAdvertisement dest = getDest(); - - // create a copy without the PID if necessary (the pid is redundant) - AccessPointAdvertisement destAPA = dest; - if(null != dest.getPeerID()) { - destAPA = dest.clone(); - destAPA.setPeerID(null); - } - - StructuredDocument xptDoc = (StructuredDocument) destAPA.getDocument(encodeAs); - StructuredDocumentUtils.copyElements(adv, e1, xptDoc); - - Enumeration eachHop = getHops(); - - // only include hops if we have some - if (eachHop.hasMoreElements()) { - Element e2 = adv.createElement("Hops"); - - adv.appendChild(e2); - - while (eachHop.hasMoreElements()) { - AccessPointAdvertisement hop = eachHop.nextElement(); - - if (null == hop.getPeerID()) { - // Refuse to write illegal hops. - continue; - } - - xptDoc = (StructuredDocument) hop.getDocument(encodeAs); - - StructuredDocumentUtils.copyElements(adv, e2, xptDoc); - } - } - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return INDEX_FIELDS; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RouteQuery.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RouteQuery.java deleted file mode 100644 index 9afedf37..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RouteQuery.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.XMLElement; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.protocol.RouteAdvertisement; -import net.jxta.protocol.RouteQueryMsg; - -import java.lang.reflect.UndeclaredThrowableException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Collection; -import java.util.Enumeration; -import net.jxta.document.XMLDocument; - -/** - * RouteQuery message used by the Endpoint Routing protocol to - * query for route - */ -public class RouteQuery extends RouteQueryMsg { - - private static final String destPIDTag = "Dst"; - private static final String srcRouteTag = "Src"; - private static final String badHopTag = "Bad"; - - /** - * Default Constructor - */ - public RouteQuery() {} - - /** - * Constructs a RouteQuery - * - * @deprecated Use default constructor and accessors. - * - * @param dest dest PeerID - * @param srcRoute source source - * @param badhops lis of AccessPointAdvertisements - */ - @Deprecated - public RouteQuery(PeerID dest, RouteAdvertisement srcRoute, Collection badhops) { - setDestPeerID(dest); - setSrcRoute(srcRoute); - setBadHops(badhops); - } - - /** - * Construct from an XML document fragment. - * - * @param doc the element - */ - public RouteQuery(XMLElement doc) { - String doctype = doc.getName(); - - if (!doctype.equals(getAdvertisementType())) { - throw new IllegalArgumentException( - "Can not construct : " + getClass().getName() + " from doc containing a " + doctype); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = elements.nextElement(); - - if (elem.getName().equals(destPIDTag)) { - try { - URI pID = new URI(elem.getTextValue()); - PeerID pid = (PeerID) IDFactory.fromURI(pID); - - setDestPeerID(pid); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerID ID in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Not a peer id"); - } - continue; - } - - if (elem.getName().equals(srcRouteTag)) { - for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements();) { - XMLElement aXpt = eachXpt.nextElement(); - - RouteAdvertisement route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(aXpt); - - setSrcRoute(route); - } - continue; - } - - if (elem.getName().equals(badHopTag)) { - try { - URI pID = new URI(elem.getTextValue()); - PeerID pid = (PeerID) IDFactory.fromURI(pID); - - addBadHop(pid); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Bad PeerID ID in advertisement"); - } catch (ClassCastException badID) { - throw new IllegalArgumentException("Not a peer id"); - } - } - } - - if(null == getDestPeerID()) { - throw new IllegalArgumentException("Destination peer not initialized"); - } - } - - /** - * {@inheritDoc} - */ - @Override - public StructuredDocument getDocument(MimeMediaType asMimeType) { - if(null == getDestPeerID()) { - throw new IllegalStateException("Destination peer not initialized"); - } - - StructuredDocument adv = StructuredDocumentFactory.newStructuredDocument(asMimeType, getAdvertisementType()); - - if (adv instanceof XMLElement) { - ((Attributable) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - ((Attributable) adv).addAttribute("xml:space", "preserve"); - } - - Element e; - - PeerID dest = getDestPeerID(); - - e = adv.createElement(destPIDTag, dest.toString()); - adv.appendChild(e); - - RouteAdvertisement route = getSrcRoute(); - - if (route != null) { - e = adv.createElement(srcRouteTag); - adv.appendChild(e); - StructuredDocument xptDoc = (StructuredDocument) route.getDocument(asMimeType); - - StructuredDocumentUtils.copyElements(adv, e, xptDoc); - } - - for (PeerID eachPeer : getBadHops()) { - e = adv.createElement(badHopTag, eachPeer.toString()); - adv.appendChild(e); - } - - return adv; - } - - /** - * return a string representation of this RouteQuery doc - */ - @Override - public String toString() { - XMLDocument doc = (XMLDocument) getDocument(MimeMediaType.XMLUTF8); - - doc.addAttribute("xml:space", "default"); - - return doc.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RouteResponse.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RouteResponse.java deleted file mode 100644 index 22a60fe1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/RouteResponse.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.protocol.RouteAdvertisement; -import net.jxta.protocol.RouteResponseMsg; - -import java.lang.reflect.UndeclaredThrowableException; -import java.util.Enumeration; - - -/** - * Used by the Endpoint Routing protocol in response to Route Query Messages. - * The Route Response Message contains a route advertisement for the destination - * peer. - *

            - *

            - * <xs:complexType name="ERR">
            - *   <xs:sequence>
            - *     <xs:element name="Dst">
            - *       <xs:complexType>
            - *         <xs:sequence>
            - *           <xs:element ref="jxta:RA" />
            - *         </xs:sequence>
            - *       </xs:complexType>
            - *     </xs:element>
            - *     <xs:element name="Src">
            - *       <xs:complexType>
            - *         <xs:sequence>
            - *           <xs:element ref="jxta:RA" />
            - *         </xs:sequence>
            - *       </xs:complexType>
            - *     </xs:element>
            - *   </xs:sequence>
            - * </xs:complexType>
            - * 
            - * - * @see net.jxta.impl.endpoint.router.EndpointRouter - * @see JXTA Protocols Specification : Endpoint Routing Protocol - */ -public class RouteResponse extends RouteResponseMsg { - - private static final String destRouteTag = "Dst"; - private static final String srcRouteTag = "Src"; - - /** - * Construct a new Route Response Message - */ - public RouteResponse() {} - - /** - * Construct from an XML document fragment. - * - * @param doc the element - */ - public RouteResponse(XMLElement doc) { - - String doctype = doc.getName(); - - if (!doctype.equals(getAdvertisementType())) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + " from doc containing a " + doctype); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = elements.nextElement(); - - if (elem.getName().equals(destRouteTag)) { - for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements();) { - XMLElement aXpt = eachXpt.nextElement(); - - RouteAdvertisement route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(aXpt); - - setDestRoute(route); - } - continue; - } - - if (elem.getName().equals(srcRouteTag)) { - for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements();) { - XMLElement aXpt = eachXpt.nextElement(); - - RouteAdvertisement route = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(aXpt); - - setSrcRoute(route); - } - } - } - - // Validate. - - if (null == getSrcRoute()) { - throw new IllegalArgumentException("Missing source route."); - } - - if (null == getDestRoute()) { - throw new IllegalArgumentException("Missing destination route."); - } - - if (null == getSrcRoute().getDestPeerID()) { - throw new IllegalArgumentException("Bad source route."); - } - - if (null == getDestRoute().getDestPeerID()) { - throw new IllegalArgumentException("Bad destination route."); - } - } - - /** - * return a Document representation of this object - */ - @Override - public Document getDocument(MimeMediaType asMimeType) { - if (null == getSrcRoute()) { - throw new IllegalStateException("Missing source route."); - } - - if (null == getDestRoute()) { - throw new IllegalStateException("Missing destination route."); - } - - if (null == getSrcRoute().getDestPeerID()) { - throw new IllegalStateException("Bad source route."); - } - - if (null == getDestRoute().getDestPeerID()) { - throw new IllegalStateException("Bad destination route."); - } - - StructuredDocument adv = StructuredDocumentFactory.newStructuredDocument(asMimeType, getAdvertisementType()); - - if (adv instanceof XMLDocument) { - ((XMLDocument) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - ((XMLDocument) adv).addAttribute("xml:space", "preserve"); - } - - Element e; - - RouteAdvertisement route = getDestRoute(); - - if (route != null) { - e = adv.createElement(destRouteTag); - adv.appendChild(e); - StructuredTextDocument xptDoc = (StructuredTextDocument) - route.getDocument(asMimeType); - - StructuredDocumentUtils.copyElements(adv, e, xptDoc); - } - - route = getSrcRoute(); - if (route != null) { - e = adv.createElement(srcRouteTag); - adv.appendChild(e); - StructuredTextDocument xptDoc = (StructuredTextDocument) - route.getDocument(asMimeType); - - StructuredDocumentUtils.copyElements(adv, e, xptDoc); - } - return adv; - } - - /** - * {@inheritDoc} - * - *

            String representation of this RouteResponse doc. - */ - @Override - public String toString() { - XMLDocument doc = (XMLDocument) getDocument(MimeMediaType.XMLUTF8); - - doc.addAttribute("xml:space", "default"); - - return doc.toString(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/SignedAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/SignedAdv.java deleted file mode 100644 index b37fc0fc..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/SignedAdv.java +++ /dev/null @@ -1,384 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.id.ID; -import net.jxta.impl.membership.pse.PSECredential; -import net.jxta.impl.util.BASE64InputStream; -import net.jxta.impl.util.BASE64OutputStream; -import net.jxta.protocol.SignedAdvertisement; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.*; -import java.lang.reflect.UndeclaredThrowableException; -import java.security.Signature; -import java.util.Enumeration; - - -/** - * A container for signed Advertisements - */ -public class SignedAdv extends SignedAdvertisement { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(SignedAdv.class.getName()); - - private static final String ADV_TYPE = "jxta:SA"; - - private static final String[] INDEX_FIELDS = {}; - - /** - * Instantiator for SignedAdv - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return ADV_TYPE; - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new SignedAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - return new SignedAdv((XMLElement) root); - } - } - - private byte[] signature = null; - - /** - * Returns the identifying type of this Advertisement. - *

            - *

            Note: This is a static method. It cannot be used to determine - * the runtime type of an advertisement. ie. - *

            -     *      Advertisement adv = module.getSomeAdv();
            -     *      String advType = adv.getAdvertisementType();
            -     *  
            - *

            - *

            This is wrong and does not work the way you might expect. - * This call is not polymorphic and calls - * Advertisement.getAdvertisementType() no matter what the real type of the - * advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return ADV_TYPE; - } - - /** - * Private constructor for new instances. Use the instantiator. - */ - private SignedAdv() { - } - - /** - * Private constructor for xml serialized instances. Use the instantiator. - * - * @param doc The XML serialization of the advertisement. - */ - private SignedAdv(XMLElement doc) { - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - Element elem = (Element) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return INDEX_FIELDS; - } - - /** - * {@inheritDoc} - */ - @Override - public net.jxta.id.ID getID() { - // FIXME bondolo Needs real implementation. - return ID.nullID; - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if ("Credential".equals(elem.getName())) { - signer = new PSECredential(elem); - - return true; - } else if ("Signature".equals(elem.getName())) { - try { - Reader signatureB64 = new StringReader(elem.getTextValue()); - InputStream bis = new BASE64InputStream(signatureB64); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - do { - int c = bis.read(); - - if (-1 == c) { - break; - } - bos.write(c); - } while (true); - - bis.close(); - bos.close(); - signature = bos.toByteArray(); - - return true; - } catch (IOException failed) { - IllegalArgumentException failure = new IllegalArgumentException("Could not process Signature"); - - failure.initCause(failed); - - throw failure; - } - } else if ("Advertisement".equals(elem.getName())) { - try { - Reader advertisementB64 = new StringReader(elem.getTextValue()); - InputStream bis = new BASE64InputStream(advertisementB64); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - do { - int c = bis.read(); - - if (-1 == c) { - break; - } - bos.write(c); - } while (true); - - byte advbytes[] = bos.toByteArray(); - - Signature verifier = ((PSECredential) signer).getSignatureVerifier("SHA1WITHRSA"); - - verifier.update(advbytes); - - boolean matched = verifier.verify(signature); - - if (!matched) { - throw new IllegalArgumentException("Advertisement could not be verified"); - } - - advertisementB64 = new StringReader(elem.getTextValue()); - bis = new BASE64InputStream(advertisementB64); - - adv = AdvertisementFactory.newAdvertisement(elem.getRoot().getMimeType(), bis); - - return true; - } catch (IOException failed) { - IllegalArgumentException failure = new IllegalArgumentException("Could not process Advertisement"); - - failure.initCause(failed); - - throw failure; - } catch (java.security.NoSuchAlgorithmException failed) { - IllegalArgumentException failure = new IllegalArgumentException("Could not process Advertisement"); - - failure.initCause(failed); - - throw failure; - } catch (java.security.SignatureException failed) { - IllegalArgumentException failure = new IllegalArgumentException("Could not process Advertisement"); - - failure.initCause(failed); - - throw failure; - } - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - - if (null == adv) { - throw new IllegalStateException("Advertisement not initialized"); - } - - if (null == signer) { - throw new IllegalStateException("Signer Credential not initialized"); - } - - if (!(signer instanceof PSECredential)) { - throw new IllegalStateException("Signer Credential not initialized"); - } - - StructuredDocument doc = (StructuredDocument) super.getDocument(encodeAs); - - StructuredDocument advDoc = (StructuredDocument) adv.getDocument(encodeAs); - - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - advDoc.sendToStream(bos); - bos.close(); - - byte advData[] = bos.toByteArray(); - - PSECredential psecred = (PSECredential) signer; - - Signature advSigner = psecred.getSigner("SHA1WITHRSA"); - - advSigner.update(advData); - - byte signature[] = advSigner.sign(); - - StringWriter signatureB64 = new StringWriter(); - StringWriter advertisementB64 = new StringWriter(); - - OutputStream signatureOut = new BASE64OutputStream(signatureB64); - - signatureOut.write(signature); - signatureOut.close(); - - OutputStream advertisementOut = new BASE64OutputStream(advertisementB64, 72); - - advertisementOut.write(advData); - advertisementOut.close(); - - StructuredDocument creddoc = signer.getDocument(encodeAs); - - StructuredDocumentUtils.copyElements(doc, doc, creddoc, "Credential"); - - Element elem = doc.createElement("Signature", signatureB64.toString()); - - doc.appendChild(elem); - - elem = doc.createElement("Advertisement", advertisementB64.toString()); - doc.appendChild(elem); - if (doc instanceof Attributable) { - ((Attributable) elem).addAttribute("type", adv.getAdvType()); - } - } catch (Exception failed) { - if (failed instanceof RuntimeException) { - throw (RuntimeException) failed; - } else { - throw new UndeclaredThrowableException(failed, "Failure building document"); - } - } - - return doc; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/SrdiMessageImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/SrdiMessageImpl.java deleted file mode 100644 index 7e890e7a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/SrdiMessageImpl.java +++ /dev/null @@ -1,355 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import net.jxta.document.*; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.protocol.SrdiMessage; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; - - -/** - * SrdiMessageImpl provides the SRDI message binding - */ -public class SrdiMessageImpl extends SrdiMessage { - - /** - * The Log4J debugging category. - */ - private final static Logger LOG = Logger.getLogger(SrdiMessageImpl.class.getName()); - - /** - * PeerID element name - */ - public final static String pidTag = "PID"; - - /** - * scope element name - */ - public final static String scopeTag = "ttl"; - - /** - * Entry element name - */ - public final static String entryTag = "Entry"; - - /** - * Primary Key element name - */ - public final static String pKeyTag = "PKey"; - - /** - * Secondary Key element name - */ - public final static String sKeyTag = "SKey"; - - /** - * Value element name - */ - public final static String valTag = "Value"; - - /** - * Expiration element name - */ - public final static String expirationTag = "Expiration"; - - /** - * Construct an empty doc - */ - public SrdiMessageImpl() { - setScope(PERSISTONLY); - } - - /** - * Construct a doc from InputStream - * - * @param stream the underlying input stream. - * @throws IOException if an I/O error occurs. - * @deprecated It's better to generate the document yourself. This method - * cannot deduce the mime type of the content. - */ - @Deprecated - public SrdiMessageImpl(InputStream stream) throws IOException { - - // We are asked to assume that the message from which this response - // is constructed is an XML document. - XMLDocument doc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, stream); - - readIt(doc); - } - - /** - * Construct from a StructuredDocument - * - * @param root the underlying document - */ - public SrdiMessageImpl(Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getMessageType()) && !getMessageType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - readIt(doc); - } - - /** - * Construct a msg from entries - * - * @param peerid PeerID associated with this message - * @param scope scope @see #PERSISTONLY, #REPLICATE - * @param pKey primary key - * @param entries the entries for this message - */ - public SrdiMessageImpl(PeerID peerid, int scope, String pKey, List entries) { - - setPeerID(peerid); - setScope(scope); - setPrimaryKey(pKey); - setEntries(entries); - } - - /** - * Construct a msg consisting of a single entry - * - * @param peerid PeerID associated with this message - * @param scope scope @see #PERSISTONLY, #REPLICATE - * @param pKey primary key - * @param key the secondary key - * @param value value for the key - * @param expiration expirations for this entry - */ - public SrdiMessageImpl(PeerID peerid, int scope, String pKey, String key, String value, long expiration) { - - setPeerID(peerid); - setScope(scope); - setPrimaryKey(pKey); - addEntry(key, value, expiration); - } - - /** - * Construct a doc from vectors of strings - * - * @param peerid PeerID associated with this message - * @param scope scope @see #PERSISTONLY, #REPLICATE - * @param pKey primary key - * @param entries the entries for this message - */ - public SrdiMessageImpl(String peerid, int scope, String pKey, List entries) { - - PeerID pid; - - try { - pid = (PeerID) IDFactory.fromURI(new URI(peerid)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Invalid PeerID ID in message"); - } - - setPeerID(pid); - setScope(scope); - setPrimaryKey(pKey); - setEntries(entries); - } - - /** - * @param doc the element - */ - public void readIt(XMLElement doc) { - - String key; - String value; - long expiration; - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (elem.getName().equals(pidTag)) { - try { - URI pID = new URI(elem.getTextValue()); - - setPeerID((PeerID) IDFactory.fromURI(pID)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("Invalid PeerID ID in message"); - } - continue; - } - if (elem.getName().equals(pKeyTag)) { - setPrimaryKey(elem.getTextValue()); - } - if (elem.getName().equals(scopeTag)) { - setScope(Integer.parseInt(elem.getTextValue())); - } - - if (elem.getName().equals(entryTag)) { - Attribute keyEl = elem.getAttribute(sKeyTag); - - if (keyEl == null) { - key = "NA"; - } else { - key = keyEl.getValue(); - } - - value = elem.getTextValue(); - if (null != value) { - Attribute expAttr = elem.getAttribute(expirationTag); - - if (expAttr != null) { - String expstr = expAttr.getValue(); - - expiration = Long.parseLong(expstr); - } else { - expiration = -1; - } - SrdiMessage.Entry entry = new SrdiMessage.Entry(key, value, expiration); - - addEntry(entry); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("SrdiMessage Entry with a Null value"); - } - } - } - } - } - - /** - * return a Document representation of this object - * - * @param encodeAs the mime type encoding - * @return document represtation of this object - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - - StructuredTextDocument adv = (StructuredTextDocument) - StructuredDocumentFactory.newStructuredDocument(encodeAs, getMessageType()); - - if (adv instanceof Attributable) { - ((Attributable) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - } - - Element e; - Iterator eachEntry = getEntries().iterator(); - PeerID peerid = getPeerID(); - - if (peerid != null) { - e = adv.createElement(pidTag, peerid.toString()); - adv.appendChild(e); - } - if (getPrimaryKey() != null) { - e = adv.createElement(pKeyTag, getPrimaryKey()); - adv.appendChild(e); - } - if (getScope() > 0) { - e = adv.createElement(scopeTag, Integer.toString(getScope())); - adv.appendChild(e); - } - - while (eachEntry.hasNext()) { - SrdiMessage.Entry entry = (SrdiMessage.Entry) eachEntry.next(); - - if (entry.key == null && entry.value == null) { - // skip bad entries - continue; - } - e = adv.createElement(entryTag, entry.value); - adv.appendChild(e); - ((Attributable) e).addAttribute(expirationTag, Long.toString(entry.expiration)); - ((Attributable) e).addAttribute(sKeyTag, entry.key); - } - return adv; - } - - /** - * returns the document string representation of this object - * - * @return String representation of the of this message type - */ - @Override - public String toString() { - StructuredTextDocument doc = (StructuredTextDocument) getDocument(MimeMediaType.XMLUTF8); - - return doc.toString(); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/TCPAdv.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/TCPAdv.java deleted file mode 100644 index cd15ebad..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/TCPAdv.java +++ /dev/null @@ -1,827 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.protocol; - - -import java.util.Arrays; -import java.util.Enumeration; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.XMLElement; -import net.jxta.protocol.TransportAdvertisement; - - -/** - * Provides configuration parameters for the JXTA TCP Message Transport. - */ -public class TCPAdv extends TransportAdvertisement { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(TCPAdv.class.getName()); - - private static final String CONFIGMODES[] = { "auto", "manual" }; - private static final String INDEXFIELDS[] = {/* none */}; - - private static final String PORT_ELEMENT = "Port"; - private static final String ClientOffTag = "ClientOff"; - private static final String ServerOffTag = "ServerOff"; - private static final String MULTICAST_OFF_TAG = "MulticastOff"; - private static final String FlagsTag = "Flags"; - private static final String PublicAddressOnlyAttr = "PublicAddressOnly"; - - private String configMode = CONFIGMODES[0]; - private String interfaceAddress = null; - private int startPort = -1; - private int listenPort = -1; - private int endPort = -1; - private String publicAddress = null; - private String multicastaddr = null; - private int multicastport = -1; - private int multicastsize = -1; - private boolean clientEnabled = true; - private boolean serverEnabled = true; - private boolean multicastEnabled = true; - private boolean publicAddressOnly = false; - - /** - * Our instantiator - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * {@inheritDoc} - */ - public String getAdvertisementType() { - return TCPAdv.getAdvertisementType(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance() { - return new TCPAdv(); - } - - /** - * {@inheritDoc} - */ - public Advertisement newInstance(net.jxta.document.Element root) { - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - return new TCPAdv((XMLElement) root); - } - } - - /** - * Returns the identifying type of this Advertisement. - * - *

            Note: This is a static method. It cannot be used to determine - * the runtime type of an advertisement. ie. - *

            -     *      Advertisement adv = module.getSomeAdv();
            -     *      String advType = adv.getAdvertisementType();
            -     *  
            - * - *

            This is wrong and does not work the way you might expect. - * This call is not polymorphic and calls - * Advertisement.getAdvertisementType() no matter what the real type of the - * advertisement. - * - * @return String the type of advertisement - */ - public static String getAdvertisementType() { - return "jxta:TCPTransportAdvertisement"; - } - - private TCPAdv() { - setProtocol("tcp"); - } - - private TCPAdv(XMLElement doc) { - this(); - - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Attribute attr = doc.getAttribute(FlagsTag); - - if (attr != null) { - String options = attr.getValue(); - - publicAddressOnly = (options.indexOf(PublicAddressOnlyAttr) != -1); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unhandled Element: " + elem); - } - } - } - - // Sanity Check!!! - if (!Arrays.asList(CONFIGMODES).contains(configMode)) { - throw new IllegalArgumentException("Unsupported configuration mode."); - } - - if ((listenPort < -1) || (listenPort > 65535)) { - throw new IllegalArgumentException("Illegal Listen Port Value"); - } - - if ((startPort < -1) || (startPort > 65535)) { - throw new IllegalArgumentException("Illegal Start Port Value"); - } - - if ((endPort < -1) || (endPort > 65535)) { - throw new IllegalArgumentException("Illegal End Port Value"); - } - - if ((0 == startPort) && (endPort != 0) || (0 != startPort) && (endPort == 0)) { - throw new IllegalArgumentException("Port ranges must both be 0 or non-0"); - } - - if ((-1 == startPort) && (endPort != -1) || (-1 != startPort) && (endPort == -1)) { - throw new IllegalArgumentException("Port ranges must both be -1 or not -1"); - } - - if ((null != publicAddress) && ((-1 != startPort) || (listenPort <= 0))) { - throw new IllegalArgumentException("Dynamic ports not supported with public address port forwarding."); - } - - if (getMulticastState() && (null == getMulticastAddr())) { - throw new IllegalArgumentException("Multicast enabled and no address specified."); - } - - if (getMulticastState() && (-1 == getMulticastPort())) { - throw new IllegalArgumentException("Multicast enabled and no port specified."); - } - - if (getMulticastState() && ((getMulticastPort() <= 0) || (getMulticastPort() > 65536))) { - throw new IllegalArgumentException("Illegal Multicast Port Value"); - } - - if (getMulticastState() && (-1 == getMulticastSize())) { - throw new IllegalArgumentException("Multicast enabled and no size specified."); - } - - if (getMulticastState() && ((getMulticastSize() <= 0) || (getMulticastSize() > 1048575L))) { - throw new IllegalArgumentException("Illegal Multicast datagram size"); - } - - // XXX 20050118 bondolo Some versions apparently don't initialize this field. Eventually make it required. - if (null == getProtocol()) { - setProtocol("tcp"); - } - } - - /** - * {@inheritDoc} - */ - @Override - public String getAdvType() { - return getAdvertisementType(); - } - - /** - * Returns the interface which the TCP transport will use. - * - * @return The interface to use. May be a DNS name or an IP Address. - */ - public String getInterfaceAddress() { - return interfaceAddress; - } - - /** - * Sets the interface which the TCP transport will use. - * - * @param ia The interface to use. May be a DNS name or an IP Address. - */ - public void setInterfaceAddress(String ia) { - if (null != ia) { - ia = ia.trim(); - - if (0 == ia.length()) { - ia = null; - } - } - - this.interfaceAddress = ia; - } - - /** - * Returns the port on which the TCP Transport will listen if configured to - * do so. If a port range is specified then this the preference. Valid - * values are -1, 0 and 1-65535. - * The -1 value is used to signify that there is no port - * preference and any port in range will be used. The 0 - * specifies that the Socket API dynamic port allocation should be used. - * For values 1-65535 the value specifies the required port on - * which the TCP transport will listen. - * - * @return the port - */ - public int getPort() { - return listenPort; - } - - /** - * Sets the port on which the TCP Transport will listen if configured to - * do so. If a port range is specified then this the preference. Valid - * values are -1, 0 and 1-65535. - * The -1 value is used to signify that there is no port - * preference and any port in range will be used. The 0 - * specifies that the Socket API dynamic port allocation should be used. - * For values 1-65535 the value specifies the required port on - * which the TCP transport will listen. - * - * @param port the port on which to listen. - */ - public void setPort(int port) { - listenPort = port; - } - - /** - * Return the lowest port on which the TCP Transport will listen if - * configured to do so. Valid values are -1, 0 and - * 1-65535. The -1 value is used to signify that - * the port range feature should be disabled. The 0 specifies - * that the Socket API dynamic port allocation should be used. For values - * 1-65535 the value must be equal to or less than the value - * used for end port. - * - * @return the lowest port on which to listen. - */ - public int getStartPort() { - return startPort; - } - - /** - * Sets the lowest port on which the TCP Transport will listen if configured - * to do so. Valid values are -1, 0 and - * 1-65535. The -1 value is used to signify that - * the port range feature should be disabled. The 0 specifies - * that the Socket API dynamic port allocation should be used. For values - * 1-65535 the value must be equal to or less than the value - * used for end port. - * - * @param start the lowest port on which to listen. - */ - public void setStartPort(int start) { - startPort = start; - } - - /** - * Return the highest port on which the TCP Transport will listen if - * configured to do so. Valid values are -1, 0 and - * 1-65535. The -1 value is used to signify that - * the port range feature should be disabled. The 0 specifies - * that the Socket API dynamic port allocation should be used. For values - * 1-65535 the value must be equal to or greater than the value - * used for start port. - * - * @return the highest port on which to listen. - */ - public int getEndPort() { - return endPort; - } - - /** - * Sets the highest port on which the TCP Transport will listen if - * configured to do so. Valid values are -1, 0 and - * 1-65535. The -1 value is used to signify that - * the port range feature should be disabled. The 0 specifies - * that the Socket API dynamic port allocation should be used. For values - * 1-65535 the value must be equal to or greater than the value - * used for start port. - * - * @param end the highest port on which to listen. - */ - public void setEndPort(int end) { - endPort = end; - } - - /** - * Determine whether multicast if off or not - * - * @return boolean current multicast state - */ - public boolean getMulticastState() { - return multicastEnabled; - } - - /** - * Enable or disable multicast. - * - * @param newState the desired state. - */ - public void setMulticastState(boolean newState) { - multicastEnabled = newState; - } - - /** - * returns the multicastaddr - * - * @return string multicastaddr - */ - public String getMulticastAddr() { - return multicastaddr; - } - - /** - * set the multicastaddr - * - * @param multicastaddr set multicastaddr - */ - public void setMulticastAddr(String multicastaddr) { - if (null != multicastaddr) { - multicastaddr = multicastaddr.trim(); - - if (0 == multicastaddr.length()) { - multicastaddr = null; - } - } - - this.multicastaddr = multicastaddr; - } - - /** - * returns the multicastport - * - * @return string multicastport - */ - public int getMulticastPort() { - return multicastport; - } - - /** - * set the multicastport - * @param multicastport set multicastport - */ - public void setMulticastPort(int multicastport) { - this.multicastport = multicastport; - } - - /** - * returns the multicastsize - * - * @return integer containting the multicast size - */ - public int getMulticastSize() { - return multicastsize; - } - - /** - * set the multicastsize - * - * @param multicastsize set multicast size - */ - public void setMulticastSize(int multicastsize) { - this.multicastsize = multicastsize; - } - - /** - * Returns the public address - * - * @return string public address - */ - public String getServer() { - return publicAddress; - } - - /** - * Set the public address. That is, a the address of a server socket - * to connect to from the outside. Argument is in the form host:port - * - * @param address address - */ - public void setServer(String address) { - if (null != address) { - address = address.trim(); - - if (0 == address.length()) { - address = null; - } - } - - this.publicAddress = address; - } - - /** - * Returns the configuration for outbound connections. - * - * @return true if outbound connections are allowed otherwise - * false - */ - public boolean isClientEnabled() { - return clientEnabled; - } - - /** - * Sets the configuration for outbound connections. - * - * @param enabled true if outbound connections are allowed otherwise - * false - */ - public void setClientEnabled(boolean enabled) { - clientEnabled = enabled; - } - - /** - * Returns the configuration for inbound connections. - * - * @return true if inbound connections are allowed otherwise - * false - */ - public boolean isServerEnabled() { - return serverEnabled; - } - - /** - * Sets the configuration for inbound connections. - * - * @param enabled true if inbound connections are allowed otherwise - * false - */ - public void setServerEnabled(boolean enabled) { - serverEnabled = enabled; - } - - /** - * returns the config mode. That is, how the user prefers to configure - * the interface address: "auto", "manual" - * - * @return string config mode - */ - public String getConfigMode() { - return configMode; - } - - /** - * set the config mode. That is, how the user prefers to configure - * the interface address: "auto", "manual" - * - * This is just a pure config item. It is never in published advs. The TCP - * transport strips it when it initializes. - * - * @param mode Can be "auto", "manual" other settings will act as the default - * which is "auto". - */ - public void setConfigMode(String mode) { - if (!Arrays.asList(CONFIGMODES).contains(mode)) { - throw new IllegalArgumentException("Unsupported configuration mode."); - } - - configMode = mode; - } - - /** - * Returns the state of whether to only use public address - * @return boolean true if set to use "Public Address Only" - */ - public boolean getPublicAddressOnly() { - return publicAddressOnly; - } - - /** - * Sets the state of whether to only use public address - * @param only true to use "Public Address Only" - */ - public void setPublicAddressOnly(boolean only) { - publicAddressOnly = only; - } - - /** - * {@inheritDoc} - */ - @Override - protected boolean handleElement(Element raw) { - - if (super.handleElement(raw)) { - return true; - } - - XMLElement elem = (XMLElement) raw; - - if (elem.getName().equals(MULTICAST_OFF_TAG)) { - setMulticastState(false); - return true; - } - - if (elem.getName().equals(ClientOffTag)) { - setClientEnabled(false); - return true; - } - - if (elem.getName().equals(ServerOffTag)) { - setServerEnabled(false); - return true; - } - - String value = elem.getTextValue(); - - if ((null == value) || (0 == value.trim().length())) { - return false; - } - - value = value.trim(); - - if (elem.getName().equals("Protocol")) { - setProtocol(value); - return true; - } - - if (PORT_ELEMENT.equals(elem.getName())) { - try { - setPort(Integer.parseInt(value)); - Attribute startAttr = elem.getAttribute("start"); - Attribute endAttr = elem.getAttribute("end"); - - if ((null != startAttr) && (null != endAttr)) { - setStartPort(Integer.parseInt(startAttr.getValue().trim())); - setEndPort(Integer.parseInt(endAttr.getValue().trim())); - } - } catch (NumberFormatException badPort) { - throw new IllegalArgumentException("Illegal port value : " + value); - } - return true; - } - - if (elem.getName().equals("MulticastAddr")) { - setMulticastAddr(value); - return true; - } - - if (elem.getName().equals("MulticastPort")) { - try { - setMulticastPort(Integer.parseInt(value)); - } catch (NumberFormatException badPort) { - throw new IllegalArgumentException("Illegal multicast port value : " + value); - } - return true; - } - - if (elem.getName().equals("MulticastSize")) { - try { - int theMulticastSize = Integer.parseInt(value); - - setMulticastSize(theMulticastSize); - } catch (NumberFormatException badPort) { - throw new IllegalArgumentException("Illegal multicast datagram size : " + value); - } - return true; - } - - if (elem.getName().equals("Server")) { - setServer(value); - return true; - } - - if (elem.getName().equals("InterfaceAddress")) { - setInterfaceAddress(value); - return true; - } - - if (elem.getName().equals("ConfigMode")) { - setConfigMode(value); - return true; - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Document getDocument(MimeMediaType encodeAs) { - StructuredDocument adv = (StructuredDocument) super.getDocument(encodeAs); - - if (!(adv instanceof Attributable)) { - throw new IllegalStateException("Only Attributable document types allowed."); - } - - // XXX 20050118 bondolo Some versions apparently don't initialize this field. Eventually make it required. - if (null == getProtocol()) { - setProtocol("tcp"); - } - - if ((listenPort < -1) || (listenPort > 65535)) { - throw new IllegalStateException("Illegal Listen Port Value"); - } - - if ((startPort < -1) || (startPort > 65535)) { - throw new IllegalStateException("Illegal Start Port Value"); - } - - if ((endPort < -1) || (endPort > 65535)) { - throw new IllegalStateException("Illegal End Port Value"); - } - - if ((0 == startPort) && (endPort != 0) || (0 != startPort) && (endPort == 0)) { - throw new IllegalStateException("Port ranges must both be 0 or non-0"); - } - - if ((-1 == startPort) && (endPort != -1) || (-1 != startPort) && (endPort == -1)) { - throw new IllegalStateException("Port ranges must both be -1 or not -1"); - } - - if ((null != publicAddress) && ((-1 != startPort) || (listenPort <= 0))) { - throw new IllegalStateException("Dynamic ports not supported with public address port forwarding."); - } - - if (getMulticastState() && (null == getMulticastAddr())) { - throw new IllegalStateException("Multicast enabled and no address specified."); - } - - if (getMulticastState() && (-1 == getMulticastPort())) { - throw new IllegalStateException("Multicast enabled and no port specified."); - } - - if (getMulticastState() && ((getMulticastPort() <= 0) || (getMulticastPort() > 65536))) { - throw new IllegalStateException("Illegal Multicast Port Value"); - } - - if (getMulticastState() && (-1 == getMulticastSize())) { - throw new IllegalStateException("Multicast enabled and no size specified."); - } - - if (getMulticastState() && ((getMulticastSize() <= 0) || (getMulticastSize() > 1048575L))) { - throw new IllegalStateException("Illegal Multicast datagram size"); - } - - if (adv instanceof Attributable) { - // Only one flag for now. Easy. - if (publicAddressOnly) { - ((Attributable) adv).addAttribute(FlagsTag, PublicAddressOnlyAttr); - } - } - - Element e11 = adv.createElement("Protocol", getProtocol()); - - adv.appendChild(e11); - - if (!isClientEnabled()) { - Element e19 = adv.createElement(ClientOffTag); - - adv.appendChild(e19); - } - - if (!isServerEnabled()) { - Element e20 = adv.createElement(ServerOffTag); - - adv.appendChild(e20); - } - - if (getConfigMode() != null) { - Element e18 = adv.createElement("ConfigMode", getConfigMode()); - - adv.appendChild(e18); - } - - String interfaceAddr = getInterfaceAddress(); - - if (null != interfaceAddr) { - Element e17 = adv.createElement("InterfaceAddress", interfaceAddr); - - adv.appendChild(e17); - } - - Element e12 = adv.createElement(PORT_ELEMENT, Integer.toString(listenPort)); - - adv.appendChild(e12); - if (adv instanceof Attributable) { - Attributable attrElem = (Attributable) e12; - - if ((-1 != startPort) && (-1 != endPort)) { - attrElem.addAttribute("start", Integer.toString(startPort)); - attrElem.addAttribute("end", Integer.toString(endPort)); - } - } - - String serverAddr = getServer(); - - if (null != serverAddr) { - Element e16 = adv.createElement("Server", serverAddr); - - adv.appendChild(e16); - } - - if (!getMulticastState()) { - Element e19 = adv.createElement(MULTICAST_OFF_TAG); - - adv.appendChild(e19); - } - - if (null != getMulticastAddr()) { - Element e13 = adv.createElement("MulticastAddr", getMulticastAddr()); - - adv.appendChild(e13); - } - - if (-1 != getMulticastPort()) { - Element e14 = adv.createElement("MulticastPort", Integer.toString(getMulticastPort())); - - adv.appendChild(e14); - } - - if (-1 != getMulticastSize()) { - Element e15 = adv.createElement("MulticastSize", Integer.toString(getMulticastSize())); - - adv.appendChild(e15); - } - - return adv; - } - - /** - * {@inheritDoc} - */ - @Override - public String[] getIndexFields() { - return INDEXFIELDS; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/package.html deleted file mode 100644 index 9574bd1c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/protocol/package.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - Provides implementation objects for Advertisments and protocol messages for - the JXTA - Core - and - Standard - Protocols. These classes are responsible for serializing and deserializing - messages and advertisements. - - @see net.jxta.document.Advertisement - @see JXTA Protocols Specification - Overview : Advertisements - @see JXTA Protocols Specification - Advertisements - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/proxy/ProxyService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/proxy/ProxyService.java deleted file mode 100644 index 81e1cd9f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/proxy/ProxyService.java +++ /dev/null @@ -1,1191 +0,0 @@ -/* - * Copyright (c) 2005-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.proxy; - -import net.jxta.discovery.DiscoveryEvent; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.exception.PeerGroupException; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.util.Cache; -import net.jxta.impl.util.CacheEntry; -import net.jxta.impl.util.CacheEntryListener; -import net.jxta.impl.util.LRUCache; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.OutputPipeEvent; -import net.jxta.pipe.OutputPipeListener; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.DiscoveryResponseMsg; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.service.Service; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.IOException; -import java.io.StringReader; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Map; -import java.util.TreeMap; - -import net.jxta.platform.Module; - - -// FIXME: jice@jxta.org - 20020515 -// All public methods are synchronized. -// None of them does anything blocking so that should be about OK, however -// first it is not 100% sure, second eventhough non-blocking, some of these -// operations could take a significant amount of time, which may be unfair -// to other threads that wish to enter for a quick operation. -// Making the locking finer-grain would require significant code rework, so -// it will have to do for now. - -public class ProxyService implements Service, EndpointListener, PipeMsgListener, OutputPipeListener, CacheEntryListener { - - private final static Logger LOG = Logger.getLogger(ProxyService.class.getName()); - - public final static int DEFAULT_THRESHOLD = 2; - public final static int DEFAULT_LIFETIME = 1000 * 60 * 30; // 30 minutes - - /** - * ********************************************************************* - * Define the proxy message tags - * ******************************************************************** - */ - public static final String REQUEST_TAG = "request"; - public static final String RESPONSE_TAG = "response"; - - static final String REQUESTID_TAG = "requestId"; - static final String TYPE_TAG = "type"; - static final String NAME_TAG = "name"; - static final String ID_TAG = "id"; - static final String ARG_TAG = "arg"; - static final String ATTRIBUTE_TAG = "attr"; - static final String VALUE_TAG = "value"; - static final String THRESHOLD_TAG = "threshold"; - static final String ERROR_MESSAGE_TAG = "error"; - static final String PROXYNS = "proxy"; - - /** - * ********************************************************************* - * Define the proxy request types - * ******************************************************************** - */ - public static final String REQUEST_JOIN = "join"; - public static final String REQUEST_CREATE = "create"; - public static final String REQUEST_SEARCH = "search"; - public static final String REQUEST_LISTEN = "listen"; - public static final String REQUEST_CLOSE = "close"; - public static final String REQUEST_SEND = "send"; - - /** - * ********************************************************************* - * Define the proxy response types - * ******************************************************************** - */ - public static final String RESPONSE_SUCCESS = "success"; - public static final String RESPONSE_ERROR = "error"; - public static final String RESPONSE_INFO = "info"; - public static final String RESPONSE_RESULT = "result"; - public static final String RESPONSE_MESSAGE = "data"; - - /** - * ********************************************************************* - * Define the proxy type tags - * ******************************************************************** - */ - public static final String TYPE_PEER = "PEER"; - public static final String TYPE_GROUP = "GROUP"; - public static final String TYPE_PIPE = "PIPE"; - - private PeerGroup group = null; - private ID assignedID = null; - private String serviceName = null; - private String serviceParameter = null; - private EndpointService endpoint = null; - private DiscoveryService discovery = null; - private PipeService pipe = null; - private ModuleImplAdvertisement implAdvertisement = null; - - private final LRUCache searchRequests = new LRUCache(25); // Currently unused - private final Map pipeListeners = new TreeMap(); - - /** - * Pending pipes cost only memory, so it is not a problrm to - * wait for the GC to cleanup things. No CacheEntryListener. - */ - private final Cache pendingPipes = new Cache(200, null); - private Cache resolvedPipes; - - private static Map proxiedGroups = new HashMap(16); - private static Map passwords = new HashMap(16); - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement implAdv) throws PeerGroupException { - this.group = group; - this.assignedID = assignedID; - this.serviceName = assignedID.toString(); - this.implAdvertisement = (ModuleImplAdvertisement) implAdv; - - serviceParameter = group.getPeerGroupID().toString(); - - // Resolved pipes cost non-memory resources, so we need to close - // them as early as we forget them. Need a CacheEntryListener (this). - resolvedPipes = new Cache(200, this); - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring JXME Proxy Service : " + assignedID); - - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group.getPeerGroupName()); - configInfo.append("\n\t\tGroup ID : ").append(group.getPeerGroupID()); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] args) { - - Service needed = group.getEndpointService(); - - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a endpoint service"); - } - - return START_AGAIN_STALLED; - } - - needed = group.getDiscoveryService(); - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a discovery service"); - } - - return START_AGAIN_STALLED; - } - - needed = group.getPipeService(); - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a pipe service"); - } - - return START_AGAIN_STALLED; - } - - endpoint = group.getEndpointService(); - discovery = group.getDiscoveryService(); - pipe = group.getPipeService(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("addListener " + serviceName + serviceParameter); - } - - endpoint.addIncomingMessageListener(this, serviceName, serviceParameter); - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("JXME Proxy Service started."); - } - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - public void stopApp() { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removeListener " + serviceName + serviceParameter); - } - - endpoint.removeIncomingMessageListener(serviceName, serviceParameter); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("JXME Proxy Service stopped."); - } - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * {@inheritDoc} - */ - public ProxyService getInterface() { - return this; - } - - /** - * {@inheritDoc} - */ - public synchronized void processIncomingMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - logMessage(message, LOG); - - Requestor requestor = null; - - try { - // requestor = Requestor.createRequestor(group, message, srcAddr); - // Commented out the above line and added the following three lines. - // The change allows to reduce the traffice going to a JXME peer - // by able to remove ERM completly. As a side effect (severe one) - // JXTA Proxy and JXTA relay need to be running on the same peer. - // This changes should be pulled out as soon as ERM is implemented - // in a more inteligent and effective way so that it doesn't - // have any impact on JXME peers. - EndpointAddress relayAddr = new EndpointAddress("relay", srcAddr.getProtocolAddress(), srcAddr.getServiceName(), - srcAddr.getServiceParameter()); - - requestor = Requestor.createRequestor(group, message, relayAddr, 0); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "could not create requestor", e); - } - } - - String request = popString(REQUEST_TAG, message); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("request = " + request + " requestor " + requestor); - } - - if (request != null && requestor != null) { - if (REQUEST_JOIN.equals(request)) { - handleJoinRequest(requestor, popString(ID_TAG, message), popString(ARG_TAG, message)); - } else if (REQUEST_CREATE.equals(request)) { - handleCreateRequest(requestor, popString(TYPE_TAG, message), popString(NAME_TAG, message), - popString(ID_TAG, message), popString(ARG_TAG, message)); - } else if (REQUEST_SEARCH.equals(request)) { - handleSearchRequest(requestor, popString(TYPE_TAG, message), popString(ATTRIBUTE_TAG, message), - popString(VALUE_TAG, message), popString(THRESHOLD_TAG, message)); - } else if ("listen".equals(request)) { - handleListenRequest(requestor, popString(ID_TAG, message)); - } else if ("close".equals(request)) { - handleCloseRequest(requestor, popString(ID_TAG, message)); - } else if ("send".equals(request)) { - handleSendRequest(requestor, popString(ID_TAG, message), message); - } - } - } - - // Right now there's a security hole: passwd come in clear. - // And not much is done for stopping clients to use the new group - // without being authenticated. We also never get rid of these - // additional groups. - private synchronized void handleJoinRequest(Requestor requestor, String grpId, String passwd) { - - PeerGroup g = proxiedGroups.get(grpId); - - if (g != null) { - if (g == this.group) { - requestor.notifyError("Same group"); - } else if (!passwords.get(grpId).equals(passwd)) { - requestor.notifyError("Incorrect password"); - } else { - requestor.notifySuccess(); - } - return; - } - - try { - g = group.newGroup((PeerGroupID) IDFactory.fromURI(new URI(grpId))); - g.getRendezVousService().startRendezVous(); - } catch (Exception ge) { - requestor.notifyError(ge.getMessage()); - return; - } - - // XXX check membership here. (would work only for single passwd grps) - // For now, assume join is always welcome. - - // So far so good. Try to start a proxy in that grp. - try { - // Fork this proxy into the new grp. - ProxyService proxyService = new ProxyService(); - proxyService.init(g, assignedID, implAdvertisement); - proxyService.startApp(null); - } catch (Exception e) { - requestor.notifyError(e.getMessage()); - return; - } - // set non-deft passwd - passwords.put(grpId, passwd); - proxiedGroups.put(grpId, g); - requestor.notifySuccess(); - } - - private void handleCreateRequest(Requestor requestor, String type, String name, String id, String arg) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("handleCreateRequest type=" + type + " name=" + name + " id=" + id + " arg=" + arg); - } - - if (name == null) { - name = ""; // default name - } - - if (TYPE_PEER.equals(type)) { - PeerAdvertisement adv = createPeerAdvertisement(name, id); - - if (adv != null) { - try { - discovery.publish(adv); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not publish peer advertisement", e); - } - } - requestor.send(adv, RESPONSE_SUCCESS); - } else { - requestor.notifyError("could not create advertisement"); - } - } else if (TYPE_GROUP.equals(type)) { - PeerGroupAdvertisement adv = createGroupAdvertisement(name, id); - - if (adv != null) { - requestor.send(adv, RESPONSE_SUCCESS); - } else { - requestor.notifyError("could not create advertisement"); - } - } else if (TYPE_PIPE.equals(type)) { - if (arg == null) { - arg = PipeService.UnicastType; // default pipe type - } - - PipeAdvertisement adv = createPipeAdvertisement(name, id, arg); - - if (adv != null) { - try { - discovery.publish(adv); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not publish pipe advertisement", e); - } - } - - requestor.send(adv, RESPONSE_SUCCESS); - } else { - requestor.notifyError("could not create advertisement"); - } - } else { - requestor.notifyError("unsupported type"); - } - } - - private void handleSearchRequest(Requestor requestor, String type, String attribute, String value, String threshold) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("handleSearchRequest type=" + type + " attribute=" + attribute + " value=" + value + " threshold=" + threshold); - } - - int discoveryType; - int thr = DEFAULT_THRESHOLD; - try { - thr = Integer.parseInt(threshold); - } catch (NumberFormatException nex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("handleSearchRequest failed to parse threshold " + threshold + ", using default " + DEFAULT_THRESHOLD); - } - } - requestor.setThreshold(thr); - - if (TYPE_PEER.equals(type)) { - discoveryType = DiscoveryService.PEER; - } else if (TYPE_GROUP.equals(type)) { - discoveryType = DiscoveryService.GROUP; - } else { - discoveryType = DiscoveryService.ADV; - } - - Enumeration each = null; - - try { - each = discovery.getLocalAdvertisements(discoveryType, attribute, value); - } catch (IOException e) { - requestor.notifyError("could not search locally"); - } - - int i = 0; - while (each.hasMoreElements() && i < thr) { - Advertisement adv = each.nextElement(); - - // notify the requestor of the result - // FIXME this can be optimized by sending all adv's in a - // single message - requestor.send(adv, RESPONSE_RESULT); - i++; - } - - // start the query - int queryId = discovery.getRemoteAdvertisements(null, discoveryType, attribute, value, thr); - - // register the query - searchRequests.put(queryId, requestor); - } - - /** - * Finds a JXTA Pipe and starts listening to it. - * - * @param requestor the peer sending listen request. - * @param id the id of the Pipe. - */ - private void handleListenRequest(Requestor requestor, String id) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("handleListenRequest id=" + id); - } - - if (id == null) { - requestor.notifyError("Pipe ID not specified"); - return; - } - - PipeAdvertisement pipeAdv = findPipeAdvertisement(null, id, null); - - if (pipeAdv == null) { - requestor.notifyError("Pipe Advertisement not found"); - return; - } - - String pipeId = pipeAdv.getPipeID().toString(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("listen to pipe name=" + pipeAdv.getName() + " id=" + pipeAdv.getPipeID() + " type=" + pipeAdv.getType()); - } - - // check to see if the input pipe already exist - PipeListenerList list = pipeListeners.get(pipeId); - - if (list == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("first listener, create input pipe"); - } - - // create an input pipe - try { - list = new PipeListenerList(pipe.createInputPipe(pipeAdv, this), pipeListeners, pipeId); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "could not listen to pipe", e); - } - requestor.notifyError("could not listen to pipe"); - return; - } - pipeListeners.put(pipeId, list); - } - - // add requestor to list - list.add(requestor); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("add requestor=" + requestor + " id=" + pipeId + " list=" + list); - LOG.fine("publish PipeAdvertisement"); - } - // advertise the pipe locally - try { - discovery.publish(pipeAdv); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not publish pipe advertisement", e); - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("done with listen request"); - } - - // notify requestor of success - requestor.notifySuccess(); - } - - private void handleCloseRequest(Requestor requestor, String id) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("handleCloseRequest id=" + id); - } - - PipeListenerList list = pipeListeners.get(id); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("handleCloseRequest list = " + list); - } - if (list != null) { - list.remove(requestor); - if (list.size() == 0) { - pipeListeners.remove(id); - } - } - - // notify requestor of success - requestor.notifySuccess(); - } - - // Send the given message to the given pipe. - private void sendToPipe(Requestor req, Message mess, OutputPipe out) { - try { - out.send(mess); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("output pipe send end"); - } - // notify requestor of success - req.notifySuccess(); - } catch (IOException e) { - req.notifyError("could not send to pipe"); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "could not send to pipe", e); - } - } - } - - class ClientMessage { - private Requestor requestor; - private Message message; - - public ClientMessage(Requestor req, Message mess) { - requestor = req; - message = mess; - } - - // Send this (pending) message - public void send(OutputPipe out) { - sendToPipe(requestor, message, out); - } - - } - - - class PendingPipe { - private ClientMessage pending; - - public PendingPipe() { - pending = null; - } - - // Just got resolved ! Will send the pending message(s). - public void sendPending(OutputPipe out) { - pending.send(out); - pending = null; - } - - // Enqueue a new pending message. - // (for now we only enqueue 1; others get trashed) - public void enqueue(Requestor req, Message mess) { - if (pending != null) { - return; - } - pending = new ClientMessage(req, mess); - } - } - - private void handleSendRequest(Requestor requestor, String id, Message message) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("handleSendRequest id=" + id); - } - - PipeAdvertisement pipeAdv = findPipeAdvertisement(null, id, null); - - if (pipeAdv == null) { - requestor.notifyError("Could not find pipe"); - return; - } - - String pipeId = pipeAdv.getPipeID().toString(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "send to pipe name=" + pipeAdv.getName() + " id=" + pipeAdv.getPipeID().toString() + " arg=" - + pipeAdv.getType()); - } - - // check if there are local listeners - - PipeListenerList list = pipeListeners.get(pipeId); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("local listener list " + list); - } - - if (list != null && PipeService.UnicastType.equals(pipeAdv.getType())) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("start sending to each requestor"); - } - - list.send(message, pipeId); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("end sending to each requestor"); - } - // notify requestor of success - requestor.notifySuccess(); - return; - } - - // NOTE: This part is NOT exercised by the load test because all - // clients are local. To exercise this part, comment out the - // optimization above. - - // This is not a unicast pipe with at least one local listener - // so we need to fingure out where the message should go. - // This may take a while and has to be done asynchronously... - // Carefull that the resolution can occur synchronously by this - // very thread, and java lock will not prevent re-entry. - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("output pipe creation begin"); - } - - // Look for the pipe in the resolved list. If not found - // look in the pending list or add it there. - OutputPipe out = (OutputPipe) resolvedPipes.get(pipeId); - - if (out != null) { - sendToPipe(requestor, message, out); - return; - } - PendingPipe p = (PendingPipe) pendingPipes.get(pipeId); - - if (p != null) { - p.enqueue(requestor, message); - return; - } - - try { - p = new PendingPipe(); - p.enqueue(requestor, message); - pendingPipes.put(pipeId, p); - pipe.createOutputPipe(pipeAdv, this); - } catch (IOException e) { - pendingPipes.remove(pipeId); - requestor.notifyError("could not create output pipe"); - } - } - - // TBD: DO WE NEED THIS FUNCTIONALITY FOR JXME? - private PeerAdvertisement createPeerAdvertisement(String name, String id) { - PeerAdvertisement adv = null; - - PeerID pid = null; - - if (id != null) { - try { - ID tempId = IDFactory.fromURI(new URI(id)); - - pid = (PeerID) tempId; - } catch (URISyntaxException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not parse peerId from url", e); - } - } catch (ClassCastException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "id was not a peerid", e); - } - } - } - - if (pid == null) { - pid = IDFactory.newPeerID(group.getPeerGroupID()); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("newPeerAdvertisement name=" + name + " id=" + pid.toString()); - } - - try { - // Create a pipe advertisement for this pipe. - adv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(PeerAdvertisement.getAdvertisementType()); - - adv.setPeerID(pid); - adv.setPeerGroupID(group.getPeerGroupID()); - adv.setName(name); - adv.setDescription("Peer Advertisement created for a jxme device"); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "newPeerAdvertisement Exception", e); - } - } - - return adv; - } - - private PeerGroupAdvertisement createGroupAdvertisement(String name, String id) { - PeerGroupAdvertisement adv; - - PeerGroupID gid = null; - - if (id != null) { - try { - ID tempId = IDFactory.fromURI(new URI(id)); - - gid = (PeerGroupID) tempId; - } catch (URISyntaxException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Invalid peergroupId", e); - } - } catch (ClassCastException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "id was not a peergroup id", e); - } - } - } - - if (gid == null) { - gid = IDFactory.newPeerGroupID(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("newPeerGroupAdvertisement name=" + name + " id=" + gid.toString()); - } - - adv = group.getPeerGroupAdvertisement().clone(); - - try { - // Create a PeerGroup Advertisement for this pipe. - adv = (PeerGroupAdvertisement) AdvertisementFactory.newAdvertisement(PeerGroupAdvertisement.getAdvertisementType()); - adv.setName(name); - adv.setPeerGroupID(gid); - adv.setModuleSpecID(PeerGroup.allPurposePeerGroupSpecID); - adv.setDescription("PeerGroup Advertisement created for a jxme device"); - ModuleImplAdvertisement groupImplAdv = group.getAllPurposePeerGroupImplAdvertisement(); - - discovery.publish(groupImplAdv); - discovery.publish(adv); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "newPeerGroupAdvertisement Exception", e); - } - } - - return adv; - } - - private PipeAdvertisement createPipeAdvertisement(String pipeName, String pipeId, String pipeType) { - PipeAdvertisement adv = null; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("newPipeAdvertisement name=" + pipeName + " pipeId=" + pipeId + " pipeType=" + pipeType); - } - - if (pipeType == null || pipeType.length() == 0) { - pipeType = PipeService.UnicastType; - } - - if (pipeId == null) { - pipeId = IDFactory.newPipeID(group.getPeerGroupID()).toString(); - } - - try { - // Create a pipe advertisement for this pipe. - adv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType()); - - adv.setName(pipeName); - adv.setPipeID(IDFactory.fromURI(new URI(pipeId))); - adv.setType(pipeType); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "newPipeAdvertisement Exception", e); - } - } - - return adv; - } - - private PipeAdvertisement findPipeAdvertisement(String name, String id, String arg) { - String attribute, value; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("findPipeAdvertisement name=" + name + " id=" + id + " arg=" + arg); - } - - if (id != null) { - attribute = PipeAdvertisement.IdTag; - value = id; - } else if (name != null) { - attribute = PipeAdvertisement.NameTag; - value = name; - } else { - // the id or the name must be specified - return null; - } - - Enumeration each; - - try { - each = discovery.getLocalAdvertisements(DiscoveryService.ADV, attribute, value); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "IOException in getLocalAdvertisements()", e); - } - return null; - } - - PipeAdvertisement pipeAdv = null; - - while (each.hasMoreElements()) { - Advertisement adv = each.nextElement(); - - // take the first match - if (adv instanceof PipeAdvertisement) { - pipeAdv = (PipeAdvertisement) adv; - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("found PipeAdvertisement = " + pipeAdv); - } - break; - } - } - - return pipeAdv; - } - - public synchronized void discoveryEvent(DiscoveryEvent event) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("discoveryEvent " + event); - } - - Requestor requestor = searchRequests.get(event.getQueryID()); - if (requestor == null) { - return; - } - - DiscoveryResponseMsg response = event.getResponse(); - if (response == null) { - return; - } - - Enumeration each = response.getAdvertisements(); - if (each == null || !each.hasMoreElements()) { - return; - } - // we have a response remove it from the LRUCache - searchRequests.remove(event.getQueryID()); - int i = 0; - - while (each.hasMoreElements() && i < requestor.getThreshold()) { - try { - requestor.send(each.nextElement(), RESPONSE_RESULT); - } catch (Exception e) { - // this should not happen unless a bad result is returned - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Bad result returned by DiscoveryService", e); - } - } - } - } - - /** - * {@inheritDoc} - */ - public synchronized void pipeMsgEvent(PipeMsgEvent event) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("pipeMsgEvent " + event.getPipeID()); - } - - String id = event.getPipeID().toString(); - - PipeListenerList list = pipeListeners.get(id); - - if (list != null) { - Message message = event.getMessage(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("pipeMsgEvent: start sending to each requestor"); - } - list.send(message.clone(), id); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("pipeMsgEvent: end sending to each requestor"); - } - } else { - // there are no listeners, close the input pipe - ((InputPipe) event.getSource()).close(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("close pipe id=" + id); - } - } - } - - /** - * {@inheritDoc} - */ - public synchronized void outputPipeEvent(OutputPipeEvent event) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("outputPipeEvent " + event); - } - PendingPipe p = (PendingPipe) pendingPipes.remove(event.getPipeID()); - - // No one cares (anylonger). TBD should it be removed then?? - if (p == null) { - event.getOutputPipe().close(); - return; - } - - resolvedPipes.put(event.getPipeID(), event.getOutputPipe()); - p.sendPending(event.getOutputPipe()); - } - - private static String popString(String name, Message message) { - MessageElement el = message.getMessageElement(PROXYNS, name); - - if (el != null) { - message.removeMessageElement(el); - return el.toString(); - } - return null; - } - - static class PipeListenerList { - LinkedList list = new LinkedList(); - InputPipe inputPipe = null; - Map pipeListeners = null; - String id = null; - - PipeListenerList(InputPipe inputPipe, Map pipeListeners, String id) { - this.inputPipe = inputPipe; - this.pipeListeners = pipeListeners; - this.id = id; - - if (pipeListeners != null) { - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - LOG.config("number of pipeListeners = " + pipeListeners.size()); - } - } - } - - void add(Requestor requestor) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("add " + requestor + " from " + toString()); - } - - if (!list.contains(requestor)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("requestor add"); - } - list.add(requestor); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("requestor exits already"); - } - } - } - - void remove(Requestor requestor) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("remove " + requestor + " from " + toString()); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removed = " + list.remove(requestor)); - } - - if (list.size() == 0) { - // close the pipe and remove from the listenerList - if (inputPipe != null) { - inputPipe.close(); - } - - if (id != null && pipeListeners != null) { - pipeListeners.remove(id); - } - } - } - - int size() { - int size = list.size(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("size " + size); - } - return size; - } - - private static StringMessageElement sme = new StringMessageElement(RESPONSE_TAG, RESPONSE_MESSAGE, null); - - void send(Message message, String id) { - LOG.fine("send list.size = " + list.size()); - - message.addMessageElement(PROXYNS, sme); - message.addMessageElement(PROXYNS, new StringMessageElement(ID_TAG, id, null)); - - // removed all element that are known to be not needed - Iterator elements = message.getMessageElements(); - - while (elements.hasNext()) { - MessageElement el = elements.next(); - String name = el.getElementName(); - - if (name.startsWith("RendezVousPropagate")) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removeMessageElement " + name); - } - elements.remove(); - } else if (name.startsWith("JxtaWireHeader")) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removeMessageElement " + name); - } - elements.remove(); - } else if (name.startsWith("RdvIncarnjxta")) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removeMessageElement " + name); - } - elements.remove(); - } else if (name.startsWith("JxtaEndpointRouter")) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removeMessageElement " + name); - } - elements.remove(); - } else if (name.startsWith("EndpointRouterMsg")) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removeMessageElement " + name); - } - elements.remove(); - } else if (name.startsWith("EndpointHeaderSrcPeer")) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("removeMessageElement " + name); - } - elements.remove(); - } - } - - Iterator iterator = list.iterator(); - try { - while (iterator.hasNext()) { - Requestor requestor = iterator.next(); - - if (!requestor.send(message.clone())) { - // could not send to listener, remove them from the list - remove(requestor); - } - } - } catch (Exception ex) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Error sending" + ex); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "PipeListenerList size=" + list.size(); - } - } - - protected static void logMessage(Message message, Logger log) { - if (!Logging.SHOW_FINER || !log.isLoggable(Level.FINER)) { - return; - } - - StringBuilder out = new StringBuilder("\n**************** begin ****************\n"); - - Message.ElementIterator elements = message.getMessageElements(); - - while (elements.hasNext()) { - MessageElement element = elements.next(); - - out.append("[").append(elements.getNamespace()).append(",").append(element.getElementName()).append("]=").append(element.toString()).append( - "\n"); - } - - out.append("**************** end ****************\n"); - log.finer(out.toString()); - } - - /** - * {@inheritDoc} - */ - public void purged(CacheEntry ce) { - // A resolved pipe was purged from the cache because we have to - // many pre-resolved pipes hanging around. Close it, because - // it may be holding critical resources that the GC will not be - // sensitive to. - ((OutputPipe) (ce.getValue())).close(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/proxy/Requestor.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/proxy/Requestor.java deleted file mode 100644 index 7d651b8c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/proxy/Requestor.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.proxy; - - -import net.jxta.document.Advertisement; -import net.jxta.endpoint.*; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PeerGroupAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import java.io.IOException; - - -public class Requestor { - private final static Logger LOG = Logger.getLogger(Requestor.class.getName()); - - private PeerGroup group; - private EndpointAddress address; - private MessageElement requestId; - private Messenger messenger; - private int threshold = 1; - - public boolean send(Message message) { - int count; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("send to " + address.toString()); - } - - try { - synchronized (this) { - if ((null == messenger) || messenger.isClosed()) { - messenger = null; - count = 0; - // Add a retry in case we did not obtain a new messenger. - // Due to the heavy polling of the client, it seems that - // we can run in a race condition where we don't get - // a new messenger. - while (count < 2 && messenger == null) { - messenger = group.getEndpointService().getMessengerImmediate(address, null); - if (messenger != null) { - break; - } - try { - Thread.sleep(500); - } catch (InterruptedException e) { - Thread.interrupted(); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Retry getting a messenger" + e); - } - } - count++; - } - - if (null == messenger) { - LOG.warning("Could not get messenger for " + address); - return false; - } - } - } - messenger.sendMessage(message); - } catch (IOException e) { - LOG.log(Level.WARNING, "Could not send message to requestor for " + address, e); - return false; - } - - ProxyService.logMessage(message, LOG); - - return true; - } - - public boolean send(Advertisement adv, String resultType) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("send " + adv); - } - - Message message = new Message(); - - if (resultType == null) { - resultType = ""; - } - setString(message, ProxyService.RESPONSE_TAG, resultType); - - if (requestId != null) { - message.addMessageElement(ProxyService.PROXYNS, requestId); - } - - if (adv instanceof PeerAdvertisement) { - PeerAdvertisement peerAdv = (PeerAdvertisement) adv; - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.TYPE_TAG, ProxyService.TYPE_PEER, null)); - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.NAME_TAG, peerAdv.getName(), null)); - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.ID_TAG, peerAdv.getPeerID().toString(), null)); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("send PeerAdvertisement name=" + peerAdv.getName() + " id=" + peerAdv.getPeerID().toString()); - } - - } else if (adv instanceof PeerGroupAdvertisement) { - PeerGroupAdvertisement groupAdv = (PeerGroupAdvertisement) adv; - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.TYPE_TAG, ProxyService.TYPE_GROUP, null)); - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.NAME_TAG, groupAdv.getName(), null)); - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.ID_TAG, groupAdv.getPeerGroupID().toString(), null)); - - LOG.fine("send GroupAdvertisement name=" + groupAdv.getName() + " id=" + groupAdv.getPeerGroupID().toString()); - - } else if (adv instanceof PipeAdvertisement) { - PipeAdvertisement pipeAdv = (PipeAdvertisement) adv; - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.TYPE_TAG, ProxyService.TYPE_PIPE, null)); - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.NAME_TAG, pipeAdv.getName(), null)); - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.ID_TAG, pipeAdv.getPipeID().toString(), null)); - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.ARG_TAG, pipeAdv.getType(), null)); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "send PipeAdvertisement name=" + pipeAdv.getName() + " id=" + pipeAdv.getPipeID().toString() + " arg=" - + pipeAdv.getType()); - } - - } else { - return false; - } - - return send(message); - } - - public boolean notifySuccess() { - LOG.fine("notifySuccess"); - - Message message = new Message(); - - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.RESPONSE_TAG, ProxyService.RESPONSE_SUCCESS, null)); - - if (requestId != null) { - message.addMessageElement(ProxyService.PROXYNS, requestId); - } - - return send(message); - } - - public boolean notifyError(String errorString) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("notifyError " + errorString); - } - - Message message = new Message(); - - if (requestId != null) { - message.addMessageElement(ProxyService.PROXYNS, requestId); - } - - if (errorString != null && errorString.length() > 0) { - message.addMessageElement(ProxyService.PROXYNS - , - new StringMessageElement(ProxyService.ERROR_MESSAGE_TAG, errorString, null)); - } - - return send(message); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(this + " equals " + obj); - } - - if (obj instanceof Requestor) { - Requestor dest = (Requestor) obj; - - if (address != null && dest.address != null) { - if (dest.address.toString().equals(address.toString())) { - return true; - } - } - } - - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int result = 17; - - return 37 * result + requestId.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "Requestor " + address.toString(); - } - - private Requestor(PeerGroup group, EndpointAddress address, MessageElement requestId) throws IOException { - this.group = group; - this.address = address; - this.requestId = requestId; - } - - public static Requestor createRequestor(PeerGroup group, Message message, EndpointAddress address, int threshold) throws IOException { - Requestor requestor; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("create new Requestor - " + address.toString()); - } - - MessageElement elem = message.getMessageElement(ProxyService.REQUESTID_TAG); - - requestor = new Requestor(group, address, elem); - requestor.setThreshold(threshold); - message.removeMessageElement(elem); - return requestor; - } - - void setThreshold(int threshold) { - this.threshold = threshold; - } - - int getThreshold() { - return threshold; - } - - private void setString(Message message, String tag, String value) { - StringMessageElement sme = new StringMessageElement(tag, value, null); - - message.addMessageElement(ProxyService.PROXYNS, sme); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/PeerConnection.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/PeerConnection.java deleted file mode 100644 index 9d3ff392..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/PeerConnection.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous; - -import java.util.Enumeration; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.OutgoingMessageEvent; -import net.jxta.endpoint.OutgoingMessageEventListener; -import net.jxta.id.ID; -import net.jxta.impl.util.TimeUtils; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import java.util.logging.Logger; - -import net.jxta.impl.endpoint.EndpointUtils; - -/** - * Manages a connection with a remote client or a rendezvous peer. - */ -public abstract class PeerConnection implements OutgoingMessageEventListener { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(PeerConnection.class.getName()); - - protected final PeerGroup group; - protected final EndpointService endpoint; - - /** - * ID of the remote peer. - */ - protected final ID peerid; - - /** - * Cached name of the peer for display purposes. - */ - protected String peerName = null; - - /** - * If true then we believe we are still connected to the remote peer. - */ - protected volatile boolean connected = true; - - /** - * The absolute time in milliseconds at which we expect this connection to - * expire unless renewed. - */ - protected long leasedTil = -1; - - /** - * A cached messenger to be used for sending messages to the remote peer. - */ - protected Messenger cachedMessenger = null; - - /** - * Constructor for the PeerConnection object - * - * @param group group context - * @param endpoint the endpoint service to use for sending messages. - * @param peerid destination peerid - */ - public PeerConnection(PeerGroup group, EndpointService endpoint, ID peerid) { - this.group = group; - this.endpoint = endpoint; - this.peerid = peerid; - - this.peerName = peerid.toString(); - } - - /** - * {@inheritDoc} - *

            - *

            performs PeerID comparison - */ - @Override - public boolean equals(Object obj) { - return obj instanceof PeerConnection && peerid.equals(((PeerConnection) obj).peerid); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return peerid.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return getPeerName() + (connected ? " C" : " c") + " : " + Long.toString(TimeUtils.toRelativeTimeMillis(leasedTil)); - } - - /** - * {@inheritDoc} - */ - public void messageSendFailed(OutgoingMessageEvent event) { - // If it's just a case of queue overflow, ignore it. - if (event.getFailure() == null) { - return; - } - setConnected(false); - } - - /** - * {@inheritDoc} - */ - public void messageSendSucceeded(OutgoingMessageEvent event) {// hurray! - } - - /** - * Get the peer id of the peer associated with this connection. - * - * @return The peer id of the connected peer. - */ - public ID getPeerID() { - return peerid; - } - - /** - * Get the peer name. If the symbolic name is available, use it, - * otherwise returns the peer id. - * - * @return The name of the connected peer. - */ - public String getPeerName() { - return peerName; - } - - /** - * set the peer name. - * - * @param name the peer name - */ - protected void setPeerName(String name) { - peerName = name; - } - - /** - * Set the lease duration in relative milliseconds. - * - * @param leaseDuration the lease duration in relative milliseconds. - */ - protected void setLease(long leaseDuration) { - leasedTil = TimeUtils.toAbsoluteTimeMillis(leaseDuration); - } - - /** - * Time at which the lease will expire in absolute milliseconds. - * - * @return The lease value - */ - public long getLeaseEnd() { - return leasedTil; - } - - /** - * Declare that we are connected for the specified amount of time. - * - * @param leaseDuration The duration of the lease in relative milliseconds. - */ - protected void connect(long leaseDuration) { - setLease(leaseDuration); - setConnected(true); - } - - /** - * Test if the connection is still active. - * - * @return The connected value - */ - public boolean isConnected() { - connected &= (TimeUtils.toRelativeTimeMillis(leasedTil) >= 0); - - return connected; - } - - /** - * Set the connection state. This operation must be idempotent. - * - * @param isConnected The new connected state. Be very careful when - * setting true state without setting a new lease. - */ - public void setConnected(boolean isConnected) { - connected = isConnected; - } - - /** - * Return a messenger suitable for communicating to this peer. - * - * @return a messenger for sending to this peer or null if - * none is available. - * @deprecated Preferred style is to pass the connection object around and - * use the sendMessage method rather than getting the messenger. - */ - @Deprecated - protected Messenger getCachedMessenger() { - - // We don't do the check on existing messenger under synchronization - // hence the temporary variable. - Messenger result = cachedMessenger; - - if ((null == result) || result.isClosed()) { - // We need a new messenger. - PeerAdvertisement padv = null; - - DiscoveryService discovery = group.getDiscoveryService(); - - // Try to see if we have a peer advertisement for this peer. - // This is very likely. - if (null != discovery) { - try { - Enumeration each = discovery.getLocalAdvertisements(DiscoveryService.PEER, "PID", peerid.toString()); - - if (each.hasMoreElements()) { - padv = (PeerAdvertisement) each.nextElement(); - } - } catch (Exception ignored) { - //ignored - } - } - result = getCachedMessenger(padv); - } - - return result; - } - - /** - * Return a messenger suitable for communicating to this peer. - * - * @param padv A peer advertisement which will be used for route hints if - * a new messenger is needed. - * @return a messenger for sending to this peer or null if - * none is available. - */ - protected synchronized Messenger getCachedMessenger(PeerAdvertisement padv) { - if ((null != padv) && !peerid.equals(padv.getPeerID())) { - throw new IllegalArgumentException("Peer Advertisement does not match connection"); - } - - if ((null != padv) && (null != padv.getName())) { - setPeerName(padv.getName()); - } - - // if we have a good messenger then re-use it. - if ((null != cachedMessenger) && !cachedMessenger.isClosed()) { - return cachedMessenger; - } - - cachedMessenger = null; - - if (isConnected()) { - // we only get new messengers while we are connected. It is not - // worth the effort for a disconnected peer. We WILL use an existing - // open messenger if we have one though. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting new cached Messenger for " + peerName); - } - - RouteAdvertisement hint = null; - - if (null != padv) { - hint = EndpointUtils.extractRouteAdv(padv); - } - - EndpointAddress destAddress = new EndpointAddress(peerid, null, null); - - cachedMessenger = endpoint.getMessenger(destAddress, hint); - - if (null == cachedMessenger) { - // no messenger? avoid doing more work. - setConnected(false); - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("connection closed : NOT getting new cached Messenger for " + peerName); - } - } - - return cachedMessenger; - } - - /** - * Send a message to the remote peer. - * - * @param msg the message to send. - * @param service The destination service. - * @param param Parameters for the destination service. - * @return true if the message was queued to be sent, - * otherwise false. A true result does not mean - * that the destination peer will receive the message. - */ - public boolean sendMessage(Message msg, String service, String param) { - Messenger messenger = getCachedMessenger(); - - if (null != messenger) { - messenger.sendMessage(msg, service, param, this); - return true; - } else { - return false; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RdvGreeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RdvGreeter.java deleted file mode 100644 index dab9789d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RdvGreeter.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous; - -import java.io.IOException; - -import net.jxta.endpoint.Message; - -/** - * A Greeter is reponsible for receiving messages from walkers, and push them to - * the service that is listening to them. - * - * @see net.jxta.impl.rendezvous.RdvWalk - * @see net.jxta.impl.rendezvous.RdvWalker - */ -public interface RdvGreeter { - - /** - * Reply to a message received by the Greeter. - * - * @param msg The source message received previously by the Greeter - * @param reply The reply message to be sent to the source of the message. - * @throws IOException when the reply cannot be sent. - */ - public void replyMessage(Message msg, Message reply) throws IOException; - - /** - * Stop the greeter - */ - public void stop(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RdvWalk.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RdvWalk.java deleted file mode 100644 index 86508571..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RdvWalk.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous; - -import net.jxta.endpoint.EndpointListener; -import net.jxta.peergroup.PeerGroup; - -/** - * A Walk implements a particular protocol/behavior policy for sending messages - * through the Rendezvous Peers. A walk strategy is composed of a Walker and a - * Greeter. The Walker is used for sending messages according to the strategy. - * The Greeter receives messages and forwards them to a local listener and may - * provide the ability to continue a walk. - *

            - *

            Each walk is associated with a source service name and service param. - * These are the name and optional parameter of the service that uses the - * RdvWalk. - * - * @see net.jxta.impl.rendezvous.RdvWalker - * @see net.jxta.impl.rendezvous.RdvGreeter - */ -public abstract class RdvWalk { - - /** - * Peergroup in which this walk is running. - */ - protected final PeerGroup group; - - /** - * Intended recipient of messages received as part of this walk. - */ - protected final EndpointListener listener; - - /** - * Service name used by the (client) of this walk. - */ - protected final String srcServiceName; - - /** - * Optional service parameter used by the client of this walk. - */ - protected final String srcServiceParam; - - /** - * Standard constructor - * - * @param group Peergroup in which this walk is running. - * @param listener Intended recipient of messages received as part of this walk. - * @param srcServiceName Service name used by the client of this walk. - * @param srcServiceParam Optional service parameter used by the client of this walk. - */ - public RdvWalk(PeerGroup group, EndpointListener listener, String srcServiceName, String srcServiceParam) { - this.group = group; - this.listener = listener; - this.srcServiceName = srcServiceName; - this.srcServiceParam = srcServiceParam; - } - - /** - * Stop the walk. - */ - public abstract void stop(); - - /** - * Get/Create a walker to be used with this walk. - * - * @return A walker to be used with this walk. {@code null} is returned if - * no greeter is available or the walk has been stopped. - */ - public abstract RdvWalker getWalker(); - - /** - * Get/Create a greeter to be used with this walk. - * - * @return A greeter to be used with this walk. {@code null} is returned if - * no greeter is available or the walk has been stopped. - */ - public abstract RdvGreeter getGreeter(); - - /** - * Return the Peer Group in which this walk occurs. - * - * @return the Peer Group in which this walk occurs. - */ - public PeerGroup getPeerGroup() { - return group; - } - - /** - * Return the listener associated with this walk - * - * @return The listener associated with this walk. - */ - public EndpointListener getListener() { - return listener; - } - - /** - * Return the source Service Name for this walk. - * - * @return The source Service Name for this walk. - */ - public String getServiceName() { - return srcServiceName; - } - - /** - * Return the source Service Param for this walk. - * - * @return The source Service Param for this walk. - */ - public String getServiceParam() { - return srcServiceParam; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RdvWalker.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RdvWalker.java deleted file mode 100644 index 369cd964..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RdvWalker.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous; - -import java.io.IOException; - -import net.jxta.endpoint.Message; -import net.jxta.peer.PeerID; - -/** - * A walker is responsible for implementing the strategy of sending messages for - * a walk. - * - * @see net.jxta.impl.rendezvous.RdvWalk - * @see net.jxta.impl.rendezvous.RdvGreeter - */ -public interface RdvWalker { - - /** - * Walk a message to other Rendezvous peers participating into the walk. An - * initial rendezvous peer can be optionally provided as a hint. - * - * @param destPeer An optional PeerID of the peer which will be the initial - * recipient of the walked message. - * @param msg The message to walk. The message will be modified. - * @param serviceName The name of the service. - * @param serviceParam The parameter of the service. - * @param ttl The maximum TTL of the message. This value may be decreased by - * the Walker implementation, but will never be increased. - * @throws IOException If the message was not sent to any other rendezvous - * peers. - */ - public void walkMessage(PeerID destPeer, Message msg, String serviceName, String serviceParam, int ttl) throws IOException; - - /** - * Stop the walker. Some walkers may implement a strategy that has state and - * this method will stop any internal processing. - */ - public void stop(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousPropagateMessage.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousPropagateMessage.java deleted file mode 100644 index ace7add1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousPropagateMessage.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous; - -import net.jxta.document.Attributable; -import net.jxta.document.Attribute; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.id.UUID.UUIDFactory; -import net.jxta.logging.Logging; - -import java.net.URI; -import java.util.Enumeration; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This class defines the wire format of the Propagation header for messages. - */ -public class RendezVousPropagateMessage { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(RendezVousPropagateMessage.class.getName()); - - public final static String MSG_NAME = "jxta:RendezVousPropagateMessage"; - public static final String MsgIdTag = "MessageId"; - public final static String DestSNameTag = "DestSName"; - public final static String DestSParamTag = "DestSParam"; - public final static String TTLTag = "TTL"; - public final static String PathTag = "Path"; - - /** - * Description of the Field - */ - public final static String Name = "RendezVousPropagate"; - - private UUID msgId = null; - private String destSName = null; - private String destSParam = null; - private int TTL = Integer.MIN_VALUE; - private final Set visited = new LinkedHashSet(); - - /** - * Constructor for the RendezVousPropagateMessage object - */ - public RendezVousPropagateMessage() {} - - /** - * Constructor for the RendezVousPropagateMessage object - * - * @param root The root element of the message. - */ - public RendezVousPropagateMessage(Element root) { - this(); - - if (!XMLElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement"); - } - - XMLElement doc = (XMLElement) root; - - String doctype = doc.getName(); - - String typedoctype = ""; - Attribute itsType = doc.getAttribute("type"); - - if (null != itsType) { - typedoctype = itsType.getValue(); - } - - if (!doctype.equals(MSG_NAME) && !MSG_NAME.equals(typedoctype)) { - throw new IllegalArgumentException( - "Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - - Enumeration elements = doc.getChildren(); - - while (elements.hasMoreElements()) { - XMLElement elem = (XMLElement) elements.nextElement(); - - if (!handleElement(elem)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Unhandled Element: " + elem.toString()); - } - } - } - - // Sanity Check!!! - - if (Integer.MIN_VALUE == getTTL()) { - throw new IllegalArgumentException("TTL value not specified"); - } - - if (null == destSName) { - throw new IllegalArgumentException("Destination service name uninitialized"); - } - - if (null == msgId) { - throw new IllegalArgumentException("Message id uninitialized"); - } - } - - /** - * Process the document - * - * @param raw the document - * @return true if successful - */ - protected boolean handleElement(Element raw) { - - XMLElement elem = (XMLElement) raw; - - if (elem.getName().equals(MsgIdTag)) { - try { - msgId = new UUID(elem.getTextValue().trim()); - } catch (IllegalArgumentException iae) { - // old message id format - try { - msgId = UUIDFactory.newHashUUID(Long.parseLong(elem.getTextValue().trim()), 0); - } catch (NumberFormatException notanumber) { - msgId = UUIDFactory.newHashUUID(elem.getTextValue().trim().hashCode(), 0); - } - } - return true; - } - - if (elem.getName().equals(DestSNameTag)) { - destSName = elem.getTextValue().trim(); - return true; - } - - if (elem.getName().equals(DestSParamTag)) { - destSParam = elem.getTextValue().trim(); - return true; - } - - if (elem.getName().equals(TTLTag)) { - TTL = Integer.parseInt(elem.getTextValue().trim()); - return true; - } - - if (elem.getName().equals(PathTag)) { - addVisited(URI.create(elem.getTextValue().trim())); - return true; - } - - return false; - } - - public UUID getMsgId() { - return msgId; - } - - public void setMsgId(UUID id) { - msgId = id; - } - - public String getDestSName() { - return destSName; - } - - public void setDestSName(String sName) { - this.destSName = sName; - } - - public String getDestSParam() { - return destSParam; - } - - public void setDestSParam(String sParam) { - this.destSParam = sParam; - } - - /** - * Gets the TTL attribute of the RendezVousPropagateMessage object - * - * @return The TTL value - */ - public int getTTL() { - return TTL; - } - - /** - * Sets the TTL attribute of the RendezVousPropagateMessage object - * - * @param ttl The new TTL value - */ - public void setTTL(int ttl) { - TTL = ttl; - } - - /** - * Adds a location to the Visited Set - * - * @param location which was visited. - */ - public void addVisited(URI location) { - visited.add(location); - } - - /** - * Returns true if the specified location is in the visited Set. - * - * @param location The location to check - * @return true if specified location has been visited. - */ - public boolean isVisited(URI location) { - return visited.contains(location); - } - - /** - * Returns the path which this message has travelled. - * - * @return the path this message travelled. - */ - public URI[] getPath() { - return visited.toArray(new URI[visited.size()]); - } - - public Document getDocument(MimeMediaType encodeAs) { - - // Sanity Check!!! - - if (getTTL() <= 0) { - throw new IllegalStateException("TTL value < 1"); - } - - if (null == destSName) { - throw new IllegalStateException("Destination service name uninitialized"); - } - - if (null == msgId) { - throw new IllegalStateException("Message id uninitialized"); - } - - if (visited.isEmpty()) { - throw new IllegalStateException("Message has not visited local peer."); - } - - StructuredDocument doc = StructuredDocumentFactory.newStructuredDocument(encodeAs, MSG_NAME); - - if (doc instanceof XMLDocument) { - ((Attributable) doc).addAttribute("xmlns:jxta", "http://jxta.org"); - ((Attributable) doc).addAttribute("xml:space", "preserve"); - } - - Element e = null; - - e = doc.createElement(MsgIdTag, msgId.toString()); - doc.appendChild(e); - - e = doc.createElement(DestSNameTag, destSName); - doc.appendChild(e); - - if (null != destSParam) { - e = doc.createElement(DestSParamTag, destSParam); - doc.appendChild(e); - } - - e = doc.createElement(TTLTag, Integer.toString(TTL)); - doc.appendChild(e); - - for (Object aVisited : visited) { - e = doc.createElement(PathTag, aVisited.toString()); - doc.appendChild(e); - } - return doc; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousServiceImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousServiceImpl.java deleted file mode 100644 index a1c2103c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousServiceImpl.java +++ /dev/null @@ -1,945 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Random; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.Vector; -import java.util.concurrent.atomic.AtomicBoolean; -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.NoSuchElementException; - -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import java.util.logging.Logger; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.id.ID; -import net.jxta.impl.endpoint.EndpointUtils; -import net.jxta.meter.MonitorResources; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.platform.Module; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.protocol.RouteAdvertisement; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.rendezvous.RendezvousEvent; -import net.jxta.rendezvous.RendezVousStatus; -import net.jxta.rendezvous.RendezvousListener; -import net.jxta.service.Service; - -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.id.UUID.UUIDFactory; -import net.jxta.impl.meter.MonitorManager; -import net.jxta.impl.protocol.RdvConfigAdv; -import net.jxta.impl.rendezvous.adhoc.AdhocPeerRdvService; -import net.jxta.impl.rendezvous.edge.EdgePeerRdvService; -import net.jxta.impl.rendezvous.rdv.RdvPeerRdvService; -import net.jxta.impl.rendezvous.rendezvousMeter.RendezvousMeterBuildSettings; -import net.jxta.impl.rendezvous.rendezvousMeter.RendezvousServiceMonitor; -import net.jxta.impl.rendezvous.rpv.PeerView; -import net.jxta.impl.rendezvous.rpv.PeerViewElement; -import net.jxta.impl.util.TimeUtils; - -/** - * A JXTA {@link net.jxta.rendezvous.RendezVousService} implementation which - * implements the standard JXTA Rendezvous Protocol (RVP). - * - * @see net.jxta.rendezvous.RendezVousService - * @see JXTA Protocols Specification : Rendezvous Protocol - */ -public final class RendezVousServiceImpl implements RendezVousService { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(RendezVousServiceImpl.class.getName()); - - private final static long rdv_watchdog_interval_default = 5 * TimeUtils.AMINUTE; // 5 Minutes - - private static final double DEMOTION_FACTOR = 0.05; - private static final long DEMOTION_MIN_PEERVIEW_COUNT = 5; - private static final long DEMOTION_MIN_CLIENT_COUNT = 3; - protected static final int MAX_MSGIDS = 1000; - - private final static Random random = new Random(); - - private PeerGroup group = null; - private ID assignedID = null; - private ModuleImplAdvertisement implAdvertisement = null; - - public EndpointService endpoint = null; - - private RendezvousServiceMonitor rendezvousServiceMonitor; - - private Timer timer; - private RdvWatchdogTask autoRdvTask = null; - - private long rdv_watchdog_interval = 5 * TimeUtils.AMINUTE; // 5 Minutes - - private final Set eventListeners = Collections.synchronizedSet(new HashSet()); - - /** - * The message IDs we have seen. Used for duplicate removal. - */ - private final List msgIds = new ArrayList(MAX_MSGIDS); - - /** - * Total number of messages which have been received. - */ - private int messagesReceived; - - private RdvConfigAdv.RendezVousConfiguration config = RdvConfigAdv.RendezVousConfiguration.EDGE; - private boolean autoRendezvous = false; - - private String[] savedArgs = null; - - /** - * If {@code true} then a rdv provider change is in progress. - */ - private AtomicBoolean rdvProviderSwitchStatus = new AtomicBoolean(false); - - /** - * The current provider - */ - private RendezVousServiceProvider provider = null; - - /** - * Our interface object. We currently always return the same object. - */ - private final RendezVousServiceInterface rendezvousInterface = new RendezVousServiceInterface(this); - - /** - * Constructor for the RendezVousServiceImpl object - */ - public RendezVousServiceImpl() { - } - - /** - * {@inheritDoc} - */ - public RendezVousService getInterface() { - return rendezvousInterface; - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * Return the assigned ID for this service. - * - * @return The assigned ID for this service. - */ - public ID getAssignedID() { - return assignedID; - } - - /** - * {@inheritDoc} - *

            - *

            Note: it is permissible to pass null as the impl parameter - * when this instance is not being loaded via the module framework. - */ - public synchronized void init(PeerGroup g, ID assignedID, Advertisement impl) { - this.group = g; - this.assignedID = assignedID; - this.implAdvertisement = (ModuleImplAdvertisement) impl; - - RdvConfigAdv rdvConfigAdv = null; - ConfigParams confAdv = group.getConfigAdvertisement(); - - // Get the config. If we do not have a config, we're done; we just keep - // the defaults (edge peer/no auto-rdv) - if (confAdv != null) { - Advertisement adv = null; - - try { - XMLDocument configDoc = (XMLDocument) confAdv.getServiceParam(getAssignedID()); - - if (null != configDoc) { - adv = AdvertisementFactory.newAdvertisement(configDoc); - } - } catch (NoSuchElementException failed) { - //ignored - } - - if (adv instanceof RdvConfigAdv) { - rdvConfigAdv = (RdvConfigAdv) adv; - } - } - - if (null == rdvConfigAdv) { - // Make a new advertisement for defaults. - rdvConfigAdv = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType()); - } - - config = rdvConfigAdv.getConfiguration(); - - autoRendezvous = rdvConfigAdv.getAutoRendezvousCheckInterval() > 0; - - rdv_watchdog_interval = rdvConfigAdv.getAutoRendezvousCheckInterval(); - - // force AD-HOC config for World Peer Group. - if (PeerGroupID.worldPeerGroupID.equals(group.getPeerGroupID())) { - config = RdvConfigAdv.RendezVousConfiguration.AD_HOC; - } - - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring RendezVous Service : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration :"); - configInfo.append("\n\t\tRendezVous : ").append(config); - configInfo.append("\n\t\tAuto RendezVous : ").append(autoRendezvous); - configInfo.append("\n\t\tAuto-RendezVous Reconfig Interval : ").append(rdv_watchdog_interval); - - LOG.config(configInfo.toString()); - } - - // "start" a rendezvous provider switch. We will finish in startApp() - rdvProviderSwitchStatus.set(true); - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] arg) { - endpoint = group.getEndpointService(); - - if (null == endpoint) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - - return START_AGAIN_STALLED; - } - - Service needed = group.getMembershipService(); - - if (null == needed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a membership service"); - } - - return START_AGAIN_STALLED; - } - - // if( !PeerGroupID.worldPeerGroupID.equals(group.getPeerGroupID())) { - // MessageTransport router = endpoint.getMessageTransport( "jxta" ); - // - // if( null == router ) { - // if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - // LOG.warning("Stalled until there is a router "); - // } - // - // return START_AGAIN_STALLED; - // } - // } - // - - timer = new Timer("RendezVousServiceImpl Timer for " + group.getPeerGroupID(), true); - - if (!rdvProviderSwitchStatus.compareAndSet(true, true)) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Unable to start rendezvous provider."); - } - - return -1; - } - - if (RdvConfigAdv.RendezVousConfiguration.AD_HOC == config) { - provider = new AdhocPeerRdvService(group, this); - } else if (RdvConfigAdv.RendezVousConfiguration.EDGE == config) { - provider = new EdgePeerRdvService(group, this); - } else if (RdvConfigAdv.RendezVousConfiguration.RENDEZVOUS == config) { - provider = new RdvPeerRdvService(group, this); - } else { - throw new IllegalStateException("Unrecognized rendezvous configuration"); - } - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING) { - rendezvousServiceMonitor = (RendezvousServiceMonitor) MonitorManager.getServiceMonitor(group - , - MonitorResources.rendezvousServiceMonitorClassID); - provider.setRendezvousServiceMonitor(rendezvousServiceMonitor); - } - - provider.startApp(null); - - rdvProviderSwitchStatus.set(false); - - if (autoRendezvous && !PeerGroupID.worldPeerGroupID.equals(group.getPeerGroupID())) { - startWatchDogTimer(); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Rendezvous Serivce started"); - } - - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - public synchronized void stopApp() { - - // We won't ever release this lock. We are shutting down. There is - // no reason to switch after stopping is begun. - rdvProviderSwitchStatus.set(true); - - if (provider != null) { - provider.stopApp(); - provider = null; - } - - timer.cancel(); - timer = null; - - msgIds.clear(); - eventListeners.clear(); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Rendezvous Serivce stopped"); - } - } - - /** - * {@inheritDoc} - */ - public boolean isRendezVous() { - RendezVousStatus currentStatus = getRendezVousStatus(); - - return (RendezVousStatus.AUTO_RENDEZVOUS == currentStatus) || (RendezVousStatus.RENDEZVOUS == currentStatus); - } - - /** - * @inheritDoc - */ - public RendezVousStatus getRendezVousStatus() { - RendezVousServiceProvider currentProvider = provider; - - if (null == currentProvider) { - return RendezVousStatus.NONE; - } else if (currentProvider instanceof AdhocPeerRdvService) { - return RendezVousStatus.ADHOC; - } else if (currentProvider instanceof EdgePeerRdvService) { - return autoRendezvous ? RendezVousStatus.AUTO_EDGE : RendezVousStatus.EDGE; - } else if (currentProvider instanceof RdvPeerRdvService) { - return autoRendezvous ? RendezVousStatus.AUTO_RENDEZVOUS : RendezVousStatus.RENDEZVOUS; - } else { - return RendezVousStatus.UNKNOWN; - } - } - - /** - * {@inheritDoc} - */ - public boolean setAutoStart(boolean auto) { - return setAutoStart(auto, rdv_watchdog_interval_default); - } - - /** - * {@inheritDoc} - */ - public synchronized boolean setAutoStart(boolean auto, long period) { - rdv_watchdog_interval = period; - boolean old = autoRendezvous; - - autoRendezvous = auto; - - if (auto && !old) { - startWatchDogTimer(); - } else if (old && !auto) { - stopWatchDogTimer(); - } - return old; - } - - /** - * Attempt to connect to the specified rendezvous peer. - * - * @param addr The endpoint address of the rendezvous peer. - * @param hint An optional hint which may be {@code null}. - * @throws IOException If no connection could be made to the specified - * peer. - */ - private void connectToRendezVous(EndpointAddress addr, RouteAdvertisement hint) throws IOException { - RendezVousServiceProvider currentProvider = provider; - - if (currentProvider != null) { - currentProvider.connectToRendezVous(addr, hint); - } else { - throw new IOException("Currently switching rendezvous roles."); - } - } - - /** - * {@inheritDoc} - */ - public void connectToRendezVous(PeerAdvertisement adv) throws IOException { - EndpointAddress addr = new EndpointAddress("jxta", adv.getPeerID().getUniqueValue().toString(), null, null); - connectToRendezVous(addr, EndpointUtils.extractRouteAdv(adv)); - } - - /** - * {@inheritDoc} - */ - public void connectToRendezVous(EndpointAddress addr) throws IOException { - connectToRendezVous(addr, null); - } - - /** - * {@inheritDoc} - */ - public void challengeRendezVous(ID peer, long delay) { - RendezVousServiceProvider currentProvider = provider; - - if (currentProvider != null) { - currentProvider.challengeRendezVous(peer, delay); - } - } - - /** - * {@inheritDoc} - */ - public void disconnectFromRendezVous(ID peerId) { - - RendezVousServiceProvider currentProvider = provider; - - if (currentProvider != null) { - currentProvider.disconnectFromRendezVous(peerId); - } - } - - /** - * {@inheritDoc} - */ - public Enumeration getConnectedRendezVous() { - throw new UnsupportedOperationException("Deprecated opertaion. Use interface if you want to use this operation."); - } - - /** - * {@inheritDoc} - */ - public Enumeration getDisconnectedRendezVous() { - throw new UnsupportedOperationException("Deprecated opertaion. Use interface if you want to use this operation."); - } - - /** - * {@inheritDoc} - */ - public Enumeration getConnectedPeers() { - throw new UnsupportedOperationException("Deprecated opertaion. Use interface if you want to use this operation."); - } - - /** - * {@inheritDoc} - */ - public Vector getConnectedPeerIDs() { - RendezVousServiceProvider currentProvider = provider; - - if (currentProvider != null) { - return currentProvider.getConnectedPeerIDs(); - } - return new Vector(); - } - - /** - * Gets the rendezvousConnected attribute of the RendezVousServiceImpl object - * - * @return true if connected to a rendezvous, false otherwise - */ - public boolean isConnectedToRendezVous() { - RendezVousServiceProvider currentProvider = provider; - return currentProvider != null && currentProvider.isConnectedToRendezVous(); - } - - /** - * {@inheritDoc} - */ - public void startRendezVous() { - try { - if (isRendezVous() || PeerGroupID.worldPeerGroupID.equals(group.getPeerGroupID())) { - return; - } - - if (!rdvProviderSwitchStatus.compareAndSet(false, true)) { - IOException failed = new IOException("Currently switching rendezvous configuration. try again later."); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failed to start rendezvous", failed); - } - throw failed; - } - - // We are at this moment an Edge Peer. First, the current implementation - // must be stopped. - if (provider != null) { - provider.stopApp(); - provider = null; - } - - config = RdvConfigAdv.RendezVousConfiguration.RENDEZVOUS; - - // Now, a new instance of RdvPeerRdvService must be created and initialized. - provider = new RdvPeerRdvService(group, this); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING) { - provider.setRendezvousServiceMonitor(rendezvousServiceMonitor); - } - - provider.startApp(savedArgs); - - rdvProviderSwitchStatus.set(false); - } catch (IOException failure) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to start rendezvous", failure); - } - } - } - - /** - * {@inheritDoc} - */ - public void stopRendezVous() { - - if (!isRendezVous()) { - return; - } - - if (!rdvProviderSwitchStatus.compareAndSet(false, true)) { - IOException failed = new IOException("Currently switching rendezvous configuration. try again later."); - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failed to stop rendezvous", failed); - } - } - - // If the service was already started, then it needs to be stopped, - // and a new instance of an EdgePeerRdvService must be created and initialized and - // started. - - if (provider != null) { - provider.stopApp(); - provider = null; - } - - config = RdvConfigAdv.RendezVousConfiguration.EDGE; - - provider = new EdgePeerRdvService(group, this); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING) { - provider.setRendezvousServiceMonitor(rendezvousServiceMonitor); - } - - provider.startApp(savedArgs); - - rdvProviderSwitchStatus.set(false); - } - - /** - * {@inheritDoc} - */ - public boolean addPropagateListener(String serviceName, String serviceParam, EndpointListener listener) { - if (null == endpoint) { - throw new IllegalStateException("Unable to register propagate listener. (not started)"); - } - - return endpoint.addIncomingMessageListener(listener, serviceName, serviceParam); - } - - /** - * {@inheritDoc} - */ - public EndpointListener removePropagateListener(String serviceName, String serviceParam, EndpointListener listener) { - - if (null == endpoint) { - throw new IllegalStateException("Unable to remove propagate listener. (not started)"); - } - - EndpointListener removed = endpoint.removeIncomingMessageListener(serviceName, serviceParam); - - if ((removed != listener) && (null != removed)) { - // Not the listener we expected. - // It's kind of bad that we removed it at all, but putting it back should fix things. - endpoint.addIncomingMessageListener(removed, serviceName, serviceParam); - return null; - } - return listener; - } - - /** - * {@inheritDoc} - */ - public void propagate(Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { - - RendezVousServiceProvider currentProvider = provider; - - if (null == currentProvider) { - throw new IOException("No RDV provider"); - } - currentProvider.propagate(msg, serviceName, serviceParam, defaultTTL); - } - - /** - * {@inheritDoc} - */ - public void propagate(Enumeration destPeerIDs, Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { - - RendezVousServiceProvider currentProvider = provider; - - if (null == currentProvider) { - throw new IOException("No RDV provider"); - } - currentProvider.propagate(destPeerIDs, msg, serviceName, serviceParam, defaultTTL); - } - - /** - * {@inheritDoc} - */ - public void walk(Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { - RendezVousServiceProvider currentProvider = provider; - - if (null == currentProvider) { - throw new IOException("No RDV provider"); - } - currentProvider.walk(msg, serviceName, serviceParam, defaultTTL); - } - - /** - * {@inheritDoc} - */ - public void walk(Vector destPeerIDs, Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { - - RendezVousServiceProvider currentProvider = provider; - - if (null == currentProvider) { - throw new IOException("No RDV provider"); - } - currentProvider.walk(destPeerIDs, msg, serviceName, serviceParam, defaultTTL); - } - - /** - * {@inheritDoc} - */ - public Vector getLocalWalkView() { - - Vector result = new Vector(); - - PeerView currView = getPeerView(); - - if (null == currView) { - return result; - } - - Collection allPVE = new ArrayList(currView.getView()); - - for (PeerViewElement pve : allPVE) { - RdvAdvertisement adv = pve.getRdvAdvertisement(); - result.add(adv); - } - - return result; - } - - /** - * Returns the PeerView - * - * @return the PeerView - */ - public PeerView getPeerView() { - RendezVousServiceProvider currentProvider = provider; - - if (currentProvider instanceof RdvPeerRdvService) { - return ((RdvPeerRdvService) currentProvider).rpv; - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - public void propagateToNeighbors(Message msg, String serviceName, String serviceParam, int ttl) throws IOException { - RendezVousServiceProvider currentProvider = provider; - - if (null == currentProvider) { - throw new IOException("No RDV provider"); - } - currentProvider.propagateToNeighbors(msg, serviceName, serviceParam, ttl); - } - - /** - * {@inheritDoc} - */ - public void propagateInGroup(Message msg, String serviceName, String serviceParam, int ttl) throws IOException { - RendezVousServiceProvider currentProvider = provider; - if (null == currentProvider) { - throw new IOException("No RDV provider"); - } - currentProvider.propagateInGroup(msg, serviceName, serviceParam, ttl); - } - - /** - * {@inheritDoc} - */ - public final void addListener(RendezvousListener listener) { - eventListeners.add(listener); - } - - /** - * {@inheritDoc} - */ - public final boolean removeListener(RendezvousListener listener) { - return eventListeners.remove(listener); - } - - /** - * Creates a rendezvous event and sends it to all registered listeners. - * - * @param type event type - * @param regarding event peer ID - */ - public final void generateEvent(int type, ID regarding) { - - Iterator eachListener = Arrays.asList(eventListeners.toArray()).iterator(); - RendezvousEvent event = new RendezvousEvent(getInterface(), type, regarding); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Calling listeners for " + event); - } - - while (eachListener.hasNext()) { - RendezvousListener aListener = (RendezvousListener) eachListener.next(); - - try { - aListener.rendezvousEvent(event); - } catch (Throwable ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught Throwable in listener (" + aListener + ")", ignored); - } - } - } - } - - private synchronized void startWatchDogTimer() { - stopWatchDogTimer(); - - autoRdvTask = new RdvWatchdogTask(); - - // Now that we have an Auto-switch flag we only use the higher timeout - // if auto-switch is off . - // Set a watchdog, so the peer will become rendezvous if, after rdv_watchdog_interval it - // still has not connected to any rendezvous peer. - timer.schedule(autoRdvTask, rdv_watchdog_interval, rdv_watchdog_interval); - } - - private synchronized void stopWatchDogTimer() { - RdvWatchdogTask tw = autoRdvTask; - - if (tw != null) { - autoRdvTask.cancel(); - autoRdvTask = null; - } - } - - /** - * Edge Peer mode connection watchdog. - */ - private class RdvWatchdogTask extends TimerTask { - - /** - * {@inheritDoc} - */ - @Override - public synchronized void run() { - try { - int connectedPeers = getConnectedPeerIDs().size(); - - if (!isRendezVous()) { - if (0 == connectedPeers) { - // This peer has not been able to connect to any rendezvous peer. - // become one. - - // become a rendezvous peer. - startRendezVous(); - } - } else { - // Perhaps we can demote ourselves back to an edge - - int peerViewSize = getLocalWalkView().size(); - - boolean isManyElementsInPeerView = (peerViewSize > DEMOTION_MIN_PEERVIEW_COUNT); - boolean isFewClients = (connectedPeers < DEMOTION_MIN_CLIENT_COUNT); - - if (isManyElementsInPeerView) { - if (connectedPeers == 0) { - // Demote ourselves if there are no clients and - // there are more than the minimum rendezvous around - stopRendezVous(); - } else if (isFewClients && (RendezVousServiceImpl.random.nextDouble() < DEMOTION_FACTOR)) { - // Randomly Demote ourselves if there are few clients and - // there are many rendezvous - stopRendezVous(); - } - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in Timer : " + Thread.currentThread().getName(), all); - } - } - } - } - - public boolean isMsgIdRecorded(UUID id) { - - boolean found; - - synchronized (msgIds) { - found = msgIds.contains(id); - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer(id + " = " + found); - } - - return found; - } - - /** - * Checks if a message id has been recorded. - * - * @param id message to record. - * @return {@code true} If message was added otherwise (duplicate) - * {@code false}. - */ - public boolean addMsgId(UUID id) { - - synchronized (msgIds) { - if (isMsgIdRecorded(id)) { - // Already there. Nothing to do - return false; - } - - if (msgIds.size() < MAX_MSGIDS) { - msgIds.add(id); - } else { - msgIds.set((messagesReceived % MAX_MSGIDS), id); - } - - messagesReceived++; - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Added Message ID : " + id); - } - - return true; - } - - public UUID createMsgId() { - return UUIDFactory.newSeqUUID(); - } - - /** - * Get the current provider. This is for debugging purposes only. - * - * @return the provider - * @deprecated This is private for debugging and diagnostics only. - */ - @Deprecated - net.jxta.impl.rendezvous.RendezVousServiceProvider getRendezvousProvider() { - return provider; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousServiceInterface.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousServiceInterface.java deleted file mode 100644 index 518a75e8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousServiceInterface.java +++ /dev/null @@ -1,377 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous; - -import java.util.Collections; -import java.util.Enumeration; -import java.util.Vector; - -import java.io.IOException; -import java.util.Collection; - -import net.jxta.document.Advertisement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.Message; -import net.jxta.id.ID; -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.rendezvous.RendezVousStatus; -import net.jxta.rendezvous.RendezvousListener; -import net.jxta.service.Service; - -import net.jxta.impl.rendezvous.rpv.PeerView; -import net.jxta.platform.Module; - -/** - * This class implements the RendezVousService interface. - */ -public class RendezVousServiceInterface implements RendezVousService { - - RendezVousServiceImpl impl = null; - - /** - * The only authorized constructor. - * - * @param theRealThing the wrapped service - */ - RendezVousServiceInterface(RendezVousServiceImpl theRealThing) { - impl = theRealThing; - } - - /** - * {@inheritDoc} - *

            - *

            Since THIS is already such an object, it returns itself. - * FIXME: it is kind of absurd to have this method part of the - * interface but we do not want to define two levels of Service interface - * just for that. - */ - public Service getInterface() { - return this; - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return impl.getImplAdvertisement(); - } - - /** - * {@inheritDoc} - *

            - *

            FIXME: This is meaningless for the interface object; - * it is there only to satisfy the requirements of the - * interface that we implement. Ultimately, the API should define - * two levels of interfaces: one for the real service implementation - * and one for the interface object. Right now it feels a bit heavy - * to so that since the only different between the two would be - * init() and may-be getName(). - */ - - public void init(PeerGroup pg, ID assignedID, Advertisement impl) { - } - - /** - * {@inheritDoc} - *

            - *

            This is here for temporary class hierarchy reasons. - * it is ALWAYS ignored. By definition, the interface object - * protects the real object's start/stop methods from being called - */ - public int startApp(String[] arg) { - return Module.START_OK; - } - - /** - * {@inheritDoc} - *

            - *

            This is here for temporary class hierarchy reasons. - * it is ALWAYS ignored. By definition, the interface object - * protects the real object's start/stop methods from being called - *

            - *

            This request is currently ignored. - */ - public void stopApp() { - } - - /** - * {@inheritDoc} - */ - public void connectToRendezVous(PeerAdvertisement adv) throws IOException { - impl.connectToRendezVous(adv); - } - - /** - * {@inheritDoc} - */ - public void connectToRendezVous(EndpointAddress addr) throws IOException { - impl.connectToRendezVous(addr); - } - - /** - * {@inheritDoc} - */ - public void challengeRendezVous(ID peer, long delay) { - impl.challengeRendezVous(peer, delay); - } - - /** - * {@inheritDoc} - */ - public void disconnectFromRendezVous(ID rendezVous) { - impl.disconnectFromRendezVous(rendezVous); - } - - /** - * {@inheritDoc} - */ - public Enumeration getConnectedRendezVous() { - Collection connectedPeers = getConnectedPeerIDs(); - - return Collections.enumeration(connectedPeers); - } - - /** - * {@inheritDoc} - */ - public Enumeration getDisconnectedRendezVous() { - Collection empty = Collections.emptyList(); - - return Collections.enumeration(empty); - } - - /** - * This portion is for peers that are RendezVous - */ - - /** - * {@inheritDoc} - */ - public void startRendezVous() { - impl.startRendezVous(); - } - - /** - * {@inheritDoc} - */ - public void stopRendezVous() { - impl.stopRendezVous(); - } - - /** - * {@inheritDoc} - */ - public Enumeration getConnectedPeers() { - Collection connectedPeers = getConnectedPeerIDs(); - - return Collections.enumeration(connectedPeers); - } - - /** - * {@inheritDoc} - */ - public Vector getConnectedPeerIDs() { - return impl.getConnectedPeerIDs(); - } - - /** - * {@inheritDoc} - */ - public boolean addPropagateListener(String serviceName, String serviceParam, EndpointListener listener) { - - return impl.addPropagateListener(serviceName, serviceParam, listener); - } - - /** - * {@inheritDoc} - */ - public EndpointListener removePropagateListener(String serviceName, String serviceParam, EndpointListener listener) { - - return impl.removePropagateListener(serviceName, serviceParam, listener); - } - - /** - * {@inheritDoc} - */ - public void addListener(RendezvousListener listener) { - - impl.addListener(listener); - } - - /** - * {@inheritDoc} - */ - public boolean removeListener(RendezvousListener listener) { - - return impl.removeListener(listener); - } - - /** - * {@inheritDoc} - */ - public void propagate(Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { - - impl.propagate(msg, serviceName, serviceParam, defaultTTL); - } - - /** - * {@inheritDoc} - */ - public void propagate(Enumeration destPeerIDs, Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { - - impl.propagate(destPeerIDs, msg, serviceName, serviceParam, defaultTTL); - } - - /** - * {@inheritDoc} - */ - public void walk(Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { - - impl.walk(msg, serviceName, serviceParam, defaultTTL); - } - - /** - * {@inheritDoc} - */ - public void walk(Vector destPeerIDs, Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { - - impl.walk(destPeerIDs, msg, serviceName, serviceParam, defaultTTL); - } - - /** - * {@inheritDoc} - */ - public Vector getLocalWalkView() { - - return impl.getLocalWalkView(); - } - - /** - * {@inheritDoc} - */ - public void propagateToNeighbors(Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { - impl.propagateToNeighbors(msg, serviceName, serviceParam, defaultTTL); - } - - /** - * {@inheritDoc} - */ - public void propagateInGroup(Message msg, String serviceName, String serviceParam, int defaultTTL) throws IOException { - impl.propagateInGroup(msg, serviceName, serviceParam, defaultTTL); - } - - /** - * {@inheritDoc} - */ - public boolean isConnectedToRendezVous() { - return impl.isConnectedToRendezVous(); - } - - /** - * {@inheritDoc} - */ - public boolean isRendezVous() { - return impl.isRendezVous(); - } - - /** - * @inheritDoc - */ - public RendezVousStatus getRendezVousStatus() { - return impl.getRendezVousStatus(); - } - - /** - * {@inheritDoc} - */ - public boolean setAutoStart(boolean auto) { - return impl.setAutoStart(auto); - } - - /** - * {@inheritDoc} - */ - public boolean setAutoStart(boolean auto, long period) { - return impl.setAutoStart(auto, period); - } - - /** - * Get the current peerview. This is for debugging purposes only. - * - * @return the peer view - * @deprecated This is private for debugging and diagnostics only. - */ - @Deprecated - public PeerView getPeerView() { - return impl.getPeerView(); - } - - /** - * Get the current provider. This is for debugging purposes only. - * - * @return the provider - * @deprecated This is private for debugging and diagnostics only. - */ - @Deprecated - public net.jxta.impl.rendezvous.RendezVousServiceProvider getRendezvousProvider() { - return impl.getRendezvousProvider(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousServiceProvider.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousServiceProvider.java deleted file mode 100644 index 3696b13a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/RendezVousServiceProvider.java +++ /dev/null @@ -1,788 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous; - -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.id.UUID.UUID; -import net.jxta.impl.rendezvous.rendezvousMeter.RendezvousMeter; -import net.jxta.impl.rendezvous.rendezvousMeter.RendezvousMeterBuildSettings; -import net.jxta.impl.rendezvous.rendezvousMeter.RendezvousServiceMonitor; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.PeerAdvertisement; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * This abstract class must be extended for all RendezVous Service providers - * that are managed by RendezVousServiceImpl. - *

            - * Implementors of providers are responsible for using appropriate - * synchronization. The RendezvousServiceImpl provides synchronization control - * only only those methods which involve changing the active provider. - */ -public abstract class RendezVousServiceProvider implements EndpointListener { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(RendezVousServiceProvider.class.getName()); - - protected static final String PropSName = "JxtaPropagate"; - - protected static final String RDV_MSG_NAMESPACE_NAME = "jxta"; - - protected final String PropPName; - protected final String PROP_HDR_ELEMENT_NAME; - - /** - * Maximum TTL we will allow for propagation and repropagation issued by - * this peer. - */ - protected int MAX_TTL; - - protected final PeerGroup group; - protected final RendezVousServiceImpl rdvService; - protected boolean closed = false; - - private PeerAdvertisement cachedPeerAdv = null; - private int cachedPeerAdvModCount = -1; - private XMLDocument cachedPeerAdvDoc = null; - - protected RendezvousServiceMonitor rendezvousServiceMonitor = null; - protected RendezvousMeter rendezvousMeter = null; - - /** - * - * @param group the peergroup - * @param rdvService the implementation - */ - protected RendezVousServiceProvider(PeerGroup group, RendezVousServiceImpl rdvService) { - - this.group = group; - this.rdvService = rdvService; - - PropPName = this.group.getPeerGroupID().getUniqueValue().toString(); - PROP_HDR_ELEMENT_NAME = RendezVousPropagateMessage.Name + PropPName; - } - - /** - * {@inheritDoc} - *

            - * EndpointListener for the JxtaPropagate/ - */ - public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - RendezVousPropagateMessage propHdr = checkPropHeader(msg); - - if (null != propHdr) { - // Get the destination real destination of the message - String sName = propHdr.getDestSName(); - String sParam = propHdr.getDestSParam(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Processing " + msg + "(" + propHdr.getMsgId() + ") for " + sName + "/" + sParam + " from " + srcAddr); - } - - // Check if we have a local listener for this message - processReceivedMessage(msg, propHdr, srcAddr, new EndpointAddress(dstAddr, sName, sParam)); - } - } - - protected XMLDocument getPeerAdvertisementDoc() { - PeerAdvertisement newPadv; - - synchronized (this) { - newPadv = group.getPeerAdvertisement(); - int newModCount = newPadv.getModCount(); - - if ((cachedPeerAdv != newPadv) || (cachedPeerAdvModCount != newModCount)) { - cachedPeerAdv = newPadv; - cachedPeerAdvModCount = newModCount; - } else { - newPadv = null; - } - - if (null != newPadv) { - cachedPeerAdvDoc = (XMLDocument) cachedPeerAdv.getDocument(MimeMediaType.XMLUTF8); - } - } - - return cachedPeerAdvDoc; - } - - /** - * Supply arguments and starts this service if it hadn't started by itself. - *

            - * Currently this service starts by itself and does not expect arguments. - * @return 0 if successful - * @param arg argument params - */ - protected int startApp(String[] arg) { - - // All propagated messages originated by RendezvousService.propagate are handled by the - // rendezvous service before being delivered to their local recipient. - // This includes: - // messages delivered here via netWorkPropagation. Therefore the rdv service has a special - // endpointService listener for that purpose. - // messages delivered here by rdv-to-rdv walk. - try { - if (!rdvService.endpoint.addIncomingMessageListener(this, PropSName, PropPName)) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Cannot register the propagation listener (already registered)"); - } - - return -1; - } - } catch (Exception ez1) { - // Not much we can do here. - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Failed registering the endpoint listener", ez1); - } - - return -1; - } - - try { - // Update the peeradv with our status - if (rdvService.isRendezVous()) { - XMLDocument params = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - XMLElement e = params.createElement("Rdv", Boolean.TRUE.toString()); - - params.appendChild(e); - group.getPeerAdvertisement().putServiceParam(rdvService.getAssignedID(), params); - } else { - group.getPeerAdvertisement().removeServiceParam(rdvService.getAssignedID()); - } - } catch (Exception ignored) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not update Rdv Params in Peer Advertisement", ignored); - } - } - - return Module.START_OK; - } - - /** - * Ask this service to stop. - */ - protected void stopApp() { - EndpointListener shouldbeMe = rdvService.endpoint.removeIncomingMessageListener(PropSName, PropPName); - - if ((null != shouldbeMe) && (this != shouldbeMe)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unregistered listener was not as expected." + this + " != " + shouldbeMe); - } - } - - // Update the peeradv. We are not a rdv. - group.getPeerAdvertisement().removeServiceParam(rdvService.getAssignedID()); - } - - /** - * Set the RendezvousServiceMonitor. The RendezvousServiceMonitor is used to - * meter the activity of the RendezvousService. - * - * @param rendezvousServiceMonitor The monitor. - * @see net.jxta.impl.meter.MonitorManager - */ - public void setRendezvousServiceMonitor(RendezvousServiceMonitor rendezvousServiceMonitor) { - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING) { - this.rendezvousServiceMonitor = rendezvousServiceMonitor; - - if (rendezvousServiceMonitor != null) { - this.rendezvousMeter = rendezvousServiceMonitor.getRendezvousMeter(); - } - } - } - - /** - * Resets the local idea of the lease to the specified value. - * As a result a lease response must be sought and obtained within the - * new specified delay or the rdv is considered disconnected. - * - * @param peer The peer to be challenged - * @param delay The delay - */ - public abstract void challengeRendezVous(ID peer, long delay); - - /** - * Attempt to connect to the specified rendezvous peer. - * - * @param addr The endpoint address of the rendezvous peer. - * @param hint An optional hint which may be {@code null}. - * @throws IOException If no connection could be made to the specified peer. - */ - public abstract void connectToRendezVous(EndpointAddress addr, Object hint) throws IOException; - - /** - * Remove a RendezVousService point. - * - * @param peerID the PeerId of the RendezVous to disconnect from. - */ - public abstract void disconnectFromRendezVous(ID peerID); - - /** - * Returns the peers that are currently connected to this peer. - * - * @return The peers that are currently connected to this peer. - */ - public abstract Vector getConnectedPeerIDs(); - - /** - * Propagates a message onto as many peers on the local network - * as possible. Typically the message will go to all the peers to - * which at least one endpoint transport can address without using - * the router. - *

            - * This method sends the message to all peers, rendezvous peers and - * edge peer. This method of propagation is very expensive and should - * not be frequently used. When rendezvous peers are used in order to - * cache index of data, it is more efficient to use the walk() method. - *

            - * Only a single HOP at a time is performed. Messages are always - * delivered to the destination handler on arrival. This handler - * is responsible for repropagating further, if deemed appropriate. - *

            - * Loop and TTL control are performed automatically. - *

            - * Messages can be propagated via this method for the first time or - * can be re-propagated by re-using a message that came in via propagation. - * In the later case, the TTL and loop detection parameters CANNOT be - * re-initialized. If one wants to "re-propagate" a message with a new TTL - * and blank gateways list one must generate a completely new message. - * This limits the risk of accidental propagation storms, although they - * can always be engineered deliberately. - *

            - * Note: The original msg is not modified and may be reused upon return. - * - * @param msg is the message to propagate. - * @param serviceName is the name of the service - * @param serviceParam is the parameter of the service - * @param initialTTL is the maximum TTL of the message (note that the Rendezvous - * Service implementation is free to decrease that value. - * @throws java.io.IOException if an io error occurs - */ - public abstract void propagate(Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException; - - /** - * Propagates a message onto as many peers on the local network - * as possible. Typically the message will go to all the peers to - * which at least one endpoint transport can address without using - * the router. - *

            - * This method sends the message to all peers, rendezvous peers and - * edge peer. This method of propagation is very expensive and should - * not be frequently used. When rendezvous peers are used in order to - * cache index of data, it is more efficient to use the walk() method. - *

            - * Only a single HOP at a time is performed. Messages are always - * delivered to the destination handler on arrival. This handler - * is responsible for repropagating further, if deemed appropriate. - *

            - * Loop and TTL control are performed automatically. - *

            - * Messages can be propagated via this method for the first time or - * can be re-propagated by re-using a message that came in via propagation. - * In the later case, the TTL and loop detection parameters CANNOT be - * re-initialized. If one wants to "re-propagate" a message with a new TTL - * and blank gateways list one must generate a completely new message. - * This limits the risk of accidental propagation storms, although they - * can always be engineered deliberately. - *

            - * Note: The original msg is not modified and may be reused upon return. - * - * @param destPeerIds An enumeration of the peers that are recipients of the - * propagated message. - * @param msg is the message to propagate. - * @param serviceName is the name of the service - * @param serviceParam is the parameter of the service - * @param initialTTL is the maximum TTL of the message (note that the Rendezvous - * Service implementation is free to decrease that value. - * @throws java.io.IOException if an io error occurs - */ - public abstract void propagate(Enumeration destPeerIds, Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException; - - /** - * Propagates a message onto as many peers on the local network - * as possible. Typically the message will go to all the peers to - * which at least one endpoint transport can address without using - * the router. - *

            - * Only a single HOP at a time is performed. Messages are always - * delivered to the destination handler on arrival. This handler - * is responsible for repropagating further, if deemed appropriate. - *

            - * Loop and TTL control are performed automatically. - *

            - * Messages can be propagated via this method for the first time or - * can be re-propagated by re-using a message that came in via propagation. - * In the later case, the TTL and loop detection parameters CANNOT be - * re-initialized. If one wants to "re-propagate" a message with a new TTL - * and blank gateways list one must generate a completely new message. - * This limits the risk of accidental propagation storms, although they - * can always be engineered deliberately. - *

            - * Note: The original msg is not modified and may be reused upon return. - * - * @param msg is the message to propagate. - * @param serviceName is the name of the service - * @param serviceParam is the parameter of the service - * @param initialTTL is the maximum TTL of the message (note that the Rendezvous - * Service implementation is free to decrease that value. - * @throws java.io.IOException if an io error occurs - */ - public abstract void propagateToNeighbors(Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException; - - /** - * Return true if connected to a rendezvous. - * - * @return true if connected to a rendezvous, false otherwise - */ - public abstract boolean isConnectedToRendezVous(); - - /** - ** The following API is related to the new Rendezvous Peer walk mechanism. - ** - **/ - - /** - * Walk a message through the rendezvous peers of the network: only - * rendezvous peers will receive the message. - *

            - * Only a single HOP at a time is performed. Messages are always - * delivered to the destination handler on arrival. This handler - * is responsible for repropagating further, if deemed appropriate. - *

            - * Loop and TTL control are performed automatically. - *

            - * Messages can be propagated via this method for the first time or - * can be re-propagated by re-using a message that came in via propagation. - * In the later case, the TTL and loop detection parameters CANNOT be - * re-initialized. If one wants to "re-propagate" a message with a new TTL - * and blank gateways list one must generate a completely new message. - * This limits the risk of accidental propagation storms, although they - * can always be engineered deliberately. - *

            - * Note: The original msg is not modified and may be reused upon return. - * - * @param msg is the message to walk. - * @param serviceName is the name of the service - * @param serviceParam is the parameter of the service - * @param initialTTL is the maximum TTL of the message (note that the Rendezvous - * Service implementation is free to decrease that value. - * @throws IOException when walking the message is impossible (network failure) - */ - public abstract void walk(Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException; - - /** - * Walk a message through the rendezvous peers of the network: only - * rendezvous peers will receive the message. - *

            - * Only a single HOP at a time is performed. Messages are always - * delivered to the destination handler on arrival. This handler - * is responsible for repropagating further, if deemed appropriate. - *

            - * Loop and TTL control are performed automatically. - *

            - * Messages can be propagated via this method for the first time or - * can be re-propagated by re-using a message that came in via propagation. - * In the later case, the TTL and loop detection parameters CANNOT be - * re-initialized. If one wants to "re-propagate" a message with a new TTL - * and blank gateways list one must generate a completely new message. - * This limits the risk of accidental propagation storms, although they - * can always be engineered deliberately. - *

            - * Note: The original msg is not modified and may be reused upon return. - * - * @param destPeerIDs is a Vector of PeerID of the peers which are receiving - * first the walker. Note that each entry in the Vector will create its own - * walker. - * @param msg is the message to walk. - * @param serviceName is the name of the service - * @param serviceParam is the parameter of the service - * @param initialTTL is the maximum TTL of the message (note that the Rendezvous - * Service implementation is free to decrease that value. - * @throws IOException when walking the message is impossible (network failure) - */ - public abstract void walk(Vector destPeerIDs, Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException; - - /** - * Process a propagated message. - * - * @param message the message received - * @param propHdr the message header - * @param srcAddr the source address - * @param dstAddr the message destination addreess - */ - protected void processReceivedMessage(Message message, RendezVousPropagateMessage propHdr, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - EndpointListener listener = rdvService.endpoint.getIncomingMessageListener(dstAddr.getServiceName(), - dstAddr.getServiceParameter()); - - if (listener != null) { - // We have a local listener for this message. Deliver it. - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Calling local listener " + listener.getClass().getName() + " for [" + dstAddr.getServiceName() + "/" - + dstAddr.getServiceParameter() + "] with " + message + " (" + propHdr.getMsgId() + ")"); - } - - rdvService.endpoint.processIncomingMessage(message, srcAddr, dstAddr); - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.receivedMessageProcessedLocally(); - } - - // NOTE: this this is only beneficial in ad-hoc mode with no rendezvous infrastructure - // with one node bridging two networks (2 interfaces). - // This should not be a base feature but rather an ad-hoc mode only feature, as - // it creates additional unnecessary traffic leading to message loss and latency. - // hamada disabling this feature as a general base functionality. - // This should addressed differently in Ad-hoc mode, where a multi-homed node would - // repropagate when more than one interface is enabled - - // Pass the message on. - // repropagate(message, propHdr, dstAddr.getServiceName(), dstAddr.getServiceParameter()); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No message listener found for ServiceName :" + dstAddr.getServiceName() + " ServiceParam :" - + dstAddr.getServiceParameter()); - } - } - } - - /** - * Responsible for forwarding received messages to the rest of the network - * as appropriate. This generally only makes sense for multicast or - * broadcast scenarios. - * - * @param msg the message to be repropagated. - * @param propHdr It's current propagation header. - * @param serviceName The destination service. - * @param serviceParam The destination service parameter. - */ - protected abstract void repropagate(Message msg, RendezVousPropagateMessage propHdr, String serviceName, String serviceParam); - - public abstract void propagateInGroup(Message msg, String serviceName, String serviceParam, int ttl) throws IOException; - - /** - * Propagates the message via endpoint propagation (multicast/broadcast) on - * all Message Transports. - *

            - * Note: The original msg is not modified and may be reused upon return. - * - * @param msg The message to be propagated. - * @param propHdr It's current propagation header. - * @throws java.io.IOException if an io error occurs - */ - protected void sendToNetwork(Message msg, RendezVousPropagateMessage propHdr) throws IOException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Endpoint propagating " + msg + " (" + propHdr.getMsgId() + ")"); - } - - rdvService.endpoint.propagate(msg, PropSName, PropPName); - } - - /** - * Convenience method for constructing an endpoint address from an id - * - * @param destPeer peer id - * @param serv the service name (if any) - * @param parm the service param (if any) - * @return endpointAddress for this peer id. - */ - protected static EndpointAddress mkAddress(String destPeer, String serv, String parm) { - ID asID; - try { - asID = IDFactory.fromURI(new URI(destPeer)); - } catch (URISyntaxException caught) { - throw new IllegalArgumentException(caught.getMessage()); - } - - return mkAddress(asID, serv, parm); - } - - /** - * Convenience method for constructing an endpoint address from an id - * - * @param destPeer peer id - * @param serv the service name (if any) - * @param parm the service param (if any) - * @return endpointAddress for this peer id. - */ - protected static EndpointAddress mkAddress(ID destPeer, String serv, String parm) { - EndpointAddress addr = new EndpointAddress(RDV_MSG_NAMESPACE_NAME, destPeer.getUniqueValue().toString(), serv, parm); - return addr; - } - - /** - * Get propagate header from the message. - * - * @param msg The source message. - * @return The message's propagate header if any, otherwise null. - */ - protected RendezVousPropagateMessage getPropHeader(Message msg) { - - MessageElement elem = msg.getMessageElement(RDV_MSG_NAMESPACE_NAME, PROP_HDR_ELEMENT_NAME); - - if (elem == null) { - return null; - } - - try { - StructuredDocument asDoc = StructuredDocumentFactory.newStructuredDocument(elem); - return new RendezVousPropagateMessage(asDoc); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not get prop header of " + msg, failed); - } - IllegalArgumentException failure = new IllegalArgumentException("Could not get prop header of " + msg); - failure.initCause(failed); - throw failure; - } - } - - /** - * Check and updates the header message element - * - * @param msg the message to check - * @return an upadate message - */ - protected RendezVousPropagateMessage checkPropHeader(Message msg) { - RendezVousPropagateMessage propHdr; - - try { - propHdr = getPropHeader(msg); - if (null == propHdr) { - // No header. Discard the message - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Discarding " + msg + " -- missing propagate header."); - } - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.invalidMessageReceived(); - } - return null; - } - } catch (Exception failure) { - // Bad header. Discard the message - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Discarding " + msg + " -- bad propagate header.", failure); - } - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.invalidMessageReceived(); - } - return null; - } - // Look at the Propagate header if any and check for loops. - // Do not remove it; we do not have to change it yet, and we have - // do look at it at different places and looking costs less on - // incoming elements than on outgoing. - - // TTL detection. A message arriving with TTL <= 0 should not even - // have been sent. Kill it. - - if (propHdr.getTTL() <= 0) { - // This message is dead on arrival. Drop it. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Discarding " + msg + "(" + propHdr.getMsgId() + ") -- dead on arrival (TTl=" + propHdr.getTTL() + ")."); - } - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.receivedDeadMessage(); - } - return null; - } - - if (!rdvService.addMsgId(propHdr.getMsgId())) { - // We already received this message - discard - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Discarding " + msg + "(" + propHdr.getMsgId() + ") -- feedback."); - } - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.receivedDuplicateMessage(); - } - return null; - } - - // Loop detection - if (propHdr.isVisited(group.getPeerID().toURI())) { - // Loop is detected - discard. - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Discarding " + msg + "(" + propHdr.getMsgId() + ") -- loopback."); - } - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.receivedLoopbackMessage(); - } - return null; - } - // Message is valid - return propHdr; - } - - protected RendezVousPropagateMessage updatePropHeader(Message msg, RendezVousPropagateMessage propHdr, String serviceName, String serviceParam, int initialTTL) { - - boolean newHeader = false; - - if (null == propHdr) { - propHdr = newPropHeader(serviceName, serviceParam, initialTTL); - newHeader = true; - } else { - if (null == updatePropHeader(propHdr, initialTTL)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("TTL expired for " + msg + " (" + propHdr.getMsgId() + ") TTL=" + propHdr.getTTL()); - } - return null; - } - } - - XMLDocument propHdrDoc = (XMLDocument) propHdr.getDocument(MimeMediaType.XMLUTF8); - MessageElement elem = new TextDocumentMessageElement(PROP_HDR_ELEMENT_NAME, propHdrDoc, null); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine((newHeader ? "Added" : "Updated") + " prop header for " + msg + " (" + propHdr.getMsgId() + ") TTL = " - + propHdr.getTTL()); - } - - msg.replaceMessageElement(RDV_MSG_NAMESPACE_NAME, elem); - return propHdr; - } - - /** - * Adds a propagation header to the given message with the given default - * TTL. Also adds this peer to the path recorded in the message. - * - * @param serviceName the service name - * @param serviceParam the parameter - * @param initialTTL initial TTL - * @return a updated message with the proper TTL and ID - */ - private RendezVousPropagateMessage newPropHeader(String serviceName, String serviceParam, int initialTTL) { - - RendezVousPropagateMessage propHdr = new RendezVousPropagateMessage(); - - propHdr.setTTL(initialTTL); - propHdr.setDestSName(serviceName); - propHdr.setDestSParam(serviceParam); - - UUID msgID = rdvService.createMsgId(); - - propHdr.setMsgId(msgID); - rdvService.addMsgId(msgID); - - // Add this peer to the path. - propHdr.addVisited(group.getPeerID().toURI()); - - return propHdr; - } - - /** - * Updates the propagation header of the message. Also adds this peer to the - * path recorded in the message. Returns true if the message should be - * repropagated, false otherwise. - * - * @param propHdr The propHdr for the message. - * @param maxTTL The maximum TTL which will be allowed. - * @return The updated propagate header if the message should be - * repropagated otherwise null. - */ - private RendezVousPropagateMessage updatePropHeader(RendezVousPropagateMessage propHdr, int maxTTL) { - - int msgTTL = propHdr.getTTL(); - URI me = group.getPeerID().toURI(); - - int useTTL = msgTTL; - - if (!propHdr.isVisited(me)) { - // only reduce TTL if message has not previously visited us. - useTTL--; - } - - // ensure TTL does not exceed maxTTL - useTTL = Math.min(useTTL, maxTTL); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Updating propagation header (" + propHdr.getMsgId() + ") TTL: " + msgTTL + "-->" + useTTL); - } - - propHdr.setTTL(useTTL); - - // Add this peer to the path. - propHdr.addVisited(me); - - // If message came in with TTL one or less, it was last trip. It can not go any further. - return (useTTL <= 0) ? null : propHdr; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/StdRendezVousService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/StdRendezVousService.java deleted file mode 100644 index f0c1153f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/StdRendezVousService.java +++ /dev/null @@ -1,520 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.endpoint.EndpointUtils; -import net.jxta.impl.rendezvous.rdv.RdvPeerRdvService; -import net.jxta.impl.rendezvous.rendezvousMeter.RendezvousMeterBuildSettings; -import net.jxta.impl.rendezvous.rpv.PeerViewElement; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.List; -import java.util.Timer; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Base class for providers which implement the JXTA Standard Rendezvous - * Protocol. - * - * @see JXTA Protocols Specification : Rendezvous Protocol - */ -public abstract class StdRendezVousService extends RendezVousServiceProvider { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(StdRendezVousService.class.getName()); - - public final static String ConnectRequest = "Connect"; - public final static String DisconnectRequest = "Disconnect"; - public final static String ConnectedPeerReply = "ConnectedPeer"; - public final static String ConnectedLeaseReply = "ConnectedLease"; - public final static String ConnectedRdvAdvReply = "RdvAdvReply"; - - /** - * Default Maximum TTL. - */ - protected static final int DEFAULT_MAX_TTL = 200; - - protected final String pName; - protected final String pParam; - - /** - * The registered handler for messages using the Standard Rendezvous - * Protocol. - * - * @see JXTA Protocols Specification : Rendezvous Protocol - */ - private StdRdvProtocolListener handler; - - protected final Timer timer; - - /** - * Interface for listeners to : <assignedID>/ - */ - protected interface StdRdvProtocolListener extends EndpointListener {} - - /** - * Constructor - * - * @param group the PeerGroup - * @param rdvService the parent rendezvous service - */ - protected StdRendezVousService(PeerGroup group, RendezVousServiceImpl rdvService) { - - super(group, rdvService); - - MAX_TTL = DEFAULT_MAX_TTL; - - pName = rdvService.getAssignedID().toString(); - pParam = group.getPeerGroupID().getUniqueValue().toString(); - - timer = new Timer("StdRendezVousService Timer for " + group.getPeerGroupID(), true); - } - - /** - * {@inheritDoc} - */ - protected int startApp(String[] argv, StdRdvProtocolListener handler) { - - this.handler = handler; - - rdvService.endpoint.addIncomingMessageListener(handler, pName, null); - - return super.startApp(argv); - } - - /** - * {@inheritDoc} - */ - @Override - public void stopApp() { - EndpointListener shouldbehandler = rdvService.endpoint.removeIncomingMessageListener(pName, null); - - if (handler != shouldbehandler) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Unregistered listener was not as expected." + handler + " != " + shouldbehandler); - } - } - - timer.cancel(); - - super.stopApp(); - } - - /** - * {@inheritDoc} - */ - @Override - public void processReceivedMessage(Message message, RendezVousPropagateMessage propHdr, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - if (srcAddr.getProtocolName().equalsIgnoreCase("jxta")) { - String idstr = ID.URIEncodingName + ":" + ID.URNNamespace + ":" + srcAddr.getProtocolAddress(); - - ID peerid; - try { - peerid = IDFactory.fromURI(new URI(idstr)); - } catch (URISyntaxException badID) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Bad ID in message", badID); - } - return; - } - - if (!group.getPeerID().equals(peerid)) { - PeerConnection pConn = getPeerConnection(peerid); - - if (null == pConn) { - PeerViewElement pve; - - if (this instanceof RdvPeerRdvService) { - // cheap hack.... - pve = ((RdvPeerRdvService) this).rpv.getPeerViewElement(peerid); - } else { - pve = null; - } - - if (null == pve) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received " + message + " (" + propHdr.getMsgId() + ") from unrecognized peer : " + peerid); - } - - propHdr.setTTL(Math.min(propHdr.getTTL(), 3)); // will be reduced during repropagate stage. - - // FIXME 20040503 bondolo need to add tombstones so that we don't end up spamming disconnects. - if (rdvService.isRendezVous() || (getPeerConnections().length > 0)) { - // edge peers with no rdv should not send disconnect. - sendDisconnect(peerid, null); - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received " + message + " (" + propHdr.getMsgId() + ") from " + pve); - } - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received " + message + " (" + propHdr.getMsgId() + ") from " + pConn); - } - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received " + message + " (" + propHdr.getMsgId() + ") from loopback."); - } - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received " + message + " (" + propHdr.getMsgId() + ") from network -- repropagating with TTL 2"); - } - - propHdr.setTTL(Math.min(propHdr.getTTL(), 3)); // will be reduced during repropagate stage. - } - super.processReceivedMessage(message, propHdr, srcAddr, dstAddr); - } - - /** - * {@inheritDoc} - */ - @Override - public void propagate(Enumeration destPeerIDs, Message msg, String serviceName, String serviceParam, int initialTTL) { - msg = msg.clone(); - int useTTL = Math.min(initialTTL, MAX_TTL); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Propagating " + msg + "(TTL=" + useTTL + ") to :" + "\n\tsvc name:" + serviceName + "\tsvc params:" - + serviceParam); - } - - RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, useTTL); - - if (null != propHdr) { - int numPeers = 0; - - try { - while (destPeerIDs.hasMoreElements()) { - ID dest = destPeerIDs.nextElement(); - - try { - PeerConnection pConn = getPeerConnection(dest); - - // TODO: make use of PeerView connections as well - if (null == pConn) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + " (" + propHdr.getMsgId() + ") to " + dest); - } - - EndpointAddress addr = mkAddress(dest, PropSName, PropPName); - - Messenger messenger = rdvService.endpoint.getMessengerImmediate(addr, null); - - if (null != messenger) { - try { - messenger.sendMessage(msg); - } catch (IOException ignored) { - continue; - } - } else { - continue; - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + " (" + propHdr.getMsgId() + ") to " + pConn); - } - - if (pConn.isConnected()) { - pConn.sendMessage(msg.clone(), PropSName, PropPName); - } else { - continue; - } - } - numPeers++; - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed to send " + msg + " (" + propHdr.getMsgId() + ") to " + dest); - } - } - } - } finally { - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToPeers(numPeers); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Propagated " + msg + " (" + propHdr.getMsgId() + ") to " + numPeers + " peers."); - } - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Declined to send " + msg + " ( no propHdr )"); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void propagateToNeighbors(Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException { - msg = msg.clone(); - int useTTL = Math.min(initialTTL, MAX_TTL); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Propagating " + msg + "(TTL=" + useTTL + ") to neighbors to :" + "\n\tsvc name:" + serviceName+ "\tsvc params:" + serviceParam); - } - - RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, useTTL); - - if (null != propHdr) { - try { - sendToNetwork(msg, propHdr); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToNeighbors(); - } - } catch (IOException failed) { - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToNeighborsFailed(); - } - - throw failed; - } - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void repropagate(Message msg, RendezVousPropagateMessage propHdr, String serviceName, String serviceParam) { - msg = msg.clone(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Repropagating " + msg + " (" + propHdr.getMsgId() + ")"); - } - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.receivedMessageRepropagatedInGroup(); - } - - try { - propHdr = updatePropHeader(msg, propHdr, serviceName, serviceParam, MAX_TTL); - - if (null != propHdr) { - // Note (hamada): This is an unnecessary operation, and serves - // no purpose other than the additional loads it imposes on the - // rendezvous. Local subnet network operations should be (and are) - // sufficient to achieve the goal. - // sendToEachConnection(msg, propHdr); - sendToNetwork(msg, propHdr); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No propagate header, declining to repropagate " + msg + ")"); - } - } - } catch (Exception ez1) { - // Not much we can do - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - if (propHdr != null) { - LOG.log(Level.WARNING, "Failed to repropagate " + msg + " (" + propHdr.getMsgId() + ")", ez1); - } else { - LOG.log(Level.WARNING, "Could to repropagate " + msg, ez1); - } - } - } - } - - /** - * Returns the peer connection or null if not present. - * - * @param id the node ID - * @return PeerConnection the peer connection or null if not present. - */ - public abstract PeerConnection getPeerConnection(ID id); - - /** - * Returns an array of the current peer connections. - * - * @return An array of the current peer connections. - */ - protected abstract PeerConnection[] getPeerConnections(); - - /** - * Sends to all connected peers. - *

            - * Note: The original msg is not modified and may be reused upon return. - * - * @param msg The message to be sent. - * @param propHdr The propagation header associated with the message. - * @return the number of nodes the message was sent to - */ - protected int sendToEachConnection(Message msg, RendezVousPropagateMessage propHdr) { - List peers = Arrays.asList(getPeerConnections()); - int sentToPeers = 0; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + "(" + propHdr.getMsgId() + ") to " + peers.size() + " peers."); - } - - for (PeerConnection pConn : peers) { - // Check if this rendezvous has already processed this propagated message. - if (!pConn.isConnected()) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Skipping " + pConn + " for " + msg + "(" + propHdr.getMsgId() + ") -- disconnected."); - } - // next! - continue; - } - - if (propHdr.isVisited(pConn.getPeerID().toURI())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Skipping " + pConn + " for " + msg + "(" + propHdr.getMsgId() + ") -- already visited."); - } - // next! - continue; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + "(" + propHdr.getMsgId() + ") to " + pConn); - } - - if (pConn.sendMessage(msg.clone(), PropSName, PropPName)) { - sentToPeers++; - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sent " + msg + "(" + propHdr.getMsgId() + ") to " + sentToPeers + " of " + peers.size() + " peers."); - } - - return sentToPeers; - } - - /** - * Sends a disconnect message to the specified peer. - * - * @param peerid The peer to be disconnected. - * @param padv The peer to be disconnected. - */ - protected void sendDisconnect(ID peerid, PeerAdvertisement padv) { - - Message msg = new Message(); - - // The request simply includes the local peer advertisement. - try { - msg.replaceMessageElement("jxta", new TextDocumentMessageElement(DisconnectRequest, getPeerAdvertisementDoc(), null)); - - EndpointAddress addr = mkAddress(peerid, null, null); - - RouteAdvertisement hint = null; - - if (null != padv) { - hint = EndpointUtils.extractRouteAdv(padv); - } - - Messenger messenger = rdvService.endpoint.getMessengerImmediate(addr, hint); - - if (null == messenger) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not get messenger for " + peerid); - } - return; - } - - messenger.sendMessage(msg, pName, pParam); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "sendDisconnect failed", e); - } - } - } - - /** - * Sends a disconnect message to the specified peer. - * - * @param pConn The peer to be disconnected. - */ - protected void sendDisconnect(PeerConnection pConn) { - - Message msg = new Message(); - - // The request simply includes the local peer advertisement. - try { - msg.replaceMessageElement("jxta", new TextDocumentMessageElement(DisconnectRequest, getPeerAdvertisementDoc(), null)); - - pConn.sendMessage(msg, pName, pParam); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "sendDisconnect failed", e); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/adhoc/AdhocPeerRdvService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/adhoc/AdhocPeerRdvService.java deleted file mode 100644 index 8d7b0d37..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/adhoc/AdhocPeerRdvService.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.rendezvous.adhoc; - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.id.ID; -import net.jxta.impl.protocol.RdvConfigAdv; -import net.jxta.impl.rendezvous.RendezVousPropagateMessage; -import net.jxta.impl.rendezvous.RendezVousServiceImpl; -import net.jxta.impl.rendezvous.RendezVousServiceProvider; -import net.jxta.impl.rendezvous.rendezvousMeter.RendezvousMeterBuildSettings; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.ConfigParams; -import net.jxta.rendezvous.RendezvousEvent; - -import java.io.IOException; -import java.util.Enumeration; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * A JXTA {@link net.jxta.rendezvous.RendezVousService} implementation which - * implements the ad hoc portion of the standard JXTA Rendezvous Protocol (RVP). - * - * @see net.jxta.rendezvous.RendezVousService - * @see JXTA Protocols Specification : Rendezvous Protocol - */ -public class AdhocPeerRdvService extends RendezVousServiceProvider { - - /** - * Log4J Logger - */ - private final static transient Logger LOG = Logger.getLogger(AdhocPeerRdvService.class.getName()); - - /** - * Default Maximum TTL. This is minimum needed to bridge networks. - */ - private static final int DEFAULT_MAX_TTL = 2; - - /** - * Constructor - * - * @param g the peergroup - * @param rdvService the rendezvous service - */ - public AdhocPeerRdvService(PeerGroup g, RendezVousServiceImpl rdvService) { - - super(g, rdvService); - - ConfigParams confAdv = g.getConfigAdvertisement(); - - // Get the config. If we do not have a config, we're done; we just keep - // the defaults (edge peer/no auto-rdv) - if (confAdv != null) { - Advertisement adv = null; - - try { - XMLDocument configDoc = (XMLDocument) confAdv.getServiceParam(rdvService.getAssignedID()); - - if (null != configDoc) { - // XXX 20041027 backwards compatibility - configDoc.addAttribute("type", RdvConfigAdv.getAdvertisementType()); - - adv = AdvertisementFactory.newAdvertisement(configDoc); - } - } catch (java.util.NoSuchElementException ignored) {// ignored - } - - if (adv instanceof RdvConfigAdv) { - RdvConfigAdv rdvConfigAdv = (RdvConfigAdv) adv; - - MAX_TTL = (-1 != rdvConfigAdv.getMaxTTL()) ? rdvConfigAdv.getMaxTTL() : DEFAULT_MAX_TTL; - } else { - MAX_TTL = DEFAULT_MAX_TTL; - } - } else { - MAX_TTL = DEFAULT_MAX_TTL; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("RendezVous Service is initialized for " + g.getPeerGroupID() + " as an ad hoc peer. "); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected int startApp(String[] arg) { - - super.startApp(arg); - - // The other services may not be fully functional but they're there - // so we can start our subsystems. - // As for us, it does not matter if our methods are called between init - // and startApp(). - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.startEdge(); - } - - // we are nominally an edge peer - rdvService.generateEvent(RendezvousEvent.BECAMEEDGE, group.getPeerID()); - - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void stopApp() { - - if (closed) { - return; - } - - closed = true; - - super.stopApp(); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.stopEdge(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Vector getConnectedPeerIDs() { - - return new Vector(0); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isConnectedToRendezVous() { - // It's as connected as it's ever going to get.... - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public void connectToRendezVous(EndpointAddress addr, Object hint) throws IOException { - - throw new UnsupportedOperationException("Not supported by ad hoc"); - } - - /** - * {@inheritDoc} - */ - @Override - public void challengeRendezVous(ID peer, long delay) { - - throw new UnsupportedOperationException("Not supported by ad hoc"); - } - - /** - * {@inheritDoc} - */ - @Override - public void disconnectFromRendezVous(ID peerId) { - - throw new UnsupportedOperationException("Not supported by ad hoc"); - } - - /** - * {@inheritDoc} - */ - @Override - public void propagate(Message msg, String serviceName, String serviceParam, int ttl) throws IOException { - - ttl = Math.min(ttl, MAX_TTL); - - RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, ttl); - - if (null != propHdr) { - sendToNetwork(msg, propHdr); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToGroup(); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void propagateInGroup(Message msg, String serviceName, String serviceParam, int ttl) throws IOException { - - ttl = Math.min(ttl, MAX_TTL); - - RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, ttl); - - if (null != propHdr) { - sendToNetwork(msg, propHdr); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToGroup(); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void propagate(Enumeration destPeerIDs, Message msg, String serviceName, String serviceParam, int ttl) { - - ttl = Math.min(ttl, MAX_TTL); - - RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, ttl); - - if (null != propHdr) { - int numPeers = 0; - - try { - while (destPeerIDs.hasMoreElements()) { - ID dest = destPeerIDs.nextElement(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + " to client " + dest); - } - - EndpointAddress addr = mkAddress(dest, PropSName, PropPName); - - Messenger messenger = rdvService.endpoint.getMessenger(addr); - - if (null != messenger) { - try { - messenger.sendMessage(msg); - numPeers++; - } catch (IOException failed) {// ignored - } - } - } - } finally { - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToPeers(numPeers); - } - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void propagateToNeighbors(Message msg, String serviceName, String serviceParam, int ttl) throws IOException { - - ttl = Math.min(ttl, MAX_TTL); - - RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, ttl); - - if (null != propHdr) { - try { - sendToNetwork(msg, propHdr); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToNeighbors(); - } - } catch (IOException failed) { - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToNeighborsFailed(); - } - - throw failed; - } - } - } - - /** - * {@inheritDoc} - *

            - * The definition of walk says that we should forward the message to the - * most appropriate peer. Since we don't make any effort keep track of other - * peers we don't have anywhere to send the message. - */ - @Override - public void walk(Message msg, String serviceName, String serviceParam, int ttl) throws IOException { - // Do nothing. Really. - } - - /** - * {@inheritDoc} - *

            - * Unlike the undirected walk we are told where to send the message so we - * deliver it as requested. - */ - @Override - public void walk(Vector destPeerIDs, Message msg, String serviceName, String serviceParam, int ttl) throws IOException { - - propagate(destPeerIDs.elements(), msg, serviceName, serviceParam, ttl); - } - - /** - * {@inheritDoc} - */ - @Override - protected void repropagate(Message msg, RendezVousPropagateMessage propHdr, String serviceName, String serviceParam) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Repropagating " + msg + " (" + propHdr.getMsgId() + ")"); - } - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.receivedMessageRepropagatedInGroup(); - } - - try { - propHdr = updatePropHeader(msg, propHdr, serviceName, serviceParam, MAX_TTL); - - if (null != propHdr) { - sendToNetwork(msg, propHdr); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No propagate header, declining to repropagate " + msg + ")"); - } - } - } catch (Exception ez1) { - // Not much we can do - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - if (propHdr != null) { - LOG.log(Level.WARNING, "Failed to repropagate " + msg + " (" + propHdr.getMsgId() + ")", ez1); - } else { - LOG.log(Level.WARNING, "Could to repropagate " + msg, ez1); - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/edge/EdgePeerRdvService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/edge/EdgePeerRdvService.java deleted file mode 100644 index 1c22185d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/edge/EdgePeerRdvService.java +++ /dev/null @@ -1,866 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.edge; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TimerTask; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import java.io.IOException; -import java.net.URISyntaxException; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.MessageTransport; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.endpoint.relay.RelayReferralSeedingManager; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.platform.Module; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RouteAdvertisement; -import net.jxta.rendezvous.RendezvousEvent; - -import net.jxta.impl.protocol.RdvConfigAdv; -import net.jxta.impl.rendezvous.PeerConnection; -import net.jxta.impl.rendezvous.RendezVousPropagateMessage; -import net.jxta.impl.rendezvous.RendezVousServiceImpl; -import net.jxta.impl.rendezvous.RendezVousServiceProvider; -import net.jxta.impl.rendezvous.StdRendezVousService; -import net.jxta.impl.rendezvous.rendezvousMeter.RendezvousConnectionMeter; -import net.jxta.impl.rendezvous.rendezvousMeter.RendezvousMeterBuildSettings; -import net.jxta.impl.rendezvous.rpv.PeerviewSeedingManager; -import net.jxta.impl.util.SeedingManager; -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.util.URISeedingManager; - -/** - * A JXTA {@link net.jxta.rendezvous.RendezVousService} implementation which - * implements the client portion of the standard JXTA Rendezvous Protocol (RVP). - * - * @see net.jxta.rendezvous.RendezVousService - * @see JXTA Protocols Specification : Rendezvous Protocol - */ -public class EdgePeerRdvService extends StdRendezVousService { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(EdgePeerRdvService.class.getName()); - - /** - * Interval in milliseconds at which we will check our rendezvous connection. - */ - private final static long MONITOR_INTERVAL = 15 * TimeUtils.ASECOND; - - /** - * Number of rendezvous we will try to connect to. - */ - private final int MAX_RDV_CONNECTIONS = 2; - - /** - * The default amount of time we will attempt to renew a lease before it - * expires. - */ - private long LEASE_MARGIN = 5 * TimeUtils.AMINUTE; - - /** - * Our source for rendezvous server seeds. - */ - private final SeedingManager seedingManager; - - /** - * Our current seeds. - */ - private final List seeds = new ArrayList(); - - /** - * Our current connections with RendezVous peers. - */ - private final Map rendezVous = Collections.synchronizedMap(new HashMap()); - - /** - * Standard Constructor - * - * @param group Description of Parameter - * @param rdvService Description of Parameter - */ - public EdgePeerRdvService(PeerGroup group, RendezVousServiceImpl rdvService) { - - super(group, rdvService); - - Advertisement adv = null; - ConfigParams confAdv = group.getConfigAdvertisement(); - - // Get the config. If we do not have a config, we're done; we just keep - // the defaults (edge peer/no auto-rdv) - if (confAdv != null) { - adv = confAdv.getSvcConfigAdvertisement(rdvService.getAssignedID()); - } - - RdvConfigAdv rdvConfigAdv; - - if (!(adv instanceof RdvConfigAdv)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Creating new RdvConfigAdv for defaults."); - } - - rdvConfigAdv = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType()); - } else { - rdvConfigAdv = (RdvConfigAdv) adv; - } - - if (-1 != rdvConfigAdv.getMaxTTL()) { - MAX_TTL = rdvConfigAdv.getMaxTTL(); - } - - if (0 != rdvConfigAdv.getLeaseMargin()) { - LEASE_MARGIN = rdvConfigAdv.getLeaseMargin(); - } - - String serviceName = rdvService.getAssignedID().toString() + group.getPeerGroupID().getUniqueValue().toString(); - if (PeerGroupID.worldPeerGroupID.equals(group.getParentGroup().getPeerGroupID())) { - URISeedingManager uriSeedingManager; - - if (rdvConfigAdv.getProbeRelays()) { - uriSeedingManager = new RelayReferralSeedingManager(rdvConfigAdv.getAclUri(), rdvConfigAdv.getUseOnlySeeds(), group, serviceName); - } else { - uriSeedingManager = new URISeedingManager(rdvConfigAdv.getAclUri(), rdvConfigAdv.getUseOnlySeeds(), group, serviceName); - } - - for (URI aSeeder : Arrays.asList(rdvConfigAdv.getSeedingURIs())) { - uriSeedingManager.addSeedingURI(aSeeder); - } - - for (URI aSeed : Arrays.asList(rdvConfigAdv.getSeedRendezvous())) { - uriSeedingManager.addSeed(aSeed); - } - - this.seedingManager = uriSeedingManager; - } else { - this.seedingManager = new PeerviewSeedingManager(rdvConfigAdv.getAclUri(), group, group.getParentGroup(), serviceName); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("RendezVous Service is initialized for " + group.getPeerGroupID() + " as an Edge peer."); - } - } - - /** - * Listener for - *

            - * <assignedID> - */ - private class StdRdvEdgeProtocolListener implements StdRendezVousService.StdRdvProtocolListener { - - /** - * {@inheritDoc} - */ - public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + group.getPeerGroupID() + "] processing " + msg); - } - - if ((msg.getMessageElement(RendezVousServiceProvider.RDV_MSG_NAMESPACE_NAME, ConnectedPeerReply) != null) - || (msg.getMessageElement(RendezVousServiceProvider.RDV_MSG_NAMESPACE_NAME, ConnectedRdvAdvReply) != null)) { - processConnectedReply(msg); - } - - if (msg.getMessageElement(RendezVousServiceProvider.RDV_MSG_NAMESPACE_NAME, DisconnectRequest) != null) { - processDisconnectRequest(msg); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - protected int startApp(String[] arg) { - - super.startApp(arg, new StdRdvEdgeProtocolListener()); - - // The other services may not be fully functional but they're there - // so we can start our subsystems. - // As for us, it does not matter if our methods are called between init - // and startApp(). - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.startEdge(); - } - - rdvService.generateEvent(RendezvousEvent.BECAMEEDGE, group.getPeerID()); - - timer.schedule(new MonitorTask(), 0, MONITOR_INTERVAL); - - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void stopApp() { - - if (closed) { - return; - } - - closed = true; - - seedingManager.stop(); - - disconnectFromAllRendezVous(); - - super.stopApp(); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.stopEdge(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Vector getConnectedPeerIDs() { - return new Vector(rendezVous.keySet()); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isConnectedToRendezVous() { - return !rendezVous.isEmpty(); - } - - /** - * {@inheritDoc} - */ - @Override - public void connectToRendezVous(EndpointAddress addr, Object hint) { - if (seedingManager instanceof URISeedingManager) { - URISeedingManager uriseed = (URISeedingManager) seedingManager; - - if (hint instanceof RouteAdvertisement) { - uriseed.addSeed((RouteAdvertisement) hint); - } else { - uriseed.addSeed(addr.toURI()); - } - } else if (seedingManager instanceof PeerviewSeedingManager) { - PeerviewSeedingManager pvseed = (PeerviewSeedingManager) seedingManager; - - if (hint instanceof RouteAdvertisement) { - pvseed.addSeed((RouteAdvertisement) hint); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void challengeRendezVous(ID peerid, long delay) { - - // If immediate failure is requested, just do it. - // {@code disconnectFromRendezVous()} will at least get the peer - // removed from the peerView, even if it is not currently a rendezvous - // of ours. That permits to purge from the peerview rdvs that we try - // and fail to connect to, faster than the background keep alive done - // by PeerView itself. - if (delay <= 0) { - removeRdv(peerid, false); - return; - } - - RdvConnection pConn = rendezVous.get(peerid); - - if (null != pConn) { - long adjusted_delay = Math.max(0, Math.min(TimeUtils.toRelativeTimeMillis(pConn.getLeaseEnd()), delay)); - - pConn.setLease(adjusted_delay, adjusted_delay); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void disconnectFromRendezVous(ID peerId) { - removeRdv(peerId, false); - } - - /** - * {@inheritDoc} - */ - @Override - public void propagate(Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException { - msg = msg.clone(); - int useTTL = Math.min(initialTTL, MAX_TTL); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Propagating " + msg + "(TTL=" + useTTL + ") to :" + "\n\tsvc name:" + serviceName + "\tsvc params:"+ serviceParam); - } - - RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, useTTL); - - if (null != propHdr) { - sendToEachConnection(msg, propHdr); - sendToNetwork(msg, propHdr); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToGroup(); - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Declining to propagate " + msg + " (No prop header)"); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void propagateInGroup(Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException { - msg = msg.clone(); - int useTTL = Math.min(initialTTL, MAX_TTL); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Propagating " + msg + "(TTL=" + useTTL + ") in group to :" + "\n\tsvc name:" + serviceName + "\tsvc params:" - + serviceParam); - } - - RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, useTTL); - - if (null != propHdr) { - sendToEachConnection(msg, propHdr); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToGroup(); - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Declining to propagate " + msg + " (No prop header)"); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void walk(Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException { - - propagateInGroup(msg, serviceName, serviceParam, initialTTL); - } - - /** - * {@inheritDoc} - */ - @Override - public void walk(Vector destPeerIDs, Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException { - - propagate(destPeerIDs.elements(), msg, serviceName, serviceParam, initialTTL); - } - - /** - * @inheritDoc - */ - @Override - public PeerConnection getPeerConnection(ID peer) { - return rendezVous.get(peer); - } - - /** - * @inheritDoc - */ - @Override - protected PeerConnection[] getPeerConnections() { - return rendezVous.values().toArray(new PeerConnection[0]); - } - - private void disconnectFromAllRendezVous() { - - for (RdvConnection pConn : new ArrayList(rendezVous.values())) { - try { - disconnectFromRendezVous(pConn.getPeerID()); - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "disconnectFromRendezVous failed for " + pConn, failed); - } - } - } - } - - /** - * Handle a disconnection request from a remote peer. - * - * @param msg Description of Parameter - */ - private void processDisconnectRequest(Message msg) { - - try { - MessageElement elem = msg.getMessageElement(RendezVousServiceProvider.RDV_MSG_NAMESPACE_NAME, DisconnectRequest); - - if (null != elem) { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(elem); - - PeerAdvertisement adv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(asDoc); - - RdvConnection rdvConnection = rendezVous.get(adv.getPeerID()); - - if (null != rdvConnection) { - rdvConnection.setConnected(false); - removeRdv(adv.getPeerID(), true); - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Ignoring disconnect request from " + adv.getPeerID()); - } - } - } - } catch (Exception failure) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure processing disconnect request", failure); - } - } - } - - /** - * Add a rendezvous to our collection of rendezvous peers. - * - * @param padv PeerAdvertisement for the rendezvous peer. - * @param lease The duration of the lease in relative milliseconds. - */ - private void addRdv(PeerAdvertisement padv, long lease) { - - int eventType; - - RdvConnection rdvConnection; - - synchronized (rendezVous) { - rdvConnection = rendezVous.get(padv.getPeerID()); - - if (null == rdvConnection) { - rdvConnection = new RdvConnection(group, rdvService, padv.getPeerID()); - rendezVous.put(padv.getPeerID(), rdvConnection); - eventType = RendezvousEvent.RDVCONNECT; - } else { - eventType = RendezvousEvent.RDVRECONNECT; - } - } - - // Check if the peer is already registered. - if (RendezvousEvent.RDVRECONNECT == eventType) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Renewed RDV lease from " + rdvConnection); - } - - // Already connected, just upgrade the lease - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousServiceMonitor != null)) { - RendezvousConnectionMeter rendezvousConnectionMeter = rendezvousServiceMonitor.getRendezvousConnectionMeter( - padv.getPeerID()); - - rendezvousConnectionMeter.leaseRenewed(lease); - } - } else { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("New RDV lease from " + rdvConnection); - } - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousServiceMonitor != null)) { - RendezvousConnectionMeter rendezvousConnectionMeter = rendezvousServiceMonitor.getRendezvousConnectionMeter( - padv.getPeerID()); - - rendezvousConnectionMeter.connectionEstablished(lease); - } - } - - rdvConnection.connect(padv, lease, Math.min(LEASE_MARGIN, (lease / 2))); - - rdvService.generateEvent(eventType, padv.getPeerID()); - } - - /** - * Remove the specified rendezvous from our collection of rendezvous. - * - * @param rdvid the id of the rendezvous to remove. - * @param requested if true, indicates a requested operation - */ - private void removeRdv(ID rdvid, boolean requested) { - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Disconnect from RDV " + rdvid); - } - - PeerConnection rdvConnection; - - synchronized (this) { - rdvConnection = rendezVous.remove(rdvid); - } - - if (null != rdvConnection) { - if (rdvConnection.isConnected()) { - rdvConnection.setConnected(false); - sendDisconnect(rdvConnection); - } - } - - rdvService.generateEvent(requested ? RendezvousEvent.RDVDISCONNECT : RendezvousEvent.RDVFAILED, rdvid); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousServiceMonitor != null)) { - RendezvousConnectionMeter rendezvousConnectionMeter = rendezvousServiceMonitor.getRendezvousConnectionMeter( - (PeerID) rdvid); - - rendezvousConnectionMeter.connectionDisconnected(); - } - } - - /** - * Send lease request to the specified peer. - * - * @param pConn The peer to which the message should be sent. - * @throws IOException Thrown for errors sending the lease request. - */ - private void sendLeaseRequest(RdvConnection pConn) throws IOException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending Lease request to " + pConn); - } - - RendezvousConnectionMeter rendezvousConnectionMeter = null; - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousServiceMonitor != null)) { - rendezvousConnectionMeter = rendezvousServiceMonitor.getRendezvousConnectionMeter(pConn.getPeerID().toString()); - } - - Message msg = new Message(); - - // The request simply includes the local peer advertisement. - msg.replaceMessageElement(RendezVousServiceProvider.RDV_MSG_NAMESPACE_NAME - , - new TextDocumentMessageElement(ConnectRequest, getPeerAdvertisementDoc(), null)); - - pConn.sendMessage(msg, pName, pParam); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousConnectionMeter != null)) { - rendezvousConnectionMeter.beginConnection(); - } - } - - /** - * Description of the Method - * - * @param msg Description of Parameter - */ - private void processConnectedReply(Message msg) { - - // get the Peer Advertisement of the RDV. - MessageElement peerElem = msg.getMessageElement(RendezVousServiceProvider.RDV_MSG_NAMESPACE_NAME, ConnectedRdvAdvReply); - - if (null == peerElem) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Missing rendezvous peer advertisement"); - } - - return; - } - - long lease; - - try { - MessageElement el = msg.getMessageElement(RendezVousServiceProvider.RDV_MSG_NAMESPACE_NAME, ConnectedLeaseReply); - - if (el == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("missing lease"); - } - return; - } - lease = Long.parseLong(el.toString()); - } catch (Exception e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Parse lease failed with ", e); - } - return; - } - - ID pId; - MessageElement el = msg.getMessageElement(RendezVousServiceProvider.RDV_MSG_NAMESPACE_NAME, ConnectedPeerReply); - - if (el == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("missing rdv peer"); - } - return; - } - - try { - pId = IDFactory.fromURI(new URI(el.toString())); - } catch (URISyntaxException badID) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Bad RDV peer ID"); - } - return; - } - - if (lease <= 0) { - removeRdv(pId, false); - } else { - if (rendezVous.containsKey(pId) || (rendezVous.size() < MAX_RDV_CONNECTIONS)) { - PeerAdvertisement padv = null; - - try { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(peerElem); - - padv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(asDoc); - } catch (Exception failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed processing peer advertisement"); - } - } - - if (null == padv) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Missing rendezvous peer advertisement"); - } - return; - } - - if (!seedingManager.isAcceptablePeer(padv)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Rejecting lease offer from unacceptable peer : " + padv.getPeerID()); - } - - // XXX bondolo 20061123 perhaps we should send a disconnect here. - - return; - } - - addRdv(padv, lease); - - try { - DiscoveryService discovery = group.getDiscoveryService(); - - if (null != discovery) { - // This is not our own peer adv so we choose not to share it and keep it for only a short time. - discovery.publish(padv, lease * 2, 0); - } - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "failed to publish Rendezvous Advertisement", e); - } - } - - String rdvName = padv.getName(); - - if (null == padv.getName()) { - rdvName = pId.toString(); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RDV Connect Response : peer=" + rdvName + " lease=" + lease + "ms"); - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Ignoring lease offer from " + pId); - } - // XXX bondolo 20040423 perhaps we should send a disconnect here. - } - } - } - - /** - * A timer task for monitoring our active rendezvous connections. - *

            - * Checks leases, initiates lease renewals, starts new lease requests. - */ - private class MonitorTask extends TimerTask { - - /** - * @inheritDoc - */ - @Override - public void run() { - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + group + "] Periodic rendezvous check"); - } - - if (closed) { - return; - } - - if (!PeerGroupID.worldPeerGroupID.equals(group.getPeerGroupID())) { - MessageTransport router = rdvService.endpoint.getMessageTransport("jxta"); - - if (null == router) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Rendezvous connection stalled until router is started!"); - } - - // Reschedule another run very soon. - timer.schedule(new MonitorTask(), 2 * TimeUtils.ASECOND); - return; - } - } - - List currentRdvs = new ArrayList(rendezVous.values()); - - for (RdvConnection pConn : currentRdvs) { - try { - if (!pConn.isConnected()) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.fine("[" + group.getPeerGroupID() + "] Lease expired. Disconnected from " + pConn); - } - removeRdv(pConn.getPeerID(), false); - continue; - } - - if (TimeUtils.toRelativeTimeMillis(pConn.getRenewal()) <= 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + group.getPeerGroupID() + "] Attempting lease renewal for " + pConn); - } - - sendLeaseRequest(pConn); - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "[" + group.getPeerGroupID() + "] Failure while checking " + pConn, e); - } - } - } - - // Not enough Rdvs? Try finding more. - if (rendezVous.size() < MAX_RDV_CONNECTIONS) { - if (seeds.isEmpty()) { - seeds.addAll(Arrays.asList(EdgePeerRdvService.this.seedingManager.getActiveSeedRoutes())); - } - - int sentLeaseRequests = 0; - - while (!seeds.isEmpty() && (sentLeaseRequests < 3)) { - RouteAdvertisement aSeed = seeds.remove(0); - - Message msg = new Message(); - - // The lease request simply includes the local peer advertisement. - msg.addMessageElement(RendezVousServiceProvider.RDV_MSG_NAMESPACE_NAME - , - new TextDocumentMessageElement(ConnectRequest, getPeerAdvertisementDoc(), null)); - - Messenger msgr = null; - - if (null == aSeed.getDestPeerID()) { - // It is an incomplete route advertisement. We are going to assume that it is only a wrapper for a single ea. - List seed_eas = aSeed.getDest().getVectorEndpointAddresses(); - - if (!seed_eas.isEmpty()) { - EndpointAddress aSeedHost = new EndpointAddress(seed_eas.get(0)); - - msgr = rdvService.endpoint.getMessengerImmediate(aSeedHost, null); - } - } else { - // We have a full route, send it to the virtual address of the route! - EndpointAddress aSeedHost = new EndpointAddress(aSeed.getDestPeerID(), null, null); - - msgr = rdvService.endpoint.getMessengerImmediate(aSeedHost, aSeed); - } - - if (null != msgr) { - try { - msgr.sendMessageN(msg, pName, pParam); - sentLeaseRequests++; - } catch (Exception failed) { - // ignored - ; - } - } - } - } else { - // We don't need any of the current seeds. Get new ones when we need them. - seeds.clear(); - } - } catch (Throwable t) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught throwable in thread :" + Thread.currentThread().getName(), t); - } - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/edge/RdvConnection.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/edge/RdvConnection.java deleted file mode 100644 index 62b3cba4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/edge/RdvConnection.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.edge; - -import net.jxta.id.ID; -import net.jxta.impl.rendezvous.PeerConnection; -import net.jxta.impl.rendezvous.RendezVousServiceImpl; -import net.jxta.impl.util.TimeUtils; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.PeerAdvertisement; - -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import java.util.logging.Logger; - -/** - * Manages a connection with a client or a rendezvous peer. - */ -public class RdvConnection extends PeerConnection { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(RdvConnection.class.getName()); - - protected long leasedTil; - protected long beginRenewalAt; - - protected PeerAdvertisement cachedPeerAdvertisement = null; - protected int cachedModCount = -1; - - /** - * Constructor for the PeerConnection object - * - * @param group group context - * @param rdvService the rendezvous service to use for sending messages. - * @param peer destination peerid - */ - public RdvConnection(PeerGroup group, RendezVousServiceImpl rdvService, ID peer) { - super(group, rdvService.endpoint, peer); - - cachedPeerAdvertisement = group.getPeerAdvertisement(); - cachedModCount = cachedPeerAdvertisement.getModCount(); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return super.toString() + " / " + Long.toString(TimeUtils.toRelativeTimeMillis(beginRenewalAt)); - } - - /** - * {@inheritDoc} - */ - @Override - protected void setLease(long leaseDuration) { - setLease(leaseDuration, 0); - } - - /** - * Set the lease duration in relative milliseconds. - * - * @param leaseDuration the lease duration in relative milliseconds. - * @param earlyRenewal amount of time in relative milliseconds before lease end to begin renewal - */ - public void setLease(long leaseDuration, long earlyRenewal) { - - if (leaseDuration < earlyRenewal) { - throw new IllegalArgumentException("Renewal scheduled before begining of lease"); - } - - super.setLease(leaseDuration); - beginRenewalAt = TimeUtils.toAbsoluteTimeMillis(leaseDuration - earlyRenewal); - } - - /** - * Declare that we are connected. - * - * @param padv the node advertisement - * @param leaseDuration lease duration in milliseconds - * @param earlyRenewal early renwal in milliseconds - */ - public void connect(PeerAdvertisement padv, long leaseDuration, long earlyRenewal) { - super.connect(leaseDuration); - - setLease(leaseDuration, earlyRenewal); - - // We will almost certainly need a messenger soon. Get it now. - getCachedMessenger(padv); - } - - /** - * Time at which the lease needs renewal in absolute milliseconds. - * - * @return The lease value - */ - public long getRenewal() { - return beginRenewalAt; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/limited/LimitedRangeGreeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/limited/LimitedRangeGreeter.java deleted file mode 100644 index ebfc19e8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/limited/LimitedRangeGreeter.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.limited; - -import java.io.IOException; - -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import java.util.logging.Logger; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; - -import net.jxta.impl.protocol.LimitedRangeRdvMsg; -import net.jxta.impl.rendezvous.RdvGreeter; -import net.jxta.impl.rendezvous.rpv.PeerViewElement; - -/** - * The limited range rendezvous peer greeter. - * - * @see net.jxta.impl.rendezvous.RdvGreeter - * @see net.jxta.impl.rendezvous.RdvWalk - * @see net.jxta.impl.rendezvous.RdvWalker - * @see net.jxta.impl.protocol.LimitedRangeRdvMsg - */ -public class LimitedRangeGreeter implements EndpointListener, RdvGreeter { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(LimitedRangeGreeter.class.getName()); - - /** - * The walk we are associated with. - */ - private final LimitedRangeWalk walk; - - /** - * XXX It would be nice to avoid making another link to the endpoint. - */ - private final EndpointService endpoint; - - /** - * Constructor - * - * @param walk The walk we will be associated with. - */ - public LimitedRangeGreeter(LimitedRangeWalk walk) { - this.walk = walk; - - this.endpoint = walk.getPeerGroup().getEndpointService(); - - if (!endpoint.addIncomingMessageListener(this, walk.getWalkServiceName(), walk.getWalkServiceParam())) { - throw new IllegalStateException("Could not register endpoint listener for greeter."); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Listening on " + walk.getWalkServiceName() + "/" + walk.getWalkServiceParam()); - } - } - - /** - * {@inheritDoc} - */ - public synchronized void stop() { - endpoint.removeIncomingMessageListener(walk.getWalkServiceName(), walk.getWalkServiceParam()); - } - - /** - * {@inheritDoc} - *

            - * Listens on "LR-Greeter"<groupid>/<walkSvc><walkParam> - *

            - * Currently, all this method has to do, is to invoke the upper layer. - */ - public void processIncomingMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Processing " + message + " from " + srcAddr); - } - - LimitedRangeRdvMsg rdvMsg = LimitedRangeWalk.getRdvMessage(message); - - // Check and update the Limited Range Rdv Message - if (null == rdvMsg) { - // Message is invalid, drop it - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Limited Range Greeter received invalid " + message + ". Dropping it."); - } - return; - } - - if (rdvMsg.getTTL() <= 0) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("No TTL remaining for " + message + ". Dropping it."); - } - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Limited Range Greeter calling listener"); - } - - try { - walk.getListener().processIncomingMessage(message, srcAddr, dstAddr); - } catch (Throwable ignored) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in listener (" + walk.getListener() + ")", ignored); - } - } - } - - /** - * {@inheritDoc} - */ - public void replyMessage(Message msg, Message reply) throws IOException { - LimitedRangeRdvMsg rdvMsg = LimitedRangeWalk.getRdvMessage(msg); - - if (rdvMsg == null) { - // No RdvMessage. This message was not received by this Greeter. - throw new IOException("LimitedRangeWalker was not able to send message" + ": not from this greeter"); - } - - PeerViewElement pve = walk.getPeerView().getPeerViewElement(rdvMsg.getSrcPeerID()); - - if (null == pve) { - throw new IOException("LimitedRangeWalker was not able to send message" + ": no pve"); - } - - if (!pve.sendMessage(msg, rdvMsg.getSrcSvcName(), rdvMsg.getSrcSvcParams())) { - throw new IOException("LimitedRangeWalker was not able to send message" + ": send failed"); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/limited/LimitedRangeWalk.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/limited/LimitedRangeWalk.java deleted file mode 100644 index 8404161b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/limited/LimitedRangeWalk.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.limited; - -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.peergroup.PeerGroup; - -import net.jxta.impl.protocol.LimitedRangeRdvMsg; -import net.jxta.impl.rendezvous.RdvWalk; -import net.jxta.impl.rendezvous.rpv.PeerView; - -/** - * This class is the Limited Walk Policy. - * - * @see net.jxta.impl.rendezvous.limited.LimitedRangeWalker - * @see net.jxta.impl.rendezvous.limited.LimitedRangeGreeter - */ -public class LimitedRangeWalk extends RdvWalk { - - /** - * The prefix we will use for service name we use for messaging. - */ - public static final String SERVICENAME = "LR-Greeter"; - - /** - * The name of the message element in which we will store our information. - */ - - public static final String ELEMENTNAME = "LimitedRangeRdvMessage"; - - /** - * The PeerView we walk. - */ - private final PeerView rpv; - - /** - * The service name for listener of this walk. All walkers in the same - * peer group have the same service name. - */ - private final String walkSvcName; - - /** - * The service param for listener of this walk. The walker param is - * composed of the walk service name concated with the walk service param. - */ - private final String walkSvcParam; - - /** - * Our walker (sender) - */ - private LimitedRangeWalker walker = null; - - /** - * Our greeter (listener) - */ - private LimitedRangeGreeter greeter = null; - - /** - * Returns the parsed LimitedRangeRdvMsg from the provided message or - * {@code null} if the message did not contain an appropriate element or - * the element couldn't be parsed. - * - * @param msg the Message which must contain the LimitedRangeRdvMsg. - * @return The LimitedRangeRdvMsg from the message or {@code null}. - */ - static LimitedRangeRdvMsg getRdvMessage(Message msg) { - MessageElement el = msg.getMessageElement("jxta", ELEMENTNAME); - - if (el == null) { - // The sender did not use this protocol - return null; - } - - try { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(el); - - return new LimitedRangeRdvMsg(asDoc); - } catch (Exception ez) { - return null; - } - } - - /** - * Standard constructor - * - * @param group Peergroup in which this walk is running. - * @param listener Intended recipient of messages received as part of this walk. - * @param srcServiceName Service name used by the client of this walk. - * @param srcServiceParam Optional service parameter used by the client of this walk. - * @param rpv the rendezvous peer PeerView to be used by this walk. - */ - public LimitedRangeWalk(PeerGroup group, EndpointListener listener, String srcServiceName, String srcServiceParam, PeerView rpv) { - super(group, listener, srcServiceName, srcServiceParam); - - this.rpv = rpv; - - this.walkSvcName = SERVICENAME + group.getPeerGroupID().toString(); - this.walkSvcParam = srcServiceName + srcServiceParam; - - this.walker = new LimitedRangeWalker(this); - this.greeter = new LimitedRangeGreeter(this); - } - - /** - * Return the Rendezvous peer PeerView used by this walk. - * - * @return The rendezvous peer PeerView used by this walk. - */ - PeerView getPeerView() { - return rpv; - } - - /** - * Return the Service Name used by listener of this walk. - * - * @return the Service Name used by listener of this walk. - */ - String getWalkServiceName() { - return walkSvcName; - } - - /** - * Return the Service Param used by listener of this walk. - * - * @return the Service Param used by listener of this walk. - */ - String getWalkServiceParam() { - return walkSvcParam; - } - - /** - * {@inheritDoc} - */ - @Override - public LimitedRangeWalker getWalker() { - return this.walker; - } - - /** - * {@inheritDoc} - */ - @Override - public LimitedRangeGreeter getGreeter() { - return this.greeter; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void stop() { - if (walker != null) { - walker.stop(); - walker = null; - } - - if (greeter != null) { - greeter.stop(); - greeter = null; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/limited/LimitedRangeWalker.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/limited/LimitedRangeWalker.java deleted file mode 100644 index 7a7abe75..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/limited/LimitedRangeWalker.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.limited; - -import java.io.IOException; - -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import java.util.logging.Logger; - -import net.jxta.document.MimeMediaType; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.peer.PeerID; - -import net.jxta.impl.protocol.LimitedRangeRdvMsg; -import net.jxta.impl.rendezvous.RdvWalker; -import net.jxta.impl.rendezvous.rpv.PeerViewElement; - -/** - * The Limited Range Walker is designed to be used by Rendezvous Peer in - * order to propagate a message amongst them. A target destination peer - * is used in order to send the message to a primary peer. Then, depending - * on the TTL, the message is duplicated into two messages, each of them - * being sent in opposite "directions" of the RPV. - */ -public class LimitedRangeWalker implements RdvWalker { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(LimitedRangeWalker.class.getName()); - - /** - * The walk we are associated with. - */ - private final LimitedRangeWalk walk; - - /** - * Constructor - * - * @param walk The walk we will be associated with. - */ - public LimitedRangeWalker(LimitedRangeWalk walk) { - this.walk = walk; - } - - /** - * {@inheritDoc} - */ - public void stop() { - } - - /** - * {@inheritDoc} - *

            - * Sends message on : - *

            -     *  "LR-Greeter"<groupid>/<walkSvc><walkParam>
            -     *  
            - *

            - * XXX bondolo 20060720 This method will currently fail to walk the - * message to the DOWN peer if there is a failure sending the message to - * the UP peer. Perhaps it would be better to ignore any errors from - * sending to either peer? - */ - private void walkMessage(Message msg, LimitedRangeRdvMsg rdvMsg) throws IOException { - - LimitedRangeRdvMsg.WalkDirection dir = rdvMsg.getDirection(); - - if ((dir == LimitedRangeRdvMsg.WalkDirection.BOTH) || (dir == LimitedRangeRdvMsg.WalkDirection.UP)) { - PeerViewElement upPeer = walk.getPeerView().getUpPeer(); - - if ((upPeer != null) && upPeer.isAlive()) { - Message newMsg = msg.clone(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Walking " + newMsg + " [UP] to " + upPeer); - } - - rdvMsg.setDirection(LimitedRangeRdvMsg.WalkDirection.UP); - - updateRdvMessage(newMsg, rdvMsg); - upPeer.sendMessage(newMsg, walk.getWalkServiceName(), walk.getWalkServiceParam()); - } - } - - if ((dir == LimitedRangeRdvMsg.WalkDirection.BOTH) || (dir == LimitedRangeRdvMsg.WalkDirection.DOWN)) { - PeerViewElement downPeer = walk.getPeerView().getDownPeer(); - - if ((downPeer != null) && downPeer.isAlive()) { - Message newMsg = msg.clone(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Walking " + newMsg + " [DOWN] to " + downPeer); - } - - rdvMsg.setDirection(LimitedRangeRdvMsg.WalkDirection.DOWN); - - updateRdvMessage(newMsg, rdvMsg); - downPeer.sendMessage(newMsg, walk.getWalkServiceName(), walk.getWalkServiceParam()); - } - } - } - - /** - * {@inheritDoc} - */ - public void walkMessage(PeerID destination, Message msg, String srcSvcName, String srcSvcParam, int ttl) throws IOException { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Walking " + msg + " to " + srcSvcName + "/" + srcSvcParam); - } - - // Check if there is already a Rdv Message - LimitedRangeRdvMsg rdvMsg = LimitedRangeWalk.getRdvMessage(msg); - - if (rdvMsg == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Creating new Walk Header for " + msg + " with TTL=" + ttl); - } - - // Create a new one. - rdvMsg = new LimitedRangeRdvMsg(); - - rdvMsg.setTTL(Integer.MAX_VALUE); // will be reduced. - rdvMsg.setDirection(LimitedRangeRdvMsg.WalkDirection.BOTH); - rdvMsg.setSrcPeerID(walk.getPeerGroup().getPeerID()); - rdvMsg.setSrcSvcName(srcSvcName); - rdvMsg.setSrcSvcParams(srcSvcParam); - } else { - // decrement TTL before walk. - rdvMsg.setTTL(rdvMsg.getTTL() - 1); - } - - int useTTL = Math.min(ttl, rdvMsg.getTTL()); - - useTTL = Math.min(useTTL, walk.getPeerView().getView().size() + 1); - - rdvMsg.setTTL(useTTL); - - if (useTTL <= 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("LimitedRangeWalker was not able to send " + msg + " : No TTL remaining"); - } - - return; - } - - // Forward the message according to the direction set in the Rdv Message. - if (null != destination) { - Message tmp = msg.clone(); - - updateRdvMessage(tmp, rdvMsg); - sendToPeer(destination, walk.getWalkServiceName(), walk.getWalkServiceParam(), tmp); - } else { - walkMessage(msg, rdvMsg); - } - } - - /** - * Replace the old version of the rdvMsg - * - * @param msg The message to be updated. - * @param rdvMsg The LimitedRangeRdvMsg which will update the message. - * @return the updated message - */ - private Message updateRdvMessage(Message msg, LimitedRangeRdvMsg rdvMsg) { - XMLDocument asDoc = (XMLDocument) rdvMsg.getDocument(MimeMediaType.XMLUTF8); - MessageElement el = new TextDocumentMessageElement(LimitedRangeWalk.ELEMENTNAME, asDoc, null); - - msg.replaceMessageElement("jxta", el); - - return msg; - } - - /** - * Sends the provided message to the specified peer. The peer must be a - * current member of the PeerView. - * - * @param dest The destination peer. - * @param svcName The destinations service. - * @param svcParam The destination service params. - * @param msg The message to send. - * @throws IOException Thrown for problems sending the message. - */ - private void sendToPeer(PeerID dest, String svcName, String svcParam, Message msg) throws IOException { - PeerViewElement pve = walk.getPeerView().getPeerViewElement(dest); - - if (null == pve) { - throw new IOException("LimitedRangeWalker was not able to send " + msg + " : no pve"); - } - - if (!pve.sendMessage(msg, svcName, svcParam)) { - throw new IOException("LimitedRangeWalker was not able to send " + msg + " : send failed"); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/package.html deleted file mode 100644 index 554fba6d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/package.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.rendezvous.RendezVousService} implementation which - implements the standard JXTA Rendezvous Protocol (RVP). - - @see net.jxta.rendezvous.RendezVousService - @see JXTA Protocols Specification : Rendezvous Protocol - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rdv/ClientConnection.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rdv/ClientConnection.java deleted file mode 100644 index 9893ec9b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rdv/ClientConnection.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rdv; - -import java.util.logging.Logger; -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.PeerAdvertisement; - -import net.jxta.impl.rendezvous.PeerConnection; -import net.jxta.impl.rendezvous.RendezVousServiceImpl; - -/** - * Manages a connection with a client peer. - */ -public class ClientConnection extends PeerConnection { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(ClientConnection.class.getName()); - - /** - * Constructor for the PeerConnection object - * - * @param group The group context. - * @param rdvService The rendezvous service instance this connection is associated with. - * @param peer The peer id of the connection. - */ - public ClientConnection(PeerGroup group, RendezVousServiceImpl rdvService, ID peer) { - super(group, rdvService.endpoint, peer); - } - - /** - * Declare that we are connected. - * - * @param padv The peer advertisement of the peer. - * @param leaseDuration The duration of the lease which is offered to the client. - */ - public void connect(PeerAdvertisement padv, long leaseDuration) { - - super.connect(leaseDuration); - - // We will almost certainly need a messenger soon. Get it now. - getCachedMessenger(padv); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rdv/RdvPeerRdvService.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rdv/RdvPeerRdvService.java deleted file mode 100644 index bebb827e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rdv/RdvPeerRdvService.java +++ /dev/null @@ -1,869 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rdv; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.ID; -import net.jxta.impl.protocol.RdvConfigAdv; -import net.jxta.impl.rendezvous.PeerConnection; -import net.jxta.impl.rendezvous.RdvWalk; -import net.jxta.impl.rendezvous.RdvWalker; -import net.jxta.impl.rendezvous.RendezVousPropagateMessage; -import net.jxta.impl.rendezvous.RendezVousServiceImpl; -import net.jxta.impl.rendezvous.StdRendezVousService; -import net.jxta.impl.rendezvous.limited.LimitedRangeWalk; -import net.jxta.impl.rendezvous.rendezvousMeter.ClientConnectionMeter; -import net.jxta.impl.rendezvous.rendezvousMeter.RendezvousMeterBuildSettings; -import net.jxta.impl.rendezvous.rpv.PeerView; -import net.jxta.impl.util.TimeUtils; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.platform.Module; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.rendezvous.RendezvousEvent; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TimerTask; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A JXTA {@link net.jxta.rendezvous.RendezVousService} implementation which - * implements the rendezvous server portion of the standard JXTA Rendezvous - * Protocol (RVP). - * - * @see net.jxta.rendezvous.RendezVousService - * @see JXTA Protocols Specification : Rendezvous Protocol - */ -public class RdvPeerRdvService extends StdRendezVousService { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(RdvPeerRdvService.class.getName()); - - public static final String RDV_WALK_SVC_NAME = "RdvWalkSvcName"; - public static final String RDV_WALK_SVC_PARAM = "RdvWalkSvcParam"; - - public final static long GC_INTERVAL = 2 * TimeUtils.AMINUTE; - public final static long DEFAULT_LEASE_DURATION = 20L * TimeUtils.AMINUTE; - public final static int DEFAULT_MAX_CLIENTS = 200; - - /** - * Duration of leases we offer measured in relative milliseconds. - */ - private final long LEASE_DURATION; - - /** - * The maximum number of simultaneous clients we will allow. - */ - private final int MAX_CLIENTS; - - /** - * The clients which currently have a lease with us. - */ - private final Map clients = Collections.synchronizedMap(new HashMap()); - - private RdvWalk walk = null; - private RdvWalker walker = null; - - /** - * The peer view for this rendezvous server. - */ - public final PeerView rpv; - - /** - * Constructor for the RdvPeerRdvService object - * - * @param group the peer group - * @param rdvService the rendezvous service object - */ - public RdvPeerRdvService(PeerGroup group, RendezVousServiceImpl rdvService) { - - super(group, rdvService); - - Advertisement adv = null; - ConfigParams confAdv = group.getConfigAdvertisement(); - - // Get the config. If we do not have a config, we're done; we just keep - // the defaults (edge peer/no auto-rdv) - if (confAdv != null) { - try { - XMLDocument configDoc = (XMLDocument) confAdv.getServiceParam(rdvService.getAssignedID()); - - if (null != configDoc) { - adv = AdvertisementFactory.newAdvertisement(configDoc); - } - } catch (java.util.NoSuchElementException failed) {// ignored - } - } - - RdvConfigAdv rdvConfigAdv; - - if (!(adv instanceof RdvConfigAdv)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Creating new RdvConfigAdv for defaults."); - } - - rdvConfigAdv = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType()); - } else { - rdvConfigAdv = (RdvConfigAdv) adv; - } - - if (rdvConfigAdv.getMaxTTL() > 0) { - MAX_TTL = rdvConfigAdv.getMaxTTL(); - } else { - MAX_TTL = StdRendezVousService.DEFAULT_MAX_TTL; - } - - if (rdvConfigAdv.getMaxClients() > 0) { - MAX_CLIENTS = rdvConfigAdv.getMaxClients(); - } else { - MAX_CLIENTS = DEFAULT_MAX_CLIENTS; - } - - if (rdvConfigAdv.getLeaseDuration() > 0) { - LEASE_DURATION = rdvConfigAdv.getLeaseDuration(); - } else { - LEASE_DURATION = DEFAULT_LEASE_DURATION; - } - - // Update the peeradv with that information: - // XXX 20050409 bondolo How does this interact with auto-rdv? - try { - XMLDocument params = (XMLDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - Element e = params.createElement("Rdv", Boolean.TRUE.toString()); - - params.appendChild(e); - group.getPeerAdvertisement().putServiceParam(rdvService.getAssignedID(), params); - } catch (Exception ohwell) { - // don't worry about it for now. It'll still work. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed adding service params", ohwell); - } - } - - PeerGroup advGroup = group.getParentGroup(); - - if ((null == advGroup) || PeerGroupID.worldPeerGroupID.equals(advGroup.getPeerGroupID())) { - // For historical reasons, we publish in our own group rather than - // the parent if our parent is the world group. - advGroup = null; - } - - rpv = new PeerView(group, advGroup, rdvService, - rdvService.getAssignedID().toString() + group.getPeerGroupID().getUniqueValue().toString()); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("RendezVous Service is initialized for " + group.getPeerGroupID() + " as a Rendezvous peer."); - } - } - - /** - * Listener for - *

            - * <assignedID>/<group-unique> - */ - private class StdRdvRdvProtocolListener implements StdRendezVousService.StdRdvProtocolListener { - - /** - * {@inheritDoc} - */ - public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + group.getPeerGroupID() + "] processing " + msg); - } - - if (msg.getMessageElement("jxta", ConnectRequest) != null) { - processLeaseRequest(msg); - } - - if (msg.getMessageElement("jxta", DisconnectRequest) != null) { - processDisconnectRequest(msg); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - protected int startApp(String[] argv) { - - super.startApp(argv, new StdRdvRdvProtocolListener()); - - rpv.start(); - - // The other services may not be fully functional but they're there - // so we can start our subsystems. - // As for us, it does not matter if our methods are called between init - // and startApp(). - - // Start the Walk protcol. Create a LimitedRange Walk - walk = new LimitedRangeWalk(group, new WalkListener(), pName, pParam, rpv); - - // We need to use a Walker in order to propagate the request - // when when have no answer. - walker = walk.getWalker(); - - timer.scheduleAtFixedRate(new GCTask(), GC_INTERVAL, GC_INTERVAL); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.startRendezvous(); - } - - rdvService.generateEvent(RendezvousEvent.BECAMERDV, group.getPeerID()); - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("RdvPeerRdvService is started"); - } - - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void stopApp() { - - if (closed) { - return; - } - - closed = true; - - walk.stop(); - walk = null; - - rpv.stop(); - - // Tell all our clientss that we are going down - disconnectAllClients(); - - clients.clear(); - - super.stopApp(); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.stopRendezvous(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void connectToRendezVous(EndpointAddress addr, Object hint) { - throw new UnsupportedOperationException("Not supported by rendezvous"); - } - - /** - * {@inheritDoc} - */ - @Override - public void challengeRendezVous(ID peer, long delay) { - throw new UnsupportedOperationException("Not supported by rendezvous"); - } - - /** - * {@inheritDoc} - */ - @Override - public void disconnectFromRendezVous(ID peerId) { - - throw new UnsupportedOperationException("Not supported by rendezvous"); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isConnectedToRendezVous() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Vector getConnectedPeerIDs() { - - Vector result = new Vector(); - List allClients = Arrays.asList(clients.values().toArray()); - - for (Object allClient : allClients) { - PeerConnection aConnection = (PeerConnection) allClient; - - if (aConnection.isConnected()) { - result.add(aConnection.getPeerID()); - } - } - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public void propagate(Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException { - if (closed) { - return; - } - - msg = msg.clone(); - int useTTL = Math.min(initialTTL, MAX_TTL); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Propagating " + msg + "(TTL=" + useTTL + ") to :" + - "\n\tsvc name:" + serviceName + "\tsvc params:" + serviceParam); - } - - RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, useTTL); - - if (null != propHdr) { - walk(msg, PropSName, PropPName, useTTL); - // hamada: this is a very expensive operation and therefore not a supported operation - // sendToEachConnection(msg, propHdr); - sendToNetwork(msg, propHdr); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToGroup(); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void propagateInGroup(Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException { - if (closed) { - return; - } - - msg = msg.clone(); - int useTTL = Math.min(initialTTL, MAX_TTL); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Propagating " + msg + "(TTL=" + useTTL + ") in group to :" + - "\n\tsvc name:" + serviceName + "\tsvc params:" + serviceParam); - } - - RendezVousPropagateMessage propHdr = updatePropHeader(msg, getPropHeader(msg), serviceName, serviceParam, useTTL); - - if (null != propHdr) { - walk(msg, PropSName, PropPName, useTTL); - sendToEachConnection(msg, propHdr); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.propagateToGroup(); - } - } - } - - /** - * @inheritDoc - */ - @Override - public PeerConnection getPeerConnection(ID peer) { - return clients.get(peer); - } - - /** - * @inheritDoc - */ - @Override - protected PeerConnection[] getPeerConnections() { - return clients.values().toArray(new PeerConnection[0]); - } - - /** - * Add a client to our collection of clients. - * - * @param padv The advertisement of the peer to be added. - * @param lease The lease duration in relative milliseconds. - * @return the ClientConnection - */ - private ClientConnection addClient(PeerAdvertisement padv, long lease) { - ClientConnectionMeter clientConnectionMeter = null; - - int eventType; - ClientConnection pConn; - - synchronized (clients) { - pConn = clients.get(padv.getPeerID()); - - // Check if the peer is already registered. - if (null != pConn) { - eventType = RendezvousEvent.CLIENTRECONNECT; - } else { - eventType = RendezvousEvent.CLIENTCONNECT; - pConn = new ClientConnection(group, rdvService, padv.getPeerID()); - clients.put(padv.getPeerID(), pConn); - } - } - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousServiceMonitor != null)) { - clientConnectionMeter = rendezvousServiceMonitor.getClientConnectionMeter(padv.getPeerID()); - } - - if (RendezvousEvent.CLIENTCONNECT == eventType) { - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (clientConnectionMeter != null)) { - clientConnectionMeter.clientConnectionEstablished(lease); - } - } else { - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (clientConnectionMeter != null)) { - clientConnectionMeter.clientLeaseRenewed(lease); - } - } - - rdvService.generateEvent(eventType, padv.getPeerID()); - - pConn.connect(padv, lease); - - return pConn; - } - - /** - * Removes the specified client from the clients collections. - * - * @param pConn The connection object to remove. - * @param requested If true then the disconnection was - * requested by the remote peer. - * @return the ClientConnection object of the client or null - * if the client was not known. - */ - private ClientConnection removeClient(PeerConnection pConn, boolean requested) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Disconnecting client " + pConn); - } - - if (pConn.isConnected()) { - pConn.setConnected(false); - sendDisconnect(pConn); - } - - rdvService.generateEvent(requested ? RendezvousEvent.CLIENTDISCONNECT : RendezvousEvent.CLIENTFAILED, pConn.getPeerID()); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousServiceMonitor != null)) { - ClientConnectionMeter clientConnectionMeter = rendezvousServiceMonitor.getClientConnectionMeter( - (PeerID) pConn.getPeerID()); - - clientConnectionMeter.clientConnectionDisconnected(requested); - } - - return clients.remove(pConn.getPeerID()); - } - - private void disconnectAllClients() { - for (Object o : Arrays.asList(clients.values().toArray())) { - ClientConnection pConn = (ClientConnection) o; - - try { - removeClient(pConn, false); - } catch (Exception ez1) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "disconnectClient failed for" + pConn, ez1); - } - } - } - } - - /** - * Handle a disconnection request - * - * @param msg Message containing the disconnection request. - */ - private void processDisconnectRequest(Message msg) { - - PeerAdvertisement adv; - - try { - MessageElement elem = msg.getMessageElement("jxta", DisconnectRequest); - - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(elem); - - adv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(asDoc); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not process disconnect request", e); - } - return; - } - - ClientConnection pConn = clients.get(adv.getPeerID()); - - if (null != pConn) { - pConn.setConnected(false); // Make sure we don't send a disconnect - removeClient(pConn, true); - } - } - - /** - * Handles a lease request message - * - * @param msg Message containing the lease request - */ - private void processLeaseRequest(Message msg) { - - PeerAdvertisement padv; - - try { - MessageElement elem = msg.getMessageElement("jxta", ConnectRequest); - - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(elem); - - padv = (PeerAdvertisement) AdvertisementFactory.newAdvertisement(asDoc); - msg.removeMessageElement(elem); - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Cannot retrieve advertisment from lease request", e); - } - return; - } - - // Publish the client's peer advertisement - try { - // This is not our own peer adv so we must not keep it longer than - // its expiration time. - DiscoveryService discovery = group.getDiscoveryService(); - - if (null != discovery) { - discovery.publish(padv, LEASE_DURATION * 2, 0); - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Client peer advertisement publish failed", e); - } - } - - long lease; - - ClientConnection pConn = clients.get(padv.getPeerID()); - - if (null != pConn) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Renewing client lease to " + pConn); - } - - lease = LEASE_DURATION; - } else { - if (clients.size() < MAX_CLIENTS) { - lease = LEASE_DURATION; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Offering new client lease to " + padv.getName() + " [" + padv.getPeerID() + "]"); - } - } else { - lease = 0; - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning( - "Max clients exceeded, declining lease request from: " + padv.getName() + " [" + padv.getPeerID() - + "]"); - } - } - } - - if (lease > 0) { - pConn = addClient(padv, lease); - - // FIXME 20041015 bondolo We're supposed to send a lease 0 if we can't accept new clients. - sendLease(pConn, lease); - } - } - - /** - * Sends a Connected lease reply message to the specified peer - * - * @param pConn The client peer. - * @param lease lease duration. - * @return Description of the Returned Value - */ - private boolean sendLease(ClientConnection pConn, long lease) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending lease (" + lease + ") to " + pConn.getPeerName()); - } - - Message msg = new Message(); - - msg.addMessageElement("jxta", new TextDocumentMessageElement(ConnectedRdvAdvReply, getPeerAdvertisementDoc(), null)); - - msg.addMessageElement("jxta", new StringMessageElement(ConnectedPeerReply, group.getPeerID().toString(), null)); - - msg.addMessageElement("jxta", new StringMessageElement(ConnectedLeaseReply, Long.toString(lease), null)); - - return pConn.sendMessage(msg, pName, pParam); - } - - /** - * {@inheritDoc} - */ - @Override - public void walk(Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException { - if (closed) { - return; - } - - msg = msg.clone(); - int useTTL = Math.min(initialTTL, MAX_TTL); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Undirected walk of " + msg + "(TTL=" + useTTL + ") to :" + "\n\tsvc name:" + serviceName + "\tsvc params:" - + serviceParam); - } - - msg.replaceMessageElement("jxta", new StringMessageElement(RDV_WALK_SVC_NAME, serviceName, null)); - - msg.replaceMessageElement("jxta", new StringMessageElement(RDV_WALK_SVC_PARAM, serviceParam, null)); - - try { - walker.walkMessage(null, msg, pName, pParam, useTTL); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.walk(); - } - } catch (IOException failure) { - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.walkFailed(); - } - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Cannot send message with Walker", failure); - } - - throw failure; - } - } - - /** - * {@inheritDoc} - */ - @Override - public void walk(Vector destPeerIDs, Message msg, String serviceName, String serviceParam, int initialTTL) throws IOException { - if (closed) { - return; - } - - msg = msg.clone(); - int useTTL = Math.min(initialTTL, MAX_TTL); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Directed walk of " + msg + "(TTL=" + useTTL + ") to :" + "\n\tsvc name:" + serviceName + "\tsvc params:" - + serviceParam); - } - - msg.replaceMessageElement("jxta", new StringMessageElement(RDV_WALK_SVC_NAME, serviceName, null)); - - msg.replaceMessageElement("jxta", new StringMessageElement(RDV_WALK_SVC_PARAM, serviceParam, null)); - - for (ID destPeerID : destPeerIDs) { - try { - walker.walkMessage((PeerID) destPeerID, msg.clone(), pName, pParam, useTTL); - } catch (IOException failed) { - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.walkToPeersFailed(); - } - - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Cannot send message with Walker to: " + destPeerID, failed); - } - - IOException failure = new IOException("Cannot send message with Walker to: " + destPeerID); - - failure.initCause(failed); - - throw failure; - } - } - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.walkToPeers(destPeerIDs.size()); - } - } - - /** - * Periodic cleanup task - */ - private class GCTask extends TimerTask { - - /** - * {@inheritDoc - */ - @Override - public void run() { - - try { - long gcStart = TimeUtils.timeNow(); - int gcedClients = 0; - - List allClients = Arrays.asList(clients.values().toArray()); - - for (Object allClient : allClients) { - ClientConnection pConn = (ClientConnection) allClient; - - try { - long now = TimeUtils.timeNow(); - - if (!pConn.isConnected() || (pConn.getLeaseEnd() < now)) { - // This client has dropped out or the lease is over. - // remove it. - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("GC CLIENT: dropping " + pConn); - } - - pConn.setConnected(false); - removeClient(pConn, false); - gcedClients++; - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "GCTask failed for " + pConn, e); - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Client GC " + gcedClients + " of " + allClients.size() + " clients completed in " - + TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), gcStart) + "ms."); - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } - } - } - - - /** - * @inheritDoc - */ - private class WalkListener implements EndpointListener { - - /** - * {@inheritDoc} - */ - public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - MessageElement serviceME = msg.getMessageElement("jxta", RDV_WALK_SVC_NAME); - - if (null == serviceME) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Discarding " + msg + " because its missing service name element"); - } - return; - } - - msg.removeMessageElement(serviceME); - String sName = serviceME.toString(); - - MessageElement paramME = msg.getMessageElement("jxta", RDV_WALK_SVC_PARAM); - - String sParam; - - if (null == paramME) { - sParam = null; - } else { - msg.removeMessageElement(paramME); - sParam = paramME.toString(); - } - - EndpointAddress realDest = new EndpointAddress(dstAddr, sName, sParam); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Calling local listener for [" + realDest.getServiceName() + " / " + realDest.getServiceParameter() - + "] with " + msg); - } - - rdvService.endpoint.processIncomingMessage(msg, srcAddr, realDest); - - if (RendezvousMeterBuildSettings.RENDEZVOUS_METERING && (rendezvousMeter != null)) { - rendezvousMeter.receivedMessageProcessedLocally(); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/ClientConnectionMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/ClientConnectionMeter.java deleted file mode 100644 index bb7d7de3..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/ClientConnectionMeter.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - - -import net.jxta.peer.*; -import net.jxta.endpoint.*; - - -/** - * The rendezvous's meter for a client peer interacting with a it - **/ -public class ClientConnectionMeter { - private PeerID peerID; - - private ClientConnectionMetric cumulativeMetrics; - private ClientConnectionMetric deltaMetrics; - - private long transitionTime = 0; - private long lastLeaseRenewalTime = 0; - - public ClientConnectionMeter(PeerID peerID) { - this.peerID = peerID; - cumulativeMetrics = new ClientConnectionMetric(peerID); - } - - public ClientConnectionMetric getCumulativeMetrics() { - return cumulativeMetrics; - } - - public synchronized ClientConnectionMetric collectMetrics() { - ClientConnectionMetric prevDelta = deltaMetrics; - - deltaMetrics = null; - return prevDelta; - } - - private void createDeltaMetric() { - deltaMetrics = new ClientConnectionMetric(cumulativeMetrics); - } - - public void clientConnectionEstablished(long lease) { - transitionTime = System.currentTimeMillis(); - - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.clientConnectionEstablished(transitionTime, lease); - cumulativeMetrics.clientConnectionEstablished(transitionTime, lease); - } - - public void clientLeaseRenewed(long lease) { - lastLeaseRenewalTime = System.currentTimeMillis(); - - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.clientLeaseRenewed(lastLeaseRenewalTime, lease); - cumulativeMetrics.clientLeaseRenewed(lastLeaseRenewalTime, lease); - } - - public void errorAddingClient() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.errorAddingClient(); - cumulativeMetrics.errorAddingClient(); - } - - public void clientConnectionDisconnected(boolean normal) { - transitionTime = System.currentTimeMillis(); - - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.clientConnectionDisconnected(normal, transitionTime); - cumulativeMetrics.clientConnectionDisconnected(normal, transitionTime); - } - - public void unableToRespondToConnectRequest() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.unableToRespondToConnectRequest(); - cumulativeMetrics.unableToRespondToConnectRequest(); - } - - public void clientConnectionRefused() { - transitionTime = System.currentTimeMillis(); - - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.clientConnectionRefused(transitionTime); - cumulativeMetrics.clientConnectionRefused(transitionTime); - } - - @Override - public String toString() { - return "ClientConnectionMeter(" + peerID + ")"; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/ClientConnectionMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/ClientConnectionMetric.java deleted file mode 100644 index ff9d9127..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/ClientConnectionMetric.java +++ /dev/null @@ -1,399 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - - -import net.jxta.impl.meter.*; -import net.jxta.rendezvous.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.peer.*; -import net.jxta.endpoint.*; -import net.jxta.util.*; -import net.jxta.exception.*; - -import java.util.*; - - -/** - * The rendezvous's metric for a client peer interacting with a it - **/ -public class ClientConnectionMetric implements DocumentSerializable { - public static final String CONNECTED = "connected"; - public static final String DISCONNECTED = "disconnected"; - public static final String REFUSED = "refused"; - - private PeerID peerID; - - private String state = null; - private long transitionTime; - private long lastLeaseRenewalTime; - - private long lease; - private int numConnects; - private int numLeaseRenewals; - private int numDisconnects; - private int numConnectionsRefused; - private int numErrorsAddingClient; - private int numUnableToRespondToConnectRequest; - - private long totalTimeConnected; - - public ClientConnectionMetric() {} - - public ClientConnectionMetric(PeerID peerID) { - this.peerID = peerID; - this.state = DISCONNECTED; - } - - public ClientConnectionMetric(ClientConnectionMetric prototype) { - this.peerID = prototype.peerID; - this.state = prototype.state; - this.transitionTime = prototype.transitionTime; - this.lastLeaseRenewalTime = prototype.lastLeaseRenewalTime; - this.lease = prototype.lease; - } - - /** Peer ID of this Client Connection **/ - public PeerID getPeerID() { - return peerID; - } - - /** - * State of Client Connection - * @return ClientConnectionMetric.CONNECTED, ClientConnectionMetric.DISCONNECTED or ClientConnectionMetric.REFUSED - **/ - public String getState() { - return state; - } - - /** Get the time that it entered the current state - * @return transition time in ms since January 1, 1970, 00:00:00 GMT - **/ - public long getTransitionTime() { - return transitionTime; - } - - /** Is this client connected **/ - public boolean isConnected() { - return (state != null) && state.equals(CONNECTED); - } - - /** Get time Connected - * @return time or 0 if not connected - **/ - public long getTimeConnectionEstablished() { - return isConnected() ? transitionTime : 0; - } - - /** Get time Connected - * @return time or 0 if not disconnected - **/ - public long getDisconnectTime() { - return isDisconnected() ? transitionTime : 0; - } - - /** Is this client disconnected **/ - public boolean isDisconnected() { - return (state != null) && (state.equals(DISCONNECTED) || state.equals(REFUSED)); - } - - /** Get Lease time granted for last lease Renewal Request. - * @see #getLastLeaseRenewalTime() - **/ - public long getLease() { - return lease; - } - - /** Get Last Received Lease Renewal Time - * @see #getLease() - **/ - public long getLastLeaseRenewalTime() { - return lastLeaseRenewalTime; - } - - /** Get number of granted connect messages received from this peer **/ - public int getNumConnects() { - return numConnects; - } - - /** Get number of granted lease renewal messages received from this peer **/ - public int getNumLeaseRenewals() { - return numLeaseRenewals; - } - - /** Get number of disconnect messages received from this peer **/ - public int getNumDisconnects() { - return numDisconnects; - } - - /** Get number of refused connect/lease-renewal messages received from this peer **/ - public int getNumConnectionsRefused() { - return numConnectionsRefused; - } - - /** Get number of errors when attempting to add this peer as a client **/ - public int getNumErrorsAddingClient() { - return numErrorsAddingClient; - } - - /** Get number of errors when attempting to respond to this peer's request**/ - public int getNumUnableToRespondToConnectRequest() { - return numUnableToRespondToConnectRequest; - } - - /** Get the total time this peer has been connected. - *

            - * Note: This does not include the current time connected (if it is currently connected) - * @see #getTotalTimeConnected(long) - * @return time in ms (see note above) - **/ - public long getTotalTimeConnected() { - return totalTimeConnected; - } - - /** Get the total time this peer has been connected. If it is currently - * connected, then the total time is adjusted to include the time since the transition time - * to become connected until the provided time - * @param adjustmentTime The time of this metric will be adjusted to - * @see #getTotalTimeConnected() - * @return time in ms (see note above) - **/ - public long getTotalTimeConnected(long adjustmentTime) { - long result = totalTimeConnected; - - if (isConnected()) { - result += (adjustmentTime - this.transitionTime); - } - - return result; - } - - /** Get the duration of current connection relative to local clock (from transition time) - *

            - * Note: This assumes the clocks are in sync with the reporting peer - * @see #getTotalTimeConnected(long) - * @return time in ms (see note above) or 0 if not connected - **/ - public long getTimeConnected() { - return getTimeConnected(System.currentTimeMillis()); - } - - /** Get the duration of current connection until the specified time - * @param adjustmentTime The time of this metric will be computed until - * @see #getTimeConnected() - * @return time in ms (see note above) or 0 if not connected - **/ - public long getTimeConnected(long adjustmentTime) { - - if (isConnected()) { - return (adjustmentTime - this.transitionTime); - } else { - return 0; - } - } - - private void resetState(String state, long transitionTime) { - if (isConnected()) { - totalTimeConnected += (System.currentTimeMillis() - this.transitionTime); - } - - this.state = state; - this.transitionTime = transitionTime; - } - - void clientConnectionEstablished(long transitionTime, long lease) { - resetState(CONNECTED, transitionTime); - - this.numConnects++; - this.lease = lease; - } - - void clientLeaseRenewed(long lastLeaseRenewalTime, long lease) { - this.numLeaseRenewals++; - this.lease = lease; - this.lastLeaseRenewalTime = System.currentTimeMillis(); - - if (!isConnected()) { - resetState(CONNECTED, lastLeaseRenewalTime); - } - } - - void errorAddingClient() { - this.numErrorsAddingClient++; - ; - } - - void clientConnectionDisconnected(boolean normal, long transitionTime) { - resetState(DISCONNECTED, transitionTime); - this.numDisconnects++; - this.lease = 0; - } - - void unableToRespondToConnectRequest() { - this.numUnableToRespondToConnectRequest++; - } - - void clientConnectionRefused(long transitionTime) { - if (!isDisconnected()) { - clientConnectionDisconnected(false, transitionTime); - } - - this.transitionTime = transitionTime; - this.numConnectionsRefused++; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - if (peerID != null) { - DocumentSerializableUtilities.addString(element, "peerID", peerID.toString()); - } - if (state != null) { - DocumentSerializableUtilities.addString(element, "state", state); - } - if (transitionTime != 0) { - DocumentSerializableUtilities.addLong(element, "transitionTime", transitionTime); - } - if (lastLeaseRenewalTime != 0) { - DocumentSerializableUtilities.addLong(element, "lastLeaseRenewalTime", lastLeaseRenewalTime); - } - if (lease != 0) { - DocumentSerializableUtilities.addLong(element, "lease", lease); - } - if (numConnects != 0) { - DocumentSerializableUtilities.addInt(element, "numConnects", numConnects); - } - if (numLeaseRenewals != 0) { - DocumentSerializableUtilities.addInt(element, "numLeaseRenewals", numLeaseRenewals); - } - if (numDisconnects != 0) { - DocumentSerializableUtilities.addInt(element, "numDisconnects", numDisconnects); - } - if (numConnectionsRefused != 0) { - DocumentSerializableUtilities.addInt(element, "numConnectionsRefused", numConnectionsRefused); - } - if (numErrorsAddingClient != 0) { - DocumentSerializableUtilities.addInt(element, "numErrorsAddingClient", numErrorsAddingClient); - } - if (numUnableToRespondToConnectRequest != 0) { - DocumentSerializableUtilities.addInt(element, "numUnableToRespondToConnectRequest", numUnableToRespondToConnectRequest); - } - if (totalTimeConnected != 0) { - DocumentSerializableUtilities.addLong(element, "totalTimeConnected", totalTimeConnected); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - state = null; - - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("peerID")) { - String peerIDText = DocumentSerializableUtilities.getString(childElement); - - peerID = MetricUtilities.getPeerIdFromString(peerIDText); - } else if (tagName.equals("state")) { - state = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("transitionTime")) { - transitionTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("lastLeaseRenewalTime")) { - lastLeaseRenewalTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("lease")) { - lease = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numConnects")) { - numConnects = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numLeaseRenewals")) { - numLeaseRenewals = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numDisconnects")) { - numDisconnects = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numConnectionsRefused")) { - numConnectionsRefused = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numErrorsAddingClient")) { - numErrorsAddingClient = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numUnableToRespondToConnectRequest")) { - numUnableToRespondToConnectRequest = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("totalTimeConnected")) { - totalTimeConnected = DocumentSerializableUtilities.getLong(childElement); - } - } - } - - public void mergeMetrics(ClientConnectionMetric otherClientConnectionMetric) { - if (otherClientConnectionMetric == null) { - return; - } - - if (otherClientConnectionMetric.state != null) { - state = otherClientConnectionMetric.state; - } - - if (otherClientConnectionMetric.transitionTime != 0) { - transitionTime = otherClientConnectionMetric.transitionTime; - } - - lease = otherClientConnectionMetric.lease; - - numConnects += otherClientConnectionMetric.numConnects; - numLeaseRenewals += otherClientConnectionMetric.numLeaseRenewals; - numDisconnects += otherClientConnectionMetric.numDisconnects; - numConnectionsRefused += otherClientConnectionMetric.numConnectionsRefused; - numErrorsAddingClient += otherClientConnectionMetric.numErrorsAddingClient; - numUnableToRespondToConnectRequest += otherClientConnectionMetric.numUnableToRespondToConnectRequest; - totalTimeConnected += otherClientConnectionMetric.totalTimeConnected; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/ConditionalRendezvousMeterBuildSettings.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/ConditionalRendezvousMeterBuildSettings.java deleted file mode 100644 index 921f0f03..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/ConditionalRendezvousMeterBuildSettings.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * The Sun Project JXTA(TM) Software License - * - * Copyright (c) 2001-2006 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: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at https://jxta.dev.java.net. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * https://jxta.dev.java.net/ - * - * This license is based on the BSD license adopted by the Apache Foundation. - * - */ - - -/* **** THIS IS A GENERATED FILE. DO NOT EDIT. **** */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - -import java.util.ResourceBundle; -import net.jxta.impl.meter.*; - -public class ConditionalRendezvousMeterBuildSettings { - public static boolean isRuntimeMetering() { - boolean runtimeMetering = false; - - try { - ResourceBundle userResourceBundle = ResourceBundle.getBundle( "net.jxta.user" ); - String meteringProperty = "net.jxta.meter.conditionalRendezvousMetering"; - String meteringValue = userResourceBundle.getString( meteringProperty ); - runtimeMetering = "on".equalsIgnoreCase( meteringValue ); - } catch (Exception ignored) { - } - - return runtimeMetering; - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousConnectionMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousConnectionMeter.java deleted file mode 100644 index a0919e5c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousConnectionMeter.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - - -import net.jxta.peer.*; - - -/** - * The meter about a client peer's connection to a rendezvous - **/ -public class RendezvousConnectionMeter { - private PeerID peerID; - - private RendezvousConnectionMetric cumulativeMetrics; - private RendezvousConnectionMetric deltaMetrics; - - private long transitionTime = 0; - private long lastLeaseRenewalTime = 0; - - public RendezvousConnectionMeter(PeerID peerID) { - this.peerID = peerID; - cumulativeMetrics = new RendezvousConnectionMetric(peerID); - } - - public RendezvousConnectionMetric getCumulativeMetrics() { - return cumulativeMetrics; - } - - public PeerID getPeerID() { - return peerID; - } - - public String getState() { - return cumulativeMetrics.getState(); - } - - public synchronized RendezvousConnectionMetric collectMetrics() { - RendezvousConnectionMetric prevDelta = deltaMetrics; - - deltaMetrics = null; - return prevDelta; - } - - private void createDeltaMetric() { - deltaMetrics = new RendezvousConnectionMetric(cumulativeMetrics); - } - - @Override - public String toString() { - return "RendezvousConnectionMeter(" + peerID + ")"; - } - - public void beginConnection() { - transitionTime = System.currentTimeMillis(); - - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.beginConnection(transitionTime); - cumulativeMetrics.beginConnection(transitionTime); - } - - public void connectionEstablished(long lease) { - long now = System.currentTimeMillis(); - long timeToConnect = now - transitionTime; - - transitionTime = now; - - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.connectionEstablished(transitionTime, timeToConnect, lease); - cumulativeMetrics.connectionEstablished(transitionTime, timeToConnect, lease); - } - - public void leaseRenewed(long lease) { - lastLeaseRenewalTime = System.currentTimeMillis(); - - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.leaseRenewed(lastLeaseRenewalTime, lease); - cumulativeMetrics.leaseRenewed(lastLeaseRenewalTime, lease); - } - - public void connectionRefused() { - transitionTime = System.currentTimeMillis(); - - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.connectionRefused(transitionTime); - cumulativeMetrics.connectionRefused(transitionTime); - } - - public void connectionDisconnected() { - transitionTime = System.currentTimeMillis(); - - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.connectionDisconnected(transitionTime); - cumulativeMetrics.connectionDisconnected(transitionTime); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousConnectionMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousConnectionMetric.java deleted file mode 100644 index 89421caf..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousConnectionMetric.java +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystem, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - - -import net.jxta.rendezvous.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.peer.*; -import net.jxta.endpoint.*; -import net.jxta.util.*; -import net.jxta.exception.*; -import net.jxta.impl.meter.*; -import java.util.*; - - -/** - * The metrics about a client peer's connection to a rendezvous - **/ -public class RendezvousConnectionMetric implements DocumentSerializable { - public static final String CONNECTING = "connecting"; - public static final String CONNECTED = "connected"; - public static final String DISCONNECTED = "disconnected"; - public static final String REFUSED = "refused"; - - private PeerID peerID; - - private String state = null; - private long transitionTime; - - private long lease; - private int numConnectionsBegun = 0; - private int numConnectionsEstablished = 0; - private int numConnectionsRefused = 0; - private long totalTimesToConnect; - private long totalTimeConnected; - - private long lastLeaseRenewalTime; - private int numLeaseRenewals; - - private int numDisconnects; - - public RendezvousConnectionMetric() {} - - public RendezvousConnectionMetric(PeerID peerID) { - this.peerID = peerID; - this.state = DISCONNECTED; - } - - public RendezvousConnectionMetric(RendezvousConnectionMetric prototype) { - this.peerID = prototype.peerID; - this.state = prototype.state; - this.transitionTime = prototype.transitionTime; - this.lastLeaseRenewalTime = prototype.lastLeaseRenewalTime; - this.lease = prototype.lease; - } - - /** Peer ID of Rendezvous **/ - public PeerID getPeerID() { - return peerID; - } - - /** - * State of Client Rendezvous - * @return RendezvousConnectionMetric.CONNECTING, RendezvousConnectionMetric.CONNECTED, RendezvousConnectionMetric.DISCONNECTED or RendezvousConnectionMetric.REFUSED - **/ - public String getState() { - return state; - } - - /** Get the time that it entered the current state - * @return transition time in ms since January 1, 1970, 00:00:00 GMT - **/ - public long getTransitionTime() { - return transitionTime; - } - - /** Is connecting to Rendezvous **/ - public boolean isConnecting() { - return (state != null) && state.equals(CONNECTING); - } - - /** Get time began connecting to Rendezvous - * @return time began or 0 if not connecting - **/ - public long getBeginConnectionTime() { - return isConnecting() ? transitionTime : 0; - } - - /** Is connected to Rendezvous **/ - public boolean isConnected() { - return (state != null) && state.equals(CONNECTED); - } - - /** Get time connected to Rendezvous - * @return time began or 0 if not connected - **/ - public long getTimeConnectionEstablished() { - return isConnected() ? transitionTime : 0; - } - - /** Get lease establised with Rendezvous **/ - public long getLease() { - return lease; - } - - /** Get Number of Connections begun with Rendezvous **/ - public int getNumConnectionsBegun() { - return numConnectionsBegun; - } - - /** Get Number of Connections established with Rendezvous **/ - public int getNumConnectionsEstablished() { - return numConnectionsEstablished; - } - - /** Get Number of Connections refused by Rendezvous **/ - public int getNumConnectionsRefused() { - return numConnectionsRefused; - } - - /** Get Sum of times it took to connect **/ - public long getTotalTimesToConnect() { - return totalTimesToConnect; - } - - /** Get Last Lease Renewal Time **/ - public long getLastLeaseRenewalTime() { - return lastLeaseRenewalTime; - } - - /** Get Number of lease Renewals **/ - public int getNumLeaseRenewals() { - return numLeaseRenewals; - } - - /** Get Number of Disconnects **/ - public int getNumDisconnects() { - return numDisconnects; - } - - /** Get time disconnected to Rendezvous - * @return time began or 0 if not disconnected - **/ - public long getDisconnectTime() { - return isDisconnected() ? transitionTime : 0; - } - - /** Have we disconnected fromthis Rendezvous **/ - public boolean isDisconnected() { - return (state != null) && (state.equals(DISCONNECTED) || state.equals(REFUSED)); - } - - /** Get the total time this peer has been connected. - *

            - * Note: This does not include the current time connected (if it is currently connected) - * @see #getTotalTimeConnected(long) - * @return time in ms (see note above) - **/ - public long getTotalTimeConnected() { - return totalTimeConnected; - } - - /** Get the total time this peer has been connected. If it is currently - * connected, then the total time is adjusted to include the time since the transition time - * to become connected until the provided time - * @param adjustmentTime The time of this metric will be adjusted to - * @see #getTotalTimeConnected() - * @return time in ms (see note above) - **/ - public long getTotalTimeConnected(long adjustmentTime) { - long result = totalTimeConnected; - - if (isConnected()) { - result += (adjustmentTime - this.transitionTime); - } - - return result; - } - - /** Get the duration of current connection relative to local clock (from transition time) - *

            - * Note: This assumes the clocks are in sync with the reporting peer - * @see #getTotalTimeConnected(long) - * @return time in ms (see note above) or 0 if not connected - **/ - public long getTimeConnected() { - return getTimeConnected(System.currentTimeMillis()); - } - - /** Get the duration of current connection until the specified time - * @param adjustmentTime The time of this metric will be computed until - * @see #getTimeConnected() - * @return time in ms (see note above) or 0 if not connected - **/ - public long getTimeConnected(long adjustmentTime) { - - if (isConnected()) { - return (adjustmentTime - this.transitionTime); - } else { - return 0; - } - } - - private void resetState(String state, long transitionTime) { - if (isConnected()) { - totalTimeConnected += (System.currentTimeMillis() - this.transitionTime); - } - - this.state = state; - this.transitionTime = transitionTime; - } - - void beginConnection(long transitionTime) { - resetState(CONNECTING, transitionTime); - - this.numConnectionsBegun++; - } - - void connectionEstablished(long transitionTime, long timeToConnectTime, long lease) { - resetState(CONNECTED, transitionTime); - this.totalTimesToConnect += timeToConnectTime; - this.numConnectionsEstablished++; - - this.lease = lease; - } - - void leaseRenewed(long lastLeaseRenewalTime, long lease) { - this.numLeaseRenewals++; - - this.lastLeaseRenewalTime = lastLeaseRenewalTime; - this.lease = lease; - - if (!isConnected()) { - resetState(CONNECTED, lastLeaseRenewalTime); - } - } - - void connectionRefused(long transitionTime) { - resetState(REFUSED, lastLeaseRenewalTime); - numConnectionsRefused++; - } - - void connectionDisconnected(long transitionTime) { - resetState(DISCONNECTED, lastLeaseRenewalTime); - - numDisconnects++; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof RendezvousConnectionMetric) { - RendezvousConnectionMetric other = (RendezvousConnectionMetric) obj; - - return (peerID.equals(other.peerID)); - } else { - return false; - } - } - - @Override - public int hashCode() { - return peerID.hashCode(); - } - - public void serializeTo(Element element) throws DocumentSerializationException { - if (peerID != null) { - DocumentSerializableUtilities.addString(element, "peerID", peerID.toString()); - } - if (state != null) { - DocumentSerializableUtilities.addString(element, "state", state); - } - if (transitionTime != 0) { - DocumentSerializableUtilities.addLong(element, "transitionTime", transitionTime); - } - if (lease != 0) { - DocumentSerializableUtilities.addLong(element, "lease", lease); - } - if (numConnectionsBegun != 0) { - DocumentSerializableUtilities.addInt(element, "numConnectionsBegun", numConnectionsBegun); - } - if (numConnectionsEstablished != 0) { - DocumentSerializableUtilities.addInt(element, "numConnectionsEstablished", numConnectionsEstablished); - } - if (numConnectionsRefused != 0) { - DocumentSerializableUtilities.addInt(element, "numConnectionsRefused", numConnectionsRefused); - } - if (totalTimesToConnect != 0) { - DocumentSerializableUtilities.addLong(element, "totalTimesToConnect", totalTimesToConnect); - } - if (totalTimeConnected != 0) { - DocumentSerializableUtilities.addLong(element, "totalTimeConnected", totalTimeConnected); - } - if (lastLeaseRenewalTime != 0) { - DocumentSerializableUtilities.addLong(element, "lastLeaseRenewalTime", lastLeaseRenewalTime); - } - if (numLeaseRenewals != 0) { - DocumentSerializableUtilities.addInt(element, "numLeaseRenewals", numLeaseRenewals); - } - if (numDisconnects != 0) { - DocumentSerializableUtilities.addInt(element, "numDisconnects", numDisconnects); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("peerID")) { - String peerIDText = DocumentSerializableUtilities.getString(childElement); - - peerID = MetricUtilities.getPeerIdFromString(peerIDText); - } else if (tagName.equals("state")) { - state = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("transitionTime")) { - transitionTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("lease")) { - lease = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numConnectionsBegun")) { - numConnectionsBegun = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numConnectionsEstablished")) { - numConnectionsEstablished = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numConnectionsRefused")) { - numConnectionsRefused = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("totalTimesToConnect")) { - totalTimesToConnect = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("totalTimeConnected")) { - totalTimeConnected = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("lastLeaseRenewalTime")) { - lastLeaseRenewalTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numLeaseRenewals")) { - numLeaseRenewals = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numDisconnects")) { - numDisconnects = DocumentSerializableUtilities.getInt(childElement); - } - } - } - - public void mergeMetrics(RendezvousConnectionMetric otherRendezvousConnectionMetric) { - if (otherRendezvousConnectionMetric == null) { - return; - } - - if (otherRendezvousConnectionMetric.state != null) { - state = otherRendezvousConnectionMetric.state; - } - - if (otherRendezvousConnectionMetric.transitionTime != 0) { - transitionTime = otherRendezvousConnectionMetric.transitionTime; - } - - if (otherRendezvousConnectionMetric.lastLeaseRenewalTime != 0) { - lastLeaseRenewalTime = otherRendezvousConnectionMetric.transitionTime; - } - - lease = otherRendezvousConnectionMetric.lease; - - numConnectionsBegun += otherRendezvousConnectionMetric.numConnectionsBegun; - numConnectionsEstablished += otherRendezvousConnectionMetric.numConnectionsEstablished; - numConnectionsRefused += otherRendezvousConnectionMetric.numConnectionsRefused; - totalTimeConnected += otherRendezvousConnectionMetric.totalTimeConnected; - - numLeaseRenewals += otherRendezvousConnectionMetric.numLeaseRenewals; - - numDisconnects += otherRendezvousConnectionMetric.numDisconnects; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousMeter.java deleted file mode 100644 index 4059bba4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousMeter.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - - -import net.jxta.peer.*; -import net.jxta.peergroup.*; -import net.jxta.rendezvous.*; -import net.jxta.impl.rendezvous.*; -import java.net.*; -import java.util.*; - - -/** - The Meter corresponding to the state and aggregate information of a Rendezvous Service - **/ -public class RendezvousMeter { - private RendezvousMetric cumulativeMetrics; - private RendezvousMetric deltaMetrics; - - private long transitionTime = System.currentTimeMillis(); - - public RendezvousMeter() { - cumulativeMetrics = new RendezvousMetric(null); - } - - public RendezvousMetric getCumulativeMetrics() { - return cumulativeMetrics; - } - - public synchronized RendezvousMetric collectMetrics() { - RendezvousMetric prevDelta = deltaMetrics; - - deltaMetrics = null; - - return prevDelta; - } - - private void createDeltaMetric() { - deltaMetrics = new RendezvousMetric(cumulativeMetrics); - } - - @Override - public String toString() { - return "RendezvousMeter"; - } - - public void startEdge() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - transitionTime = System.currentTimeMillis(); - deltaMetrics.startEdge(transitionTime); - cumulativeMetrics.startEdge(transitionTime); - } - - public void stopEdge() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - long now = System.currentTimeMillis(); - long timeAsEdge = now - transitionTime; - - transitionTime = now; - - if (!cumulativeMetrics.isEdge()) { - timeAsEdge = 0; - } - - deltaMetrics.stopEdge(now, timeAsEdge); - cumulativeMetrics.stopEdge(now, timeAsEdge); - } - - public void startRendezvous() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - transitionTime = System.currentTimeMillis(); - deltaMetrics.startRendezvous(transitionTime); - cumulativeMetrics.startRendezvous(transitionTime); - } - - public void stopRendezvous() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - long now = System.currentTimeMillis(); - long timeAsRendezvous = cumulativeMetrics.isRendezvous() ? (now - transitionTime) : 0; - - transitionTime = now; - - deltaMetrics.stopRendezvous(now, timeAsRendezvous); - cumulativeMetrics.stopRendezvous(now, timeAsRendezvous); - } - - public void invalidMessageReceived() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.invalidMessageReceived(); - cumulativeMetrics.invalidMessageReceived(); - } - - public void receivedMessageProcessedLocally() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.receivedMessageProcessedLocally(); - cumulativeMetrics.receivedMessageProcessedLocally(); - } - - public void receivedMessageRepropagatedInGroup() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.receivedMessageRepropagatedInGroup(); - cumulativeMetrics.receivedMessageRepropagatedInGroup(); - } - - public void receivedDeadMessage() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.receivedDeadMessage(); - cumulativeMetrics.receivedDeadMessage(); - } - - public void receivedLoopbackMessage() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.receivedLoopbackMessage(); - cumulativeMetrics.receivedLoopbackMessage(); - } - - public void receivedDuplicateMessage() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.receivedDuplicateMessage(); - cumulativeMetrics.receivedDuplicateMessage(); - } - - public void propagateToPeers(int numPeers) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.propagateToPeers(numPeers); - cumulativeMetrics.propagateToPeers(numPeers); - } - - public void propagateToNeighbors() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.propagateToNeighbors(); - cumulativeMetrics.propagateToNeighbors(); - } - - public void propagateToNeighborsFailed() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.propagateToNeighborsFailed(); - cumulativeMetrics.propagateToNeighborsFailed(); - } - - public void propagateToGroup() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.propagateToGroup(); - cumulativeMetrics.propagateToGroup(); - } - - public void walk() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.walk(); - cumulativeMetrics.walk(); - } - - public void walkFailed() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.walkFailed(); - cumulativeMetrics.walkFailed(); - } - - public void walkToPeers(int numPeers) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.walkToPeers(numPeers); - cumulativeMetrics.walkToPeers(numPeers); - } - - public void walkToPeersFailed() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.walkToPeersFailed(); - cumulativeMetrics.walkToPeersFailed(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousMeterBuildSettings.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousMeterBuildSettings.java deleted file mode 100644 index 39898554..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousMeterBuildSettings.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * The Sun Project JXTA(TM) Software License - * - * Copyright (c) 2001-2006 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: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at https://jxta.dev.java.net. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * https://jxta.dev.java.net/ - * - * This license is based on the BSD license adopted by the Apache Foundation. - * - */ - - -/* **** THIS IS A GENERATED FILE. DO NOT EDIT. **** */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - -import net.jxta.impl.meter.*; - -public interface RendezvousMeterBuildSettings extends MeterBuildSettings { - public static final boolean RENDEZVOUS_METERING = ConditionalRendezvousMeterBuildSettings.isRuntimeMetering(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousMetric.java deleted file mode 100644 index 719c0f0e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousMetric.java +++ /dev/null @@ -1,666 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - - -import net.jxta.rendezvous.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; - -import java.util.*; - - -/** - The Metric corresponding to the state and aggregate information of a Rendezvous Service - **/ -public class RendezvousMetric implements DocumentSerializable { - - public static final String EDGE = "edge"; - public static final String RENDEZVOUS = "rendezvous"; - public static final String STOPPED = "stopped"; // but internally represent as null - - private String state = null; - private long transitionTime = 0; - - private long totalEdgeTime; - private int numEdgeTransitions; - - private long totalRendezvousTime; - private long numRendezvousTransitions; - - private int numReceivedProcessedLocally; - private int numReceivedRepropagatedInGroup; - private int numReceivedInvalid; - private int numReceivedDead; - private int numReceivedLoopback; - private int numReceivedDuplicate; - - private int numPropagated; - private int numFailedPropagating; - private int numRepropagated; - private int numFailedRepropagating; - - private int numPropagatedToPeers; - private int numFailedPropagatingToPeers; - private int numPeersPropagatedTo; - - private int numPropagatedInGroup; - - private int numPropagatedToNeighbors; - private int numFailedPropagatingToNeighbors; - - private int numWalks; - private int numFailedWalks; - - private int numWalkedToPeers; - private int numFailedWalkToPeers; - private int numPeersWalkedTo; - - public RendezvousMetric() {} - - public RendezvousMetric(RendezvousMetric prototype) { - if (prototype == null) { - this.state = STOPPED; - } else { - this.state = prototype.state; - this.transitionTime = prototype.transitionTime; - } - } - - /** Get the current state (edge, rendezvous or stopped) - * @return RendezvousMetric.EDGE, RendezvousMetric.RENDEZVOUS or RendezvousMetric.STOPPED - **/ - public String getState() { - return (state != null) ? state : STOPPED; - } - - /** Get the time that it entered the current state - * @return transition time in ms since January 1, 1970, 00:00:00 GMT - **/ - public long getTransitionTime() { - return transitionTime; - } - - /** Is this Rendezvous currently operating as an Edge **/ - public boolean isEdge() { - return (state != null) && state.equals(EDGE); - } - - /** Is this Rendezvous currently operating as an Rendezvous */ - public boolean isRendezvous() { - return (state != null) && state.equals(RENDEZVOUS); - } - - /** Get the time that it began operating as an Edge - * @return time or 0 if it is not currently an Edge - **/ - public long getEdgeStartTime() { - return isEdge() ? transitionTime : 0; - } - - /** Get the total time it began operating as an Edge. - *

            - * Note: This does not include the current time as edge (if it is currently an edge) - * @see #getTotalEdgeTime(long) - * @return time in ms (see note above) - **/ - public long getTotalEdgeTime() { - return totalEdgeTime; - } - - /** Get the total time it began operating as an Edge. If it is currently operating as - * an edge, then the total time is adjusted to include the time since the transition time - * to an edge until the provided time - * @param adjustmentTime The time of this metric will be adjusted to - * @see #getTotalEdgeTime() - * @return time in ms (see note above) - **/ - public long getTotalEdgeTime(long adjustmentTime) { - long result = totalEdgeTime; - - if (isEdge()) { - result += (adjustmentTime - this.transitionTime); - } - - return result; - } - - /** The number of times the peer has become an edge **/ - public int getNumEdgeTransitions() { - return numEdgeTransitions; - } - - /** Get the time that it began operating as an Rendezvous - * @return time or 0 if it is not currently an Rendezvous - **/ - public long getRendezvousStartTime() { - return isRendezvous() ? transitionTime : 0; - } - - /** Get the total time it began operating as an Rendezvous. - *

            - * Note: This does not include the current time as rendezvous (if it is currently an rendezvous) - * @see #getTotalRendezvousTime(long) - * @return time in ms (see note above) - **/ - public long getTotalRendezvousTime() { - return totalRendezvousTime; - } - - /** Get the total time it began operating as an Rendezvous. If it is currently operating as - * a rendezvous, then the total time is adjusted to include the time since the transition time - * to an rendezvous until the provided time - * @param adjustmentTime The time of this metric will be adjusted to - * @see #getTotalRendezvousTime() - * @return time in ms (see note above) - **/ - public long getTotalRendezvousTime(long adjustmentTime) { - long result = totalRendezvousTime; - - if (isRendezvous()) { - result += (adjustmentTime - this.transitionTime); - } - - return result; - } - - /** The number of times the peer has become an rendezvous **/ - public long getNumRendezvousTransitions() { - return numRendezvousTransitions; - } - - /** The number of messages received that were sent to local listeners **/ - public int getNumReceivedProcessedLocally() { - return numReceivedProcessedLocally; - } - - /** The number of messages received that were repropagated to the group **/ - public int getNumReceivedRepropagatedInGroup() { - return numReceivedRepropagatedInGroup; - } - - /** The number of invalid messages received **/ - public int getNumReceivedInvalid() { - return numReceivedInvalid; - } - - /** The number of TTL Dead messages received **/ - public int getNumReceivedDead() { - return numReceivedDead; - } - - /** The number of messages received that originated at peer **/ - public int getNumReceivedLoopback() { - return numReceivedLoopback; - } - - /** The number of duplicate messages received **/ - public int getNumReceivedDuplicate() { - return numReceivedDuplicate; - } - - /** The total number of inbound messages to the rendezvous service that could not be delivered**/ - public int getTotalReceivedUndelivered() { - return numReceivedInvalid + numReceivedDead + numReceivedLoopback + numReceivedDuplicate; - } - - /** The total number of inbound messages to the rendezvous service **/ - public int getTotalReceived() { - return getTotalReceivedUndelivered() + numReceivedProcessedLocally + numReceivedRepropagatedInGroup; - } - - /** The number of outbound messages propagated **/ - public int getNumPropagated() { - return numPropagated; - } - - /** The number of outbound messages failed during propagation **/ - public int getNumFailedPropagating() { - return numFailedPropagating; - } - - /** The number of outbound messages repropagated **/ - public int getNumRepropagated() { - return numRepropagated; - } - - /** The number of outbound messages failed during repropagation **/ - public int getNumFailedRepropagating() { - return numFailedRepropagating; - } - - /** The number of outbound messages propagated to peers **/ - public int getNumPropagatedToPeers() { - return numPropagatedToPeers; - } - - /** The number of outbound messages failed when propagated to peers **/ - public int getNumFailedPropagatingToPeers() { - return numFailedPropagatingToPeers; - } - - /** The number of peers that outbound messages were propagated to **/ - public int getNumPeersPropagatedTo() { - return numPeersPropagatedTo; - } - - /** The number of outbound messages propagated in group **/ - public int getNumPropagatedInGroup() { - return numPropagatedInGroup; - } - - /** The number of outbound messages propagated to neighbors **/ - public int getNumPropagatedToNeighbors() { - return numPropagatedToNeighbors; - } - - /** The number of outbound messages failed when propagated to neighbors **/ - public int getNumFailedPropagatingToNeighbors() { - return numFailedPropagatingToNeighbors; - } - - /** The number of outbound messages walked **/ - public int getNumWalks() { - return numWalks; - } - - /** The number of outbound messages failed attempting walk **/ - public int getNumFailedWalks() { - return numFailedWalks; - } - - /** The number of outbound messages walked to a set of peers **/ - public int getNumWalkedToPeers() { - return numWalkedToPeers; - } - - /** The number of outbound messages failed in an attempt to walk to a set of peers **/ - public int getNumFailedWalkToPeers() { - return numFailedWalkToPeers; - } - - /** The number of peers that outbound messages were walked to **/ - public int getNumPeersWalkedTo() { - return numPeersWalkedTo; - } - - /** Get the duration of current transition to an edge - *

            - * Note: This assumes the clocks are in sync with the reporting peer - * @see #getTimeAsEdge(long) - * @return time in ms (see note above) or 0 if not edge - **/ - public long getTimeAsEdge() { - return getTimeAsEdge(System.currentTimeMillis()); - } - - /** Get the duration of time became an edge until the specified time - * @param adjustmentTime The time of this metric will be computed until - * @see #getTimeAsEdge() - * @return time in ms (see note above) or 0 if not connected - **/ - public long getTimeAsEdge(long adjustmentTime) { - if (isEdge()) { - return (adjustmentTime - this.transitionTime); - } else { - return 0; - } - } - - /** Get the duration of current transition to a rendezvous - *

            - * Note: This assumes the clocks are in sync with the reporting peer - * @see #getTimeAsRendezvous(long) - * @return time in ms (see note above) or 0 if not edge - **/ - public long getTimeAsRendezvous() { - return getTimeAsRendezvous(System.currentTimeMillis()); - } - - /** Get the duration of time became an rendezvous until the specified time - * @param adjustmentTime The time of this metric will be computed until - * @see #getTimeAsRendezvous() - * @return time in ms (see note above) or 0 if not connected - **/ - public long getTimeAsRendezvous(long adjustmentTime) { - if (isRendezvous()) { - return (adjustmentTime - this.transitionTime); - } else { - return 0; - } - } - - void startEdge(long transitionTime) { - this.transitionTime = transitionTime; - this.state = EDGE; - this.numEdgeTransitions++; - } - - void stopEdge(long transitionTime, long timeAsEdge) { - this.state = STOPPED; - this.transitionTime = transitionTime; - this.totalEdgeTime += timeAsEdge; - } - - void startRendezvous(long transitionTime) { - this.state = RENDEZVOUS; - this.transitionTime = transitionTime; - this.numRendezvousTransitions++; - } - - void stopRendezvous(long transitionTime, long timeAsRendezvous) { - this.state = STOPPED; - this.transitionTime = transitionTime; - this.totalRendezvousTime += timeAsRendezvous; - } - - void invalidMessageReceived() { - numReceivedInvalid++; - } - - void receivedMessageProcessedLocally() { - numReceivedProcessedLocally++; - } - - void receivedMessageRepropagatedInGroup() { - numReceivedRepropagatedInGroup++; - } - - void receivedDeadMessage() { - numReceivedDead++; - } - - void receivedLoopbackMessage() { - numReceivedLoopback++; - } - - void receivedDuplicateMessage() { - numReceivedDuplicate++; - } - - void propagateToPeers(int numPeers) { - numPropagatedToPeers++; - numPeersPropagatedTo += numPeers; - } - - void propagateToNeighbors() { - numPropagatedToNeighbors++; - } - - void propagateToNeighborsFailed() { - numFailedPropagatingToNeighbors++; - } - - void propagateToGroup() { - numPropagatedInGroup++; - } - - void walk() { - numWalks++; - } - - void walkFailed() { - numFailedWalks++; - } - - void walkToPeers(int numPeers) { - numWalkedToPeers++; - numPeersWalkedTo += numPeers; - } - - void walkToPeersFailed() { - numFailedWalkToPeers++; - } - - public void mergeMetrics(RendezvousMetric otherRendezvousMetric) { - if (otherRendezvousMetric == null) { - return; - } - - if (otherRendezvousMetric.state != null) { - state = otherRendezvousMetric.state; - } - - if (otherRendezvousMetric.transitionTime != 0) { - transitionTime = otherRendezvousMetric.transitionTime; - } - - this.totalEdgeTime += otherRendezvousMetric.totalEdgeTime; - this.numEdgeTransitions += otherRendezvousMetric.numEdgeTransitions; - - this.totalRendezvousTime += otherRendezvousMetric.totalRendezvousTime; - this.numRendezvousTransitions += otherRendezvousMetric.numRendezvousTransitions; - - this.numReceivedProcessedLocally += otherRendezvousMetric.numReceivedProcessedLocally; - this.numReceivedRepropagatedInGroup += otherRendezvousMetric.numReceivedRepropagatedInGroup; - - this.numReceivedInvalid += otherRendezvousMetric.numReceivedInvalid; - - this.numReceivedDead += otherRendezvousMetric.numReceivedDead; - this.numReceivedLoopback += otherRendezvousMetric.numReceivedLoopback; - this.numReceivedDuplicate += otherRendezvousMetric.numReceivedDuplicate; - - this.numPropagated += otherRendezvousMetric.numPropagated; - this.numFailedPropagating += otherRendezvousMetric.numFailedPropagating; - this.numRepropagated += otherRendezvousMetric.numRepropagated; - this.numFailedRepropagating += otherRendezvousMetric.numFailedRepropagating; - - this.numPropagatedToPeers += otherRendezvousMetric.numPropagatedToPeers; - this.numFailedPropagatingToPeers += otherRendezvousMetric.numFailedPropagatingToPeers; - this.numPeersPropagatedTo += otherRendezvousMetric.numPeersPropagatedTo; - - this.numPropagatedInGroup += otherRendezvousMetric.numPropagatedInGroup; - - this.numPropagatedToNeighbors += otherRendezvousMetric.numPropagatedToNeighbors; - this.numFailedPropagatingToNeighbors += otherRendezvousMetric.numFailedPropagatingToNeighbors; - - this.numWalks += otherRendezvousMetric.numWalks; - this.numFailedWalks += otherRendezvousMetric.numFailedWalks; - - this.numWalkedToPeers += otherRendezvousMetric.numWalkedToPeers; - this.numFailedWalkToPeers += otherRendezvousMetric.numFailedWalkToPeers; - this.numPeersWalkedTo += otherRendezvousMetric.numPeersWalkedTo; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - if (state != null) { - DocumentSerializableUtilities.addString(element, "state", state); - } - if (transitionTime != 0) { - DocumentSerializableUtilities.addLong(element, "transitionTime", transitionTime); - } - if (totalEdgeTime != 0) { - DocumentSerializableUtilities.addLong(element, "totalEdgeTime", totalEdgeTime); - } - if (numEdgeTransitions != 0) { - DocumentSerializableUtilities.addInt(element, "numEdgeTransitions", numEdgeTransitions); - } - if (totalRendezvousTime != 0) { - DocumentSerializableUtilities.addLong(element, "totalRendezvousTime", totalRendezvousTime); - } - if (numRendezvousTransitions != 0) { - DocumentSerializableUtilities.addLong(element, "numRendezvousTransitions", numRendezvousTransitions); - } - if (numReceivedProcessedLocally != 0) { - DocumentSerializableUtilities.addInt(element, "numReceivedProcessedLocally", numReceivedProcessedLocally); - } - if (numReceivedRepropagatedInGroup != 0) { - DocumentSerializableUtilities.addInt(element, "numReceivedRepropagatedInGroup", numReceivedRepropagatedInGroup); - } - if (numReceivedInvalid != 0) { - DocumentSerializableUtilities.addInt(element, "numReceivedInvalid", numReceivedInvalid); - } - if (numReceivedDead != 0) { - DocumentSerializableUtilities.addInt(element, "numReceivedDead", numReceivedDead); - } - if (numReceivedLoopback != 0) { - DocumentSerializableUtilities.addInt(element, "numReceivedLoopback", numReceivedLoopback); - } - if (numReceivedDuplicate != 0) { - DocumentSerializableUtilities.addInt(element, "numReceivedDuplicate", numReceivedDuplicate); - } - if (numPropagated != 0) { - DocumentSerializableUtilities.addInt(element, "numPropagated", numPropagated); - } - if (numFailedPropagating != 0) { - DocumentSerializableUtilities.addInt(element, "numFailedPropagating", numFailedPropagating); - } - if (numRepropagated != 0) { - DocumentSerializableUtilities.addInt(element, "numRepropagated", numRepropagated); - } - if (numFailedRepropagating != 0) { - DocumentSerializableUtilities.addInt(element, "numFailedRepropagating", numFailedRepropagating); - } - if (numPropagatedToPeers != 0) { - DocumentSerializableUtilities.addInt(element, "numPropagatedToPeers", numPropagatedToPeers); - } - if (numFailedPropagatingToPeers != 0) { - DocumentSerializableUtilities.addInt(element, "numFailedPropagatingToPeers", numFailedPropagatingToPeers); - } - if (numPeersPropagatedTo != 0) { - DocumentSerializableUtilities.addInt(element, "numPeersPropagatedTo", numPeersPropagatedTo); - } - if (numPropagatedInGroup != 0) { - DocumentSerializableUtilities.addInt(element, "numPropagatedInGroup", numPropagatedInGroup); - } - if (numPropagatedToNeighbors != 0) { - DocumentSerializableUtilities.addInt(element, "numPropagatedToNeighbors", numPropagatedToNeighbors); - } - if (numFailedPropagatingToNeighbors != 0) { - DocumentSerializableUtilities.addInt(element, "numFailedPropagatingToNeighbors", numFailedPropagatingToNeighbors); - } - if (numWalks != 0) { - DocumentSerializableUtilities.addInt(element, "numWalks", numWalks); - } - if (numFailedWalks != 0) { - DocumentSerializableUtilities.addInt(element, "numFailedWalks", numFailedWalks); - } - if (numWalkedToPeers != 0) { - DocumentSerializableUtilities.addInt(element, "numWalkedToPeers", numWalkedToPeers); - } - if (numFailedWalkToPeers != 0) { - DocumentSerializableUtilities.addInt(element, "numFailedWalkToPeers", numFailedWalkToPeers); - } - if (numPeersWalkedTo != 0) { - DocumentSerializableUtilities.addInt(element, "numPeersWalkedTo", numPeersWalkedTo); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("state")) { - state = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("transitionTime")) { - transitionTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("totalEdgeTime")) { - totalEdgeTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numEdgeTransitions")) { - numEdgeTransitions = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("totalRendezvousTime")) { - totalRendezvousTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numRendezvousTransitions")) { - numRendezvousTransitions = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numReceivedProcessedLocally")) { - numReceivedProcessedLocally = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numReceivedRepropagatedInGroup")) { - numReceivedRepropagatedInGroup = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numReceivedInvalid")) { - numReceivedInvalid = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numReceivedDead")) { - numReceivedDead = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numReceivedLoopback")) { - numReceivedLoopback = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numReceivedDuplicate")) { - numReceivedDuplicate = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPropagated")) { - numPropagated = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numFailedPropagating")) { - numFailedPropagating = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numRepropagated")) { - numRepropagated = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numFailedRepropagating")) { - numFailedRepropagating = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPropagatedToPeers")) { - numPropagatedToPeers = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numFailedPropagatingToPeers")) { - numFailedPropagatingToPeers = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPeersPropagatedTo")) { - numPeersPropagatedTo = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPropagatedInGroup")) { - numPropagatedInGroup = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPropagatedToNeighbors")) { - numPropagatedToNeighbors = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numFailedPropagatingToNeighbors")) { - numFailedPropagatingToNeighbors = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numWalks")) { - numWalks = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numFailedWalks")) { - numFailedWalks = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numWalkedToPeers")) { - numWalkedToPeers = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numFailedWalkToPeers")) { - numFailedWalkToPeers = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPeersWalkedTo")) { - numPeersWalkedTo = DocumentSerializableUtilities.getInt(childElement); - } - } - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousServiceMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousServiceMetric.java deleted file mode 100644 index d2e56f66..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousServiceMetric.java +++ /dev/null @@ -1,358 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - - -import net.jxta.meter.*; -import net.jxta.peer.*; - -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.platform.*; -import java.util.*; -import net.jxta.util.*; -import net.jxta.exception.*; -import net.jxta.id.*; -import java.net.*; - - -/** - * The Service Monitor Metric for the standard Rendezvous Service - **/ -public class RendezvousServiceMetric implements ServiceMetric { - private RendezvousMetric rendezvousMetric; - private LinkedList rendezvousConnectionMetrics = new LinkedList(); - private LinkedList clientConnectionMetrics = new LinkedList(); - private ModuleClassID moduleClassID = MonitorResources.rendezvousServiceMonitorClassID; - - /** - * Create a Service Metric: No-arg constructor is required - **/ - public RendezvousServiceMetric() {} - - private RendezvousServiceMetric(ModuleClassID moduleClassID) { - init(moduleClassID); - } - - /** - * Initialize the metric with the ModuleClassID of the Monitor - **/ - public void init(ModuleClassID moduleClassID) { - this.moduleClassID = moduleClassID; - } - - /** Get the ModuleClassID of the Monitor that generated this ServiceMetric **/ - public ModuleClassID getModuleClassID() { - return moduleClassID; - } - - /** - * Get the General Rendezvous Metric - **/ - public RendezvousMetric getRendezvousMetric() { - return rendezvousMetric; - } - - void setRendezvousMetric(RendezvousMetric rendezvousMetric) { - this.rendezvousMetric = rendezvousMetric; - } - - /** - * Append a Client Connection Metric - **/ - public void addClientConnectionMetric(ClientConnectionMetric clientConnectionMetric) { - synchronized (clientConnectionMetrics) { - clientConnectionMetrics.add(clientConnectionMetric); - } - } - - /** - * Get all the Client Connection Metrics - **/ - public Iterator getClientConnectionMetrics() { - return clientConnectionMetrics.iterator(); - } - - void clearClientConnectionMetrics() { - clientConnectionMetrics.clear(); - } - - /** - * Get the Client Connection Metrics for a single Peers ID - **/ - public ClientConnectionMetric getClientConnectionMetric(PeerID peerId) { - for (Iterator i = clientConnectionMetrics.iterator(); i.hasNext();) { - ClientConnectionMetric clientConnectionMetric = (ClientConnectionMetric) i.next(); - - if (peerId.equals(clientConnectionMetric.getPeerID())) { - return clientConnectionMetric; - } - } - - return null; - } - - /** - * Append a Rendezvous Connection Metric - **/ - public void addRendezvousConnectionMetric(RendezvousConnectionMetric rendezvousConnectionMetric) { - synchronized (rendezvousConnectionMetrics) { - rendezvousConnectionMetrics.add(rendezvousConnectionMetric); - } - } - - /** - * Get all the Rendezvous Connection Metrics - **/ - public Iterator getRendezvousConnectionMetrics() { - return rendezvousConnectionMetrics.iterator(); - } - - void clearRendezvousConnectionMetrics() { - rendezvousConnectionMetrics.clear(); - } - - /** - * Get the Rendezvous Connection Metrics for each Peers ID - **/ - public RendezvousConnectionMetric getRendezvousConnectionMetric(PeerID peerID) { - for (Iterator i = rendezvousConnectionMetrics.iterator(); i.hasNext();) { - RendezvousConnectionMetric rendezvousConnectionMetric = (RendezvousConnectionMetric) i.next(); - - if (peerID.equals(rendezvousConnectionMetric.getPeerID())) { - return rendezvousConnectionMetric; - } - } - - return null; - } - - /** - * {@inheritDoc} - **/ - public void serializeTo(Element element) throws DocumentSerializationException { - if (rendezvousMetric != null) { - DocumentSerializableUtilities.addDocumentSerializable(element, "rendezvousMetric", rendezvousMetric); - } - - for (Iterator i = clientConnectionMetrics.iterator(); i.hasNext();) { - ClientConnectionMetric clientConnectionMetric = (ClientConnectionMetric) i.next(); - - DocumentSerializableUtilities.addDocumentSerializable(element, "clientConnectionMetric", clientConnectionMetric); - } - - for (Iterator i = rendezvousConnectionMetrics.iterator(); i.hasNext();) { - RendezvousConnectionMetric rendezvousConnectionMetric = (RendezvousConnectionMetric) i.next(); - - DocumentSerializableUtilities.addDocumentSerializable(element, "rendezvousConnectionMetric" - , - rendezvousConnectionMetric); - } - - if (moduleClassID != null) { - DocumentSerializableUtilities.addString(element, "moduleClassID", moduleClassID.toString()); - } - - } - - /** - * {@inheritDoc} - **/ - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("clientConnectionMetric")) { - ClientConnectionMetric clientConnectionMetric = (ClientConnectionMetric) DocumentSerializableUtilities.getDocumentSerializable( - childElement, ClientConnectionMetric.class); - - clientConnectionMetrics.add(clientConnectionMetric); - } else if (tagName.equals("rendezvousConnectionMetric")) { - RendezvousConnectionMetric rendezvousConnectionMetric = (RendezvousConnectionMetric) DocumentSerializableUtilities.getDocumentSerializable( - childElement, RendezvousConnectionMetric.class); - - rendezvousConnectionMetrics.add(rendezvousConnectionMetric); - } else if (tagName.equals("rendezvousMetric")) { - rendezvousMetric = (RendezvousMetric) DocumentSerializableUtilities.getDocumentSerializable(childElement - , - RendezvousMetric.class); - } - if (tagName.equals("moduleClassID")) { - try { - moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI(DocumentSerializableUtilities.getString(childElement))); - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Can't read moduleClassID", jex); - } - } - } - } - - /** - * {@inheritDoc} - **/ - public void mergeMetrics(ServiceMetric otherServiceMetric) { - mergeMetrics(otherServiceMetric, true, true, true); - } - - /** - * Make a deep copy of this metric only including the portions designated in the Filter - * The resulting metric is Safe to modify without danger to the underlying Monitor Metrics - * @param rendezvousServiceMonitorFilter Filter designates constituant parts to be included - * @return a copy of this metric with references to the designated parts - **/ - public RendezvousServiceMetric deepCopy(RendezvousServiceMonitorFilter rendezvousServiceMonitorFilter) { - RendezvousServiceMetric serviceMetric = new RendezvousServiceMetric(); - - serviceMetric.moduleClassID = moduleClassID; - - serviceMetric.mergeMetrics(this, true, rendezvousServiceMonitorFilter.isIncludeClientConnectionMetrics() - , - rendezvousServiceMonitorFilter.isIncludeRendezvousConnectionMetrics()); - return serviceMetric; - } - - /** - * {@inheritDoc} - *

            This will only merge the designated submetrics - * @param includeRendezvousMetric Include the basic Rendezvous Metric in the merge - * @param includeClientConnectionMetrics Include Client Connection Metrics in the merge - * @param includeRendezvousConnectionMetrics Include Rendezvous Connection Metrics in the merge - **/ - public void mergeMetrics(ServiceMetric otherServiceMetric, boolean includeRendezvousMetric, boolean includeClientConnectionMetrics, boolean includeRendezvousConnectionMetrics) { - RendezvousServiceMetric otherRendezvousServiceMetric = (RendezvousServiceMetric) otherServiceMetric; - - if (includeRendezvousMetric) { - RendezvousMetric otherRendezvousMetric = otherRendezvousServiceMetric.getRendezvousMetric(); - - if ((rendezvousMetric == null) && (otherRendezvousMetric != null)) { - rendezvousMetric = new RendezvousMetric(otherRendezvousMetric); - } - - if (otherRendezvousMetric != null) { - rendezvousMetric.mergeMetrics(otherRendezvousMetric); - } - } - - if (includeClientConnectionMetrics) { - for (Iterator i = otherRendezvousServiceMetric.getClientConnectionMetrics(); i.hasNext();) { - ClientConnectionMetric otherClientConnectionMetric = (ClientConnectionMetric) i.next(); - ClientConnectionMetric clientConnectionMetric = getClientConnectionMetric(otherClientConnectionMetric.getPeerID()); - - if (clientConnectionMetric == null) { - clientConnectionMetric = new ClientConnectionMetric(otherClientConnectionMetric); - addClientConnectionMetric(clientConnectionMetric); - } - - clientConnectionMetric.mergeMetrics(otherClientConnectionMetric); - } - } - - if (includeRendezvousConnectionMetrics) { - for (Iterator i = otherRendezvousServiceMetric.getRendezvousConnectionMetrics(); i.hasNext();) { - RendezvousConnectionMetric otherRendezvousConnectionMetric = (RendezvousConnectionMetric) i.next(); - RendezvousConnectionMetric rendezvousConnectionMetric = getRendezvousConnectionMetric( - otherRendezvousConnectionMetric.getPeerID()); - - if (rendezvousConnectionMetric == null) { - rendezvousConnectionMetric = new RendezvousConnectionMetric(otherRendezvousConnectionMetric); - addRendezvousConnectionMetric(rendezvousConnectionMetric); - } - - rendezvousConnectionMetric.mergeMetrics(otherRendezvousConnectionMetric); - } - } - } - - /** - * {@inheritDoc} - **/ - public void diffMetrics(ServiceMetric otherOne) { - throw new RuntimeException("Not Supported"); - } - - /** - * Make a shallow copy of this metric only including the portions designated in the Filter - *

            Note: since this is a shallow copy it is dangerous to modify the submetrics - * @param rendezvousServiceMonitorFilter Filter designates constituant parts to be included - * @return a copy of this metric with references to the designated parts - **/ - public RendezvousServiceMetric shallowCopy(RendezvousServiceMonitorFilter rendezvousServiceMonitorFilter) { - RendezvousServiceMetric rendezvousServiceMetric = new RendezvousServiceMetric(moduleClassID); - - rendezvousServiceMetric.rendezvousMetric = rendezvousMetric; - - if (rendezvousServiceMonitorFilter.isIncludeClientConnectionMetrics()) { - for (Iterator i = getClientConnectionMetrics(); i.hasNext();) { - ClientConnectionMetric clientConnectionMetric = (ClientConnectionMetric) i.next(); - - rendezvousServiceMetric.addClientConnectionMetric(clientConnectionMetric); - } - } - - if (rendezvousServiceMonitorFilter.isIncludeRendezvousConnectionMetrics()) { - for (Iterator i = getRendezvousConnectionMetrics(); i.hasNext();) { - RendezvousConnectionMetric rendezvousConnectionMetric = (RendezvousConnectionMetric) i.next(); - - rendezvousServiceMetric.addRendezvousConnectionMetric(rendezvousConnectionMetric); - } - } - - return rendezvousServiceMetric; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousServiceMonitor.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousServiceMonitor.java deleted file mode 100644 index 07e2cc93..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousServiceMonitor.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.impl.meter.GenericServiceMonitor; -import net.jxta.impl.meter.MetricUtilities; -import net.jxta.meter.ServiceMetric; -import net.jxta.meter.ServiceMonitorFilter; -import net.jxta.peer.PeerID; - -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.LinkedList; - - -/** - * The Service Monitor for the standard Rendezvous Service - */ -public class RendezvousServiceMonitor extends GenericServiceMonitor { - private Hashtable clientConnectionMeters = new Hashtable(); - private LinkedList rendezvousConnectionMeters = new LinkedList(); - - private RendezvousMeter rendezvousMeter = new RendezvousMeter(); - - private RendezvousServiceMetric cumulativeRendezvousServiceMetric; - - /** - * {@inheritDoc} - */ - @Override - protected void init() { - cumulativeRendezvousServiceMetric = (RendezvousServiceMetric) getCumulativeServiceMetric(); - cumulativeRendezvousServiceMetric.setRendezvousMetric(rendezvousMeter.getCumulativeMetrics()); - } - - /** - * Get the General RendezvousMeter - * @return client RendezvousMeter - */ - public RendezvousMeter getRendezvousMeter() { - return rendezvousMeter; - } - - /** - * Get a Client Connection Meter - * - * @param endpointAddress containing Peer Id for the Meter - * @return client connection meter - */ - public synchronized ClientConnectionMeter getClientConnectionMeter(EndpointAddress endpointAddress) { - PeerID peerID = MetricUtilities.getPeerIdFromEndpointAddress(endpointAddress); - - return getClientConnectionMeter(peerID); - } - - /** - * Get a Client Connection Meter - * - * @param peerId Peer Id for the Meter - * @return client connection meter - */ - public synchronized ClientConnectionMeter getClientConnectionMeter(PeerID peerId) { - ClientConnectionMeter clientConnectionMeter = clientConnectionMeters.get(peerId); - - if (clientConnectionMeter == null) { - clientConnectionMeter = new ClientConnectionMeter(peerId); - clientConnectionMeters.put(peerId, clientConnectionMeter); - cumulativeRendezvousServiceMetric.addClientConnectionMetric(clientConnectionMeter.getCumulativeMetrics()); - } - - return clientConnectionMeter; - } - - /** - * Get a Client Connection Meter - * - * @param peerIdString Peer Id as a String - * @return client connection meter - */ - public synchronized ClientConnectionMeter getClientConnectionMeter(String peerIdString) { - PeerID peerID = MetricUtilities.getPeerIdFromString(peerIdString); - - return getClientConnectionMeter(peerID); - } - - /* - public synchronized void removeClientConnectionMeter(String peerId) { - clientConnectionMeters.remove(peerId); - } - */ - - /** - * Get a Rendezvous Connection Meter - * - * @param peerIdStr Peer Id for the Meter as a String - * @return the Rendezvous Connection Meter - */ - public synchronized RendezvousConnectionMeter getRendezvousConnectionMeter(String peerIdStr) { - PeerID peerID = MetricUtilities.getPeerIdFromString(peerIdStr); - - return getRendezvousConnectionMeter(peerID); - } - - /** - * Get a Rendezvous Connection Meter - * - * @param peerID Peer Id for the Meter - * @return the Rendezvous Connection Meter - */ - public synchronized RendezvousConnectionMeter getRendezvousConnectionMeter(PeerID peerID) { - if (peerID == null) { - peerID = MetricUtilities.BAD_PEERID; - } - - for (Object rendezvousConnectionMeter1 : rendezvousConnectionMeters) { - RendezvousConnectionMeter rendezvousConnectionMeter = (RendezvousConnectionMeter) rendezvousConnectionMeter1; - - if (peerID.equals(rendezvousConnectionMeter.getPeerID())) { - return rendezvousConnectionMeter; - } - } - - RendezvousConnectionMeter rendezvousConnectionMeter = new RendezvousConnectionMeter(peerID); - - rendezvousConnectionMeters.add(rendezvousConnectionMeter); - cumulativeRendezvousServiceMetric.addRendezvousConnectionMetric(rendezvousConnectionMeter.getCumulativeMetrics()); - - return rendezvousConnectionMeter; - } - - /* - public synchronized void removeRendezvousConnectionMeter(PeerID peerID) { - if (peerID == null) - return; - - for (Iterator i = rendezvousConnectionMeters.iterator(); i.hasNext(); ) { - RendezvousConnectionMeter rendezvousConnectionMeter = (RendezvousConnectionMeter)i.next(); - if (peerID.equals(rendezvousConnectionMeter.getPeerID())) { - i.remove(); - return; - } - } - } - */ - - /** - * {@inheritDoc} - */ - @Override - protected synchronized ServiceMetric collectServiceMetrics() { - RendezvousServiceMetric rendezvousServiceMetric = (RendezvousServiceMetric) createServiceMetric(); - - boolean anyData = false; - - for (Enumeration e = clientConnectionMeters.elements(); e.hasMoreElements();) { - ClientConnectionMeter clientConnectionMeter = e.nextElement(); - ClientConnectionMetric clientConnectionMetric = clientConnectionMeter.collectMetrics(); // clears delta from meter - - if (clientConnectionMetric != null) { - rendezvousServiceMetric.addClientConnectionMetric(clientConnectionMetric); - anyData = true; - } - } - - for (RendezvousConnectionMeter rendezvousConnectionMeter : rendezvousConnectionMeters) { - RendezvousConnectionMetric rendezvousConnectionMetric = rendezvousConnectionMeter.collectMetrics(); // clears delta from meter - - if (rendezvousConnectionMetric != null) { - rendezvousServiceMetric.addRendezvousConnectionMetric(rendezvousConnectionMetric); - anyData = true; - } - } - - RendezvousMetric rendezvousMetric = rendezvousMeter.collectMetrics(); - - if (rendezvousMetric != null) { - rendezvousServiceMetric.setRendezvousMetric(rendezvousMetric); - anyData = true; - } - - if (anyData) { - return rendezvousServiceMetric; - } else { - return null; - } - } - - /** - * {@inheritDoc} - */ - @Override - public ServiceMetric getServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime, int pulseIndex, long reportRate) { - int deltaReportRateIndex = monitorManager.getReportRateIndex(reportRate); - RendezvousServiceMetric origMetric = (RendezvousServiceMetric) deltaServiceMetrics[deltaReportRateIndex]; - - if (origMetric == null) { - return null; - } - - RendezvousServiceMonitorFilter rendezvousServiceMonitorFilter = (RendezvousServiceMonitorFilter) serviceMonitorFilter; - - return origMetric.shallowCopy(rendezvousServiceMonitorFilter); - } - - /** - * {@inheritDoc} - */ - @Override - public ServiceMetric getCumulativeServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime) { - RendezvousServiceMonitorFilter rendezvousServiceMonitorFilter = (RendezvousServiceMonitorFilter) serviceMonitorFilter; - RendezvousServiceMetric origMetric = (RendezvousServiceMetric) getCumulativeServiceMetric(); - - return origMetric.deepCopy(rendezvousServiceMonitorFilter); - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousServiceMonitorFilter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousServiceMonitorFilter.java deleted file mode 100644 index 25c82181..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rendezvousMeter/RendezvousServiceMonitorFilter.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.rendezvous.rendezvousMeter; - - -import net.jxta.meter.*; -import net.jxta.platform.*; -import net.jxta.document.*; -import net.jxta.util.documentSerializable.*; -import java.util.*; -import net.jxta.util.*; -import net.jxta.exception.*; -import java.net.*; -import net.jxta.id.IDFactory; - - -public class RendezvousServiceMonitorFilter implements ServiceMonitorFilter { - private boolean includeClientConnectionMetrics = true; - private boolean includeRendezvousConnectionMetrics = true; - private ModuleClassID moduleClassID = MonitorResources.rendezvousServiceMonitorClassID; - - public ModuleClassID getModuleClassID() { - return moduleClassID; - } - - public RendezvousServiceMonitorFilter() {} - - public void init(ModuleClassID moduleClassID) { - this.moduleClassID = moduleClassID; - } - - public boolean isIncludeClientConnectionMetrics() { - return includeClientConnectionMetrics; - } - - public boolean isIncludeRendezvousConnectionMetrics() { - return includeRendezvousConnectionMetrics; - } - - public void setIncludeClientConnectionMetrics(boolean includeClientConnectionMetrics) { - this.includeClientConnectionMetrics = includeClientConnectionMetrics; - } - - public void setIncludeRendezvousConnectionMetrics(boolean includeClientConnectionMetrics) { - this.includeRendezvousConnectionMetrics = includeClientConnectionMetrics; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - DocumentSerializableUtilities.addBoolean(element, "includeClientConnectionMetrics", includeClientConnectionMetrics); - DocumentSerializableUtilities.addBoolean(element, "includeRendezvousConnectionMetrics", includeRendezvousConnectionMetrics); - if (moduleClassID != null) { - DocumentSerializableUtilities.addString(element, "moduleClassID", moduleClassID.toString()); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("includeClientConnectionMetrics")) { - includeClientConnectionMetrics = DocumentSerializableUtilities.getBoolean(childElement); - } else if (tagName.equals("includeRendezvousConnectionMetrics")) { - includeRendezvousConnectionMetrics = DocumentSerializableUtilities.getBoolean(childElement); - } else if (tagName.equals("moduleClassID")) { - try { - moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI((DocumentSerializableUtilities.getString(childElement)))); - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Can't read moduleClassID", jex); - } - } - } - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerView.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerView.java deleted file mode 100644 index 44b006d8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerView.java +++ /dev/null @@ -1,2067 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rpv; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Random; -import java.util.Set; -import java.util.SortedSet; -import java.util.Timer; -import java.util.TimerTask; -import java.util.TreeSet; -import java.util.Vector; -import java.util.logging.Level; -import java.util.logging.Logger; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.logging.Logging; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.PipeID; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.protocol.RouteAdvertisement; -import net.jxta.rendezvous.RendezvousEvent; -import net.jxta.rendezvous.RendezvousListener; - -import net.jxta.impl.endpoint.EndpointUtils; -import net.jxta.impl.endpoint.relay.RelayReferralSeedingManager; -import net.jxta.impl.protocol.RdvConfigAdv; -import net.jxta.impl.rendezvous.RendezVousServiceImpl; -import net.jxta.impl.util.SeedingManager; -import net.jxta.impl.util.TimeUtils; -import net.jxta.impl.util.URISeedingManager; - -/** - * This class models a Rendezvous Peer View (RPV): - * ordered collection of all other Rendezvous Peers visible to - * this peer. - *

            - * Presently this class implements a random "diffusion" algorithm - * where each Peer periodically selects a randomly selected peer advertisement - * from its view and sends it over to a randomly selected peer from its view. - * Over time, this causes every peer to learn about every other peer, resulting - * in a "converged" peer view. - *

            - * This diffusion process is bootstrapped by every peer sending their - * own peer advertisements to some well-known, stable, "seed" peers on - * startup. - */ -public final class PeerView implements EndpointListener, RendezvousListener { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(PeerView.class.getName()); - - /** - * Our service name - */ - static final String SERVICE_NAME = "PeerView"; - - /** - * Namespace used for rdv message elements. - */ - static final String MESSAGE_NAMESPACE = "jxta"; - - /** - * Element name of outgoing messages. Note that the element contains a - * RdvAvertisement and not a Peer Advertisement. - */ - static final String MESSAGE_ELEMENT_NAME = "PeerView.PeerAdv"; - - /** - * Element name of responses. Note that the element contains a - * RdvAvertisement and not a Peer Advertisement. - */ - static final String RESPONSE_ELEMENT_NAME = "PeerView.PeerAdv.Response"; - - /** - * Message element name for PeerView "Cached" Message Element - */ - static final String CACHED_RADV_ELEMENT_NAME = "PeerView.Cached"; - - /** - * Optional message element that specifies by its presence in a peerview - * message that the referenced peer is not the provider of the - * RdvAdvertisement and the advertisement is a "hint" or referral from the - * responding peer. - *

            - * In practice, when sending its own RdvAdvertisement, a peer does not - * include this element, but when sending another peer's RdvAdvertisement, - * this element is included. - */ - static final MessageElement CACHED_RADV_ELEMENT = new StringMessageElement(CACHED_RADV_ELEMENT_NAME, Boolean.TRUE.toString(), null); - - /** - * Message element name that specifies the route advertisement of the - * source of the message. - */ - static final String SRCROUTEADV_ELEMENT_NAME = "PeerView.SrcRouteAdv"; - - /** - * Message element name for PeerView "Edge" Message Element - */ - static final String EDGE_ELEMENT_NAME = "PeerView.EdgePeer"; - - /** - * Optional message element that specifies by its presence in a peerview - * message that the referenced peer is an edge peer and not a member of the - * peerview. - */ - static final MessageElement EDGE_ELEMENT = new StringMessageElement(EDGE_ELEMENT_NAME, Boolean.TRUE.toString(), null); - - /** - * Message element name for PeerView "Failure" Message Element - */ - static final String FAILURE_ELEMENT_NAME = "PeerView.Failure"; - - /** - * Optional message element that specifies by its presence in a peerview - * message that the referenced peer has either failed or is quitting. If the - * "cached" element is also set then the error is being reported by a third - * party. - */ - static final MessageElement FAILURE_ELEMENT = new StringMessageElement(FAILURE_ELEMENT_NAME, Boolean.TRUE.toString(), null); - - /** - * This is the interval between adv exchange in seconds. This is - * the main tunable runtime parameter for the diffusion - * process. An interval that is too low will improve view - * consistency at the expense of gratuitous network traffic. On - * the other hand, an interval that is too high will cause the - * view to become inconsistent. It is desirable to err on the side - * of extra traffic. - */ - private static final long DEFAULT_SEEDING_PERIOD = 5 * TimeUtils.ASECOND; - - private static final long WATCHDOG_PERIOD = 30 * TimeUtils.ASECOND; - private static final long WATCHDOG_GRACE_DELAY = 5 * TimeUtils.AMINUTE; - - private static final long DEFAULT_BOOTSTRAP_KICK_INTERVAL = 3 * TimeUtils.ASECOND; - - private static final int MIN_BOOTLEVEL = 0; - private static final int BOOTLEVEL_INCREMENT = 1; - private static final int MAX_BOOTLEVEL = 6; - - /** - * DEFAULT_SEEDING_RDVPEERS - *

            - * This value is the maximum number of rendezvous peers that will be - * send our own advertisement at boot time. - */ - //private static final int DEFAULT_SEEDING_RDVPEERS = 5; - - private final PeerGroup group; - - /** - * The group in which our propagate pipe will run. - */ - private final PeerGroup advertisingGroup; - private final RendezVousServiceImpl rdvService; - private final EndpointService endpoint; - - /** - * The name of this PeerView. - *

            - * FIXME 20040623 bondolo This should be a CodatID. - */ - private final String name; - - /** - * Delay in relative milliseconds to apply before contacting seeding rdvs. - * 0 is supposed to be reserved by RdvConfig to mean "use the default". - * However, it is in fact a valid value and also the one we want for the default. - * The only problem with that is that it is not possible to configure this value - * explicitly, should it one day not be the default. The issue is actually in RdvConfig. - */ - private long seedingRdvConnDelay = 0; - - private final boolean useOnlySeeds; - - private final SeedingManager seedingManager; - - /** - * If the peerview is smaller than this we will try harder to find - * additional peerview members. - */ - private int minHappyPeerView = 4; - - /** - * A single timer is used to periodically kick each PeerView - * into activity. For the Random PeerView, this activity consists - * of selecting a PeerViewElement at random from its view and - * sending it across to a randomly-selected peer from its view. - *

            - * FIXME 20021121 lomax - *

            - * The original idea of using a common timer in order to save threads IS a - * very good idea. However, limitations, and actually, bugs, in java.util.Timer - * creates the following problems when using a static Timer: - *

            - *

              - *
            • Memory Leak: Canceling a TimerTask does not remove it from the - * execution queue of the Timer until the Timer is canceled or the - * TimerTask is fired. Since most of the TimerTasks are inner classes - * this can mean that the PeerView is held around for a long time.
            • - *

              - *

            • java.util.Timer is not only not real-time (which is more or less fine - * for the PeerView, but it sequentially invokes tasks (only one Thread - * per Timer). As a result, tasks that takes a long time to run delays - * other tasks.
            • - *
            - *

            - * The PeerView would function better with a better Timer, but JDK does - * not provide a standard timer that would fulfill the needs of the - * PeerView. Maybe we should implement a JXTA Timer, since lots of the JXTA - * services, by being very asynchronous, rely on the same kind of timer - * semantics as the PeerView. Until then, creating a Timer per instance of - * the PeerView (i.e. per instance of joined PeerGroup) is the best - * workaround. - */ - private final Timer timer; - - /** - * A random number generator. - */ - private final static Random random = new Random(); - - /** - * List of scheduled tasks - */ - private final Set scheduledTasks = Collections.synchronizedSet(new HashSet()); - - /** - * Describes the frequency and amount of effort we will spend updating - * the peerview. - */ - private int bootLevel = MIN_BOOTLEVEL; - - /** - * Earliest absolute time in milliseconds at which we will allow a reseed - * to take place. - */ - private long earliestReseed = 0L; - - private final String uniqueGroupId; - - /** - * Listeners for PeerView Events. - */ - private final Set rpvListeners = Collections.synchronizedSet(new HashSet()); - - /** - * Used for querying for pves. - */ - private InputPipe wirePipeInputPipe = null; - - /** - * Used for querying for pves. - */ - private OutputPipe wirePipeOutputPipe = null; - - /** - * Used for notifications about pve failures. - */ - private InputPipe localGroupWirePipeInputPipe = null; - - /** - * Used for notifications about pve failures. - */ - private OutputPipe localGroupWirePipeOutputPipe = null; - - /** - * A task which monitors the up and down peers in the peerview. - */ - private WatchdogTask watchdogTask = null; - - /** - * This is the accumulated view by an instance of this class. - */ - private final SortedSet localView = Collections.synchronizedSortedSet(new TreeSet()); - - /** - * PVE for ourself. - *

            - * FIXME bondolo 20041015 This should be part of the local view. - */ - private final PeerViewElement self; - private PeerViewElement upPeer = null; - private PeerViewElement downPeer = null; - - private final PeerViewStrategy replyStrategy; - - private final PeerViewStrategy kickRecipientStrategy; - - private final PeerViewStrategy kickAdvertisementStrategy; - - private final PeerViewStrategy refreshRecipientStrategy; - - // PeerAdv tracking. - private PeerAdvertisement lastPeerAdv = null; - private int lastModCount = -1; - - private final PipeAdvertisement localGroupWirePipeAdv; - private final PipeAdvertisement advGroupPropPipeAdv; - - /** - * If true then this Peer View instance is closed and is - * shutting down. - */ - private volatile boolean closed = false; - - /** - * Get an instance of PeerView for the specified PeerGroup and Service. - * - * @param group Peer Group in which this Peer View instance operates. - * @param advertisingGroup Peer Group in which this Peer View instance will - * advertise and broadcast its existence. - * @param rdvService The rdvService we are to use. - * @param name The identifying name for this Peer View instance. - */ - public PeerView(PeerGroup group, PeerGroup advertisingGroup, RendezVousServiceImpl rdvService, String name) { - this.group = group; - this.advertisingGroup = advertisingGroup; - this.rdvService = rdvService; - this.name = name; - - this.endpoint = group.getEndpointService(); - - this.uniqueGroupId = group.getPeerGroupID().getUniqueValue().toString(); - - timer = new Timer("PeerView Timer for " + group.getPeerGroupID(), true); - - Advertisement adv = null; - ConfigParams confAdv = group.getConfigAdvertisement(); - - // Get the config. If we do not have a config, we're done; we just keep - // the defaults (edge peer/no auto-rdv) - if (confAdv != null) { - try { - XMLDocument configDoc = (XMLDocument) confAdv.getServiceParam(rdvService.getAssignedID()); - - if (null != configDoc) { - adv = AdvertisementFactory.newAdvertisement(configDoc); - } - } catch (java.util.NoSuchElementException failed) {// ignored - } - } - - RdvConfigAdv rdvConfigAdv; - - if (!(adv instanceof RdvConfigAdv)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Creating new RdvConfigAdv for defaults."); - } - - rdvConfigAdv = (RdvConfigAdv) AdvertisementFactory.newAdvertisement(RdvConfigAdv.getAdvertisementType()); - } else { - rdvConfigAdv = (RdvConfigAdv) adv; - } - - if (rdvConfigAdv.getSeedRendezvousConnectDelay() > 0) { - seedingRdvConnDelay = rdvConfigAdv.getSeedRendezvousConnectDelay(); - } - - useOnlySeeds = rdvConfigAdv.getUseOnlySeeds(); - - if (rdvConfigAdv.getMinHappyPeerView() > 0) { - minHappyPeerView = rdvConfigAdv.getMinHappyPeerView(); - } - - URISeedingManager seedingManager; - - if ((null == advertisingGroup) && rdvConfigAdv.getProbeRelays()) { - seedingManager = new RelayReferralSeedingManager(rdvConfigAdv.getAclUri(), useOnlySeeds, group, name); - } else { - seedingManager = new URISeedingManager(rdvConfigAdv.getAclUri(), useOnlySeeds, group, name); - } - - for (URI aSeeder : Arrays.asList(rdvConfigAdv.getSeedingURIs())) { - seedingManager.addSeedingURI(aSeeder); - } - - for (URI aSeed : Arrays.asList(rdvConfigAdv.getSeedRendezvous())) { - seedingManager.addSeed(aSeed); - } - - this.seedingManager = seedingManager; - - lastPeerAdv = group.getPeerAdvertisement(); - lastModCount = lastPeerAdv.getModCount(); - - // create a new local RdvAdvertisement and set it to self. - RdvAdvertisement radv = createRdvAdvertisement(lastPeerAdv, name); - - self = new PeerViewElement(endpoint, radv); - - // addPeerViewElement( self ); - - // setup endpoint listener - endpoint.addIncomingMessageListener(this, SERVICE_NAME, uniqueGroupId); - - // add rendezvous listener - rdvService.addListener(this); - - // initialize strategies - replyStrategy = new PeerViewRandomWithReplaceStrategy(localView); - - kickRecipientStrategy = new PeerViewRandomStrategy(localView); - - kickAdvertisementStrategy = new PeerViewRandomWithReplaceStrategy(localView); - - refreshRecipientStrategy = new PeerViewSequentialStrategy(localView); - - localGroupWirePipeAdv = makeWirePipeAdvertisement(group, group, name); - - if (null != advertisingGroup) { - advGroupPropPipeAdv = makeWirePipeAdvertisement(advertisingGroup, group, name); - } else { - advGroupPropPipeAdv = null; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info( "PeerView created for group \"" + group.getPeerGroupName() + - "\" [" + group.getPeerGroupID() + "] name \"" + name + "\""); - } - } - - /** - * {@inheritDoc} - *

            - * Listener for "PeerView"/<peergroup-unique-id> and propagate pipes. - */ - public void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - // check what kind of message this is (response or not). - boolean isResponse = false; - MessageElement me = msg.getMessageElement(MESSAGE_NAMESPACE, MESSAGE_ELEMENT_NAME); - - if (me == null) { - me = msg.getMessageElement(MESSAGE_NAMESPACE, RESPONSE_ELEMENT_NAME); - if (me == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Discarding damaged " + msg + "."); - } - return; - } else { - isResponse = true; - } - } - - Advertisement adv; - - try { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(me); - - adv = AdvertisementFactory.newAdvertisement(asDoc); - } catch (RuntimeException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building rdv advertisement from message element", failed); - } - return; - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building rdv advertisement from message element", failed); - } - return; - } - - if (!(adv instanceof RdvAdvertisement)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Response does not contain radv (" + adv.getAdvertisementType() + ")"); - } - return; - } - - RdvAdvertisement radv = (RdvAdvertisement) adv; - - if (null == radv.getRouteAdv()) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Rdv Advertisement does not contain route."); - } - return; - } - - // See if we can find a src route adv in the message. - me = msg.getMessageElement(MESSAGE_NAMESPACE, SRCROUTEADV_ELEMENT_NAME); - if (me != null) { - try { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(me); - Advertisement routeAdv = AdvertisementFactory.newAdvertisement(asDoc); - - if (!(routeAdv instanceof RouteAdvertisement)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Advertisement is not a RouteAdvertisement"); - } - } else { - RouteAdvertisement rdvRouteAdv = radv.getRouteAdv().clone(); - - // XXX we stich them together even if in the end it gets optimized away - RouteAdvertisement.stichRoute(rdvRouteAdv, (RouteAdvertisement) routeAdv); - radv.setRouteAdv(rdvRouteAdv); - } - } catch (RuntimeException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building route adv from message element", failed); - } - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building route adv from message element", failed); - } - } - } - me = null; - - // Is this a message about ourself? - if (group.getPeerID().equals(radv.getPeerID())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received a PeerView message about self. Discard."); - } - - return; - } - - // Collect the various flags. - - boolean isFailure = (msg.getMessageElement(MESSAGE_NAMESPACE, FAILURE_ELEMENT_NAME) != null); - boolean isCached = (msg.getMessageElement(MESSAGE_NAMESPACE, CACHED_RADV_ELEMENT_NAME) != null); - boolean isFromEdge = (msg.getMessageElement(MESSAGE_NAMESPACE, EDGE_ELEMENT_NAME) != null); - boolean isTrusted = isFromEdge || seedingManager.isAcceptablePeer(radv.getRouteAdv()); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - String srcPeer = srcAddr.toString(); - - if ("jxta".equals(srcAddr.getProtocolName())) { - try { - String idstr = ID.URIEncodingName + ":" + ID.URNNamespace + ":" + srcAddr.getProtocolAddress(); - - ID asID = IDFactory.fromURI(new URI(idstr)); - - PeerViewElement pve = getPeerViewElement(asID); - - if (null != pve) { - srcPeer = "\"" + pve.getRdvAdvertisement().getName() + "\""; - } - } catch (URISyntaxException failed) {// ignored - } - } - - LOG.fine( - "[" + group.getPeerGroupID() + "] Received a" + (isCached ? " cached" : "") + (isResponse ? " response" : "") - + (isFailure ? " failure" : "") + " message (" + msg.toString() + ")" + (isFromEdge ? " from edge" : "") - + " regarding \"" + radv.getName() + "\" from " + srcPeer); - } - - if (!isTrusted) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Rejecting peerview message from " + radv.getPeerID()); - } - return; - } - - // if this is a notification failure. All we have to do is locally - // process the failure - if (isFailure) { - notifyFailure(radv.getPeerID(), false); - return; - } - - handlePeerViewMessage(isResponse, isCached, isFromEdge, isTrusted, radv); - } - - /** - * Following the extraction of a peerview message from a - */ - private void handlePeerViewMessage(boolean isResponse, boolean isCached, boolean isFromEdge, boolean isTrusted, RdvAdvertisement radv) { - - // Figure out if we know that peer already. If we do, reuse the pve - // that we have. - boolean isNewbie = false; - boolean added = false; - PeerViewElement pve; - - synchronized (localView) { - PeerViewElement newbie = new PeerViewElement(endpoint, radv); - - pve = getPeerViewElement(newbie); - - if (null == pve) { - pve = newbie; - isNewbie = true; - } - - if (!isFromEdge && !isCached && isTrusted) { - if (isNewbie) { - added = addPeerViewElement(pve); - } else { - pve.setRdvAdvertisement(radv); - } - } - } - - if (!isNewbie && isFromEdge && !isCached) { - // The message stated that it is from an edge we believed was a - // peerview member. Best thing to do is tell everyone that it's no - // longer in peerview. - notifyFailure(pve, true); - // we continue processing because it's not the other peer's fault we had the wrong idea. - } - - // Do the rest of the add related tasks out of synch. - // We must not nest any possibly synchronized ops in - // the LocalView lock; it's the lowest level. - - if (added) { - // Notify local listeners - generateEvent(PeerViewEvent.ADD, pve); - } - - /* - * Now, see what if any message we have to send as a result. - * There are three kinds of messages we can send: - * - * - A response with ourselves, if we're being probed and we're - * a rdv. - * - * - A probe to the peer whose adv we received, because we want - * confirmation that it's alive. - * - * - A response with a random adv from our cache if we're being probed - * - * We may send more than one message. - */ - - boolean status; - - if (!isCached) { - if (!isResponse) { - // Type 1: Respond to probe - // - // We are being probed by an edge peer or peerview member. We respond - // with our own advertisement. - status = send(pve, self, true, false); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Type 1 (Respond with self PVE) : Sent to " + pve + " result =" + status); - } - - // Type 3: Respond with random entry from our PV when we are probed. - // - // Respond with a strategized adv from our view. - PeerViewElement sendpve = replyStrategy.next(); - - if ((sendpve != null) && !pve.equals(sendpve) && !self.equals(sendpve)) { - status = send(pve, sendpve, true, false); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Type 3 (Respond with random PVE) : Sent " + sendpve + " to " + pve + " result=" + status); - } - } - } else { - // Heartbeat: do nothing. - } - } else if (isResponse) { - if (isNewbie && !useOnlySeeds && !isFromEdge) { - // Type 2: Probe a peer we have just learned about from a referral. - // - // If useOnlySeeds, we're not allowed to talk to peers other than our - // seeds, so do not probe anything we learn from 3rd party. (Probing of - // seeds happens as part of the "kick" strategy). - status = send(pve, self, false, false); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Type 2 (Probe PVE) : Probed " + pve + " result=" + status); - } - } else { - // Already known or ignoring: do nothing. - } - } else { - // Invalid : do nothing. - } - } - - /** - * {@inheritDoc} - */ - @SuppressWarnings("fallsthrough") - public void rendezvousEvent(RendezvousEvent event) { - - if (closed) { - return; - } - - boolean notifyFailure = false; - - synchronized (this) { - - int theEventType = event.getType(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("[" + group.getPeerGroupName() + "] Processing " + event); - } - - refreshSelf(); - - if ((RendezvousEvent.BECAMERDV == theEventType) || (RendezvousEvent.BECAMEEDGE == theEventType)) { - // kill any existing watchdog task - if (null != watchdogTask) { - removeTask(watchdogTask); - watchdogTask.cancel(); - watchdogTask = null; - } - } - - switch (theEventType) { - case RendezvousEvent.RDVCONNECT: - case RendezvousEvent.RDVRECONNECT: - case RendezvousEvent.CLIENTCONNECT: - case RendezvousEvent.CLIENTRECONNECT: - case RendezvousEvent.RDVFAILED: - case RendezvousEvent.RDVDISCONNECT: - case RendezvousEvent.CLIENTFAILED: - case RendezvousEvent.CLIENTDISCONNECT: - break; - - case RendezvousEvent.BECAMERDV: - openWirePipes(); - watchdogTask = new WatchdogTask(); - addTask(watchdogTask, WATCHDOG_PERIOD, WATCHDOG_PERIOD); - rescheduleKick(true); - break; - - case RendezvousEvent.BECAMEEDGE: - openWirePipes(); - if (!localView.isEmpty()) { - // FIXME bondolo 20040229 since we likely don't have a - // rendezvous connection, it is kind of silly to be sending - // this now. probably should wait until we get a rendezvous - // connection. - notifyFailure = true; - } - rescheduleKick(true); - break; - - default: - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("[" + group.getPeerGroupName() + "] Unexpected RDV event : " + event); - } - break; - } - } - - // we can't do the notification under synchronization. - if (notifyFailure) { - notifyFailure(self, true); - } - } - - public void start() {// do nothing for now... all the good stuff happens as a result of - // rendezvous events. - } - - public void stop() { - - synchronized (this) { - // Only one thread gets to perform the shutdown. - if (closed) { - return; - } - closed = true; - } - - // notify other rendezvous peers that we are going down - notifyFailure(self, true); - - // From now on we can nullify everything we want. Other threads check - // the closed flag where it matters. - synchronized (this) { - if (watchdogTask != null) { - removeTask(watchdogTask); - watchdogTask.cancel(); - watchdogTask = null; - } - - // Remove message listener. - endpoint.removeIncomingMessageListener(SERVICE_NAME, uniqueGroupId); - - // Remove rendezvous listener. - rdvService.removeListener(this); - - // Remove all our pending scheduled tasks - // Carefull with the indices while removing: do it backwards, it's - // cheaper and simpler. - - synchronized (scheduledTasks) { - Iterator eachTask = scheduledTasks.iterator(); - - while (eachTask.hasNext()) { - try { - TimerTask task = eachTask.next(); - - task.cancel(); - eachTask.remove(); - } catch (Exception ez1) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Cannot cancel task: ", ez1); - } - } - } - } - - // Make sure that we close our WirePipes - closeWirePipes(); - - // Let go of the up and down peers. - downPeer = null; - upPeer = null; - localView.clear(); - - timer.cancel(); - - rpvListeners.clear(); - } - } - - protected void addTask(TimerTask task, long delay, long interval) { - - synchronized (scheduledTasks) { - if (scheduledTasks.contains(task)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Task list already contains specified task."); - } - } - scheduledTasks.add(task); - } - - if (interval >= 1) { - timer.schedule(task, delay, interval); - } else { - timer.schedule(task, delay); - } - } - - protected void removeTask(TimerTask task) { - scheduledTasks.remove(task); - } - - /** - * Adds the specified URI to the list of seeds. Even if useOnlySeeds is in - * effect, this seed may now be used, as if it was part of the initial - * configuration. - * - * @param seed the URI of the seed rendezvous. - */ - public void addSeed(URI seed) { - if (seedingManager instanceof URISeedingManager) { - ((URISeedingManager) seedingManager).addSeed(seed); - } - } - - /** - * Probe the specified peer immediately. - *

            - * Note: If "useOnlySeeds" is in effect and the peer is not a seed, any response to this probe will be ignored. - */ - public boolean probeAddress(EndpointAddress address, RouteAdvertisement hint) { - - PeerViewElement holdIt; - - synchronized (localView) { - holdIt = self; - } - - return send(address, hint, holdIt, false, false); - } - - /** - * Send our own advertisement to all of the seed rendezvous. - */ - public void seed() { - long reseedRemaining = earliestReseed - TimeUtils.timeNow(); - - if (reseedRemaining > 0) { - // Too early; the previous round is not even done. - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Still Seeding for " + reseedRemaining + "ms."); - } - return; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("New Seeding..."); - } - - // Schedule sending propagated query to our local network neighbors. - send(null, null, self, false, false); - - long iterations = 0; - - if (localView.size() < minHappyPeerView) { - // We only do these things if we don't have a "happy" Peer View. - // If the Peer View is already "happy" then we will use only - // Peer View referrals for learning of new entires. - - List seedRdvs = new ArrayList( - Arrays.asList(seedingManager.getActiveSeedRoutes())); - - while (!seedRdvs.isEmpty()) { - RouteAdvertisement aSeed = seedRdvs.remove(0); - - if (null == aSeed.getDestPeerID()) { - // It is an incomplete route advertisement. We are going to assume that it is only a wrapper for a single ea. - Vector seed_eas = aSeed.getDest().getVectorEndpointAddresses(); - - if (!seed_eas.isEmpty()) { - EndpointAddress aSeedHost = new EndpointAddress(seed_eas.get(0)); - - // XXX 20061220 bondolo We could check all of our current PVEs to make sure that this address is not already known. - - send(aSeedHost, null, self, false, false); - } - } else { - // We have a full route, send it to the virtual address of the route! - // FIXME malveaux 20070816 Second part of conjunct can be removed once 'self' is included in the peerview - if ((null == getPeerViewElement(aSeed.getDestPeerID())) && !group.getPeerID().equals(aSeed.getDestPeerID())) { - EndpointAddress aSeedHost = new EndpointAddress("jxta", aSeed.getDestPeerID().getUniqueValue().toString(), - null, null); - - send(aSeedHost, aSeed, self, false, false); - } - } - } - - if (!useOnlySeeds) { - // If use only seeds, we're not allowed to put in the peerview - // anything but our seed rdvs. So, we've done everything that - // was required. - - // Schedule sending propagated query to our advertising group - if (advertisingGroup != null) { - // send it, but not immediately. - scheduleAdvertisingGroupQuery(DEFAULT_SEEDING_PERIOD * 2); - } - } - } - - earliestReseed = TimeUtils.toAbsoluteTimeMillis(seedingRdvConnDelay + (DEFAULT_SEEDING_PERIOD * iterations)); - } - - /** - * Make sure that the PeerView properly changes behavior, when switching - * from edge mode to rdv mode, and vice-versa. - * Since openWirePipes() requires some other services such as the Pipe - * Service, and since updateStatus is invoked this work must happen in - * background, giving a chance to other services to be started. - */ - private class OpenPipesTask extends TimerTask { - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - if (closed) { - return; - } - - openWirePipes(); - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread: " + Thread.currentThread().getName(), all); - } - } finally { - removeTask(this); - } - } - } - - private void scheduleOpenPipes(long delay) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Scheduling open pipes attempt in " + delay + "ms."); - } - - addTask(new OpenPipesTask(), delay, -1); - } - - /** - * Send a PeerView Message to the specified peer. - * - * @param response indicates whether this is a response. Otherwise - * we may create a distributed loop where peers keep perpetually - * responding to each-other. - * @param failure Construct the message as a failure notification. - */ - private boolean send(PeerViewElement dest, PeerViewElement pve, boolean response, boolean failure) { - - Message msg = makeMessage(pve, response, failure); - - boolean result = dest.sendMessage(msg, SERVICE_NAME, uniqueGroupId); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + " to " + dest + " success = " + result); - } - - return result; - } - - /** - * Send a PeerView Message to the specified peer. - * - * @param response indicates whether this is a response. Otherwise - * we may create a distributed loop where peers keep perpetually - * responding to each-other. - * @param failure Construct the message as a failure notification. - */ - private boolean send(EndpointAddress dest, RouteAdvertisement hint, PeerViewElement pve, boolean response, boolean failure) { - - Message msg = makeMessage(pve, response, failure); - - if (null != dest) { - EndpointAddress realAddr = new EndpointAddress(dest, SERVICE_NAME, uniqueGroupId); - - Messenger messenger = rdvService.endpoint.getMessengerImmediate(realAddr, hint); - - if (null != messenger) { - try { - boolean result = messenger.sendMessage(msg); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + " to " + dest + " success = " + result); - } - - return result; - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not send " + msg + " to " + dest, failed); - } - return false; - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not get messenger for " + dest); - } - - return false; - } - } else { - // Else, propagate the message. - try { - endpoint.propagate(msg, SERVICE_NAME, uniqueGroupId); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sent " + msg + " via propagate"); - } - return true; - } catch (IOException ez) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - // Pretty strange. This has little basis for failure... - LOG.log(Level.WARNING, "Could not propagate " + msg, ez); - } - return false; - } - } - } - - /** - * Send a PeerView Message to the specified peer. - * - * @param response indicates whether this is a response. Otherwise - * we may create a distributed loop where peers keep perpetually - * responding to each-other. - * @param failure Construct the message as a failure notification. - * @param dest destination output pipe - * @param pve the peer view element - * @return true if successful - */ - private boolean send(OutputPipe dest, PeerViewElement pve, boolean response, boolean failure) { - - Message msg = makeMessage(pve, response, failure); - - try { - return dest.send(msg); - } catch (IOException ez) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not send " + msg, ez); - } - return false; - } - } - - /** - * Make a PeerView Message - * - * @param content the peer view element - * @param response the response - * @param failure whether to create a message based on a failure - * @return the message - */ - private Message makeMessage(PeerViewElement content, boolean response, boolean failure) { - - Message msg = new Message(); - - // // edge peers add an identifying element, RDV peers do not - // if (!rdvService.isRendezVous()) { - // msg.addMessageElement(MESSAGE_NAMESPACE, EDGE_ELEMENT); - // } - // - if (failure) { - // This is a failure notification. - msg.addMessageElement(MESSAGE_NAMESPACE, FAILURE_ELEMENT); - } - - refreshSelf(); - - RdvAdvertisement radv = content.getRdvAdvertisement(); - - XMLDocument doc = (XMLDocument) radv.getDocument(MimeMediaType.XMLUTF8); - String msgName = response ? RESPONSE_ELEMENT_NAME : MESSAGE_ELEMENT_NAME; - - MessageElement msge = new TextDocumentMessageElement(msgName, doc, null); - - msg.addMessageElement(MESSAGE_NAMESPACE, msge); - - if (!content.equals(self)) { - // This is a cached RdvAdvertisement - msg.addMessageElement(MESSAGE_NAMESPACE, CACHED_RADV_ELEMENT); - - // This message contains an RdvAdvertisement which is not ourself. In that - // case, it is wise to also send the local route advertisement (as the optional - // SrcRdvAdv) so the destination might have a better change to access the "content" - // RendezvousAdv (this peer will then act as a hop). - - RouteAdvertisement localra = EndpointUtils.extractRouteAdv(lastPeerAdv); - - if (localra != null) { - try { - XMLDocument radoc = (XMLDocument) localra.getDocument(MimeMediaType.XMLUTF8); - - msge = new TextDocumentMessageElement(SRCROUTEADV_ELEMENT_NAME, radoc, null); - msg.addMessageElement(MESSAGE_NAMESPACE, msge); - } catch (Exception ez1) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not create optional src route adv for " + content, ez1); - } - } - } - } - - return msg; - } - - /** - * Invoked by anyone in order to inform the PeerView of a failure - * of one of the member peers. - * - * @param pid ID of the peer which failed. - * @param propagateFailure If truethen broadcast the failure to - * other peers otherwise only update the local peerview. - */ - public void notifyFailure(PeerID pid, boolean propagateFailure) { - - PeerViewElement pve = getPeerViewElement(pid); - - if (null != pve) { - notifyFailure(pve, propagateFailure); - } - } - - /** - * Invoked when a peerview member peer becomes unreachable. - * - * @param pve The peer which failed. - * @param propagateFailure If {@code true} then broadcast the failure to - * other peers otherwise only update the local peerview. - */ - void notifyFailure(PeerViewElement pve, boolean propagateFailure) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Notifying failure of " + pve); - } - - try { - boolean removedFromPeerView = removePeerViewElement(pve); - - // only propagate if we actually knew of the peer - propagateFailure &= (removedFromPeerView || (self == pve)); - - // Notify local listeners - if (removedFromPeerView) { - generateEvent(PeerViewEvent.FAIL, pve); - } - - boolean emptyPeerView = localView.isEmpty(); - - // If the local view has become empty, reset the kicker into - // a seeding mode. - if (emptyPeerView && removedFromPeerView) { - rescheduleKick(true); - } - - if (propagateFailure) { - // Notify other rendezvous peers that there has been a failure. - OutputPipe op = localGroupWirePipeOutputPipe; - - if (null != op) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Propagating failure of " + pve); - } - - send(op, pve, true, true); - } - } - } catch (Exception ez) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure while generating noficiation of failure of PeerView : " + pve, ez); - } - } - } - - /** - * Invoked by the Timer thread to cause each PeerView to initiate - * a Peer Advertisement exchange. - */ - private void kick() { - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Begun kick() in " + group.getPeerGroupID()); - } - - // Use seed strategy. (it has its own throttling and resource limiting). - seed(); - - // refresh ourself to a peer in our view - PeerViewElement refreshee = refreshRecipientStrategy.next(); - - if ((refreshee != null) && (self != refreshee)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Refresh " + refreshee); - } - send(refreshee, self, false, false); - } - - // now share an adv from our local view to another peer from our - // local view. - - PeerViewElement recipient = kickRecipientStrategy.next(); - - if (recipient == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No recipient to send adv "); - } - return; - } - - PeerViewElement rpve = kickAdvertisementStrategy.next(); - - if (rpve == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No adv to send"); - } - return; - } - - if (rpve.equals(recipient) || self.equals(recipient)) { - // give up: no point in sending a peer its own adv - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("adv to send is same as recipient: Nothing to do."); - } - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending adv " + rpve + " to " + recipient); - } - - send(recipient, rpve, true, false); - } finally { - rescheduleKick(false); - } - } - - /** - * Choose a boot level appropriate for the current configuration and state. - * - * @return the new boot level. - */ - private int adjustBootLevel() { - - boolean areWeHappy = localView.size() >= minHappyPeerView; - - // increment boot level faster if we have a reasonable peerview. - int increment = areWeHappy ? BOOTLEVEL_INCREMENT : BOOTLEVEL_INCREMENT * 2; - - // if we don't have a reasonable peerview, we continue to try harder. - int maxbootlevel = MAX_BOOTLEVEL - (areWeHappy ? 0 : BOOTLEVEL_INCREMENT); - - bootLevel = Math.min(maxbootlevel, bootLevel + increment); - - return bootLevel; - } - - private synchronized void rescheduleKick(boolean now) { - - if (closed) { - return; - } - - // Set the next iteration - try { - if (now) { - bootLevel = MIN_BOOTLEVEL; - } else { - adjustBootLevel(); - } - - long tilNextKick = DEFAULT_BOOTSTRAP_KICK_INTERVAL * ((1L << bootLevel) - 1); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Scheduling kick in " + (tilNextKick / TimeUtils.ASECOND) + " seconds at bootLevel " + bootLevel - + " in group " + group.getPeerGroupID()); - } - - KickerTask task = new KickerTask(); - - addTask(task, tilNextKick, -1); - } catch (Exception ez1) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Cannot set timer. RPV will not work.", ez1); - } - } - } - - /** - * Refresh the local copy of the peer advertisement and the rendezvous - * advertisement. - */ - private void refreshSelf() { - - RdvAdvertisement radv; - - synchronized (this) { - PeerAdvertisement newPadv = group.getPeerAdvertisement(); - int newModCount = newPadv.getModCount(); - - if ((lastPeerAdv != newPadv) || (lastModCount != newModCount)) { - lastPeerAdv = newPadv; - lastModCount = newModCount; - - // create a new local RdvAdvertisement and set it to self. - radv = createRdvAdvertisement(lastPeerAdv, name); - - if (radv != null) { - self.setRdvAdvertisement(radv); - } - } - } - } - - static RdvAdvertisement createRdvAdvertisement(PeerAdvertisement padv, String serviceName) { - - try { - // FIX ME: 10/19/2002 lomax@jxta.org. We need to properly set up the service ID. Unfortunately - // this current implementation of the PeerView takes a String as a service name and not its ID. - // Since currently, there is only PeerView per group (all peerviews share the same "service", this - // is not a problem, but that will have to be fixed eventually. - - // create a new RdvAdvertisement - RdvAdvertisement rdv = (RdvAdvertisement) AdvertisementFactory.newAdvertisement( - RdvAdvertisement.getAdvertisementType()); - - rdv.setPeerID(padv.getPeerID()); - rdv.setGroupID(padv.getPeerGroupID()); - rdv.setServiceName(serviceName); - rdv.setName(padv.getName()); - - RouteAdvertisement ra = EndpointUtils.extractRouteAdv(padv); - - // Insert it into the RdvAdvertisement. - rdv.setRouteAdv(ra); - - return rdv; - } catch (Exception ez) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Cannot create Local RdvAdvertisement: ", ez); - } - return null; - } - } - - /** - * Add a listener for PeerViewEvent - * - * @param listener An PeerViewListener to process the event. - * @return true if successful - */ - public boolean addListener(PeerViewListener listener) { - boolean added = rpvListeners.add(listener); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Registered PeerViewEvent Listener (" + listener.getClass().getName() + ")"); - } - - return added; - } - - /** - * Removes a PeerViewEvent Listener previously added with addListener. - * - * @param listener the PeerViewListener listener remove - * @return whether successful or not - */ - public boolean removeListener(PeerViewListener listener) { - boolean removed = rpvListeners.remove(listener); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Removed PeerViewEvent Listener (" + listener.getClass().getName() + ")"); - } - - return removed; - } - - /** - * Generate a PeerView Event and notify all listeners. - * - * @param type the Event Type. - * @param element The peer having the event. - */ - private void generateEvent(int type, PeerViewElement element) { - - PeerViewEvent newevent = new PeerViewEvent(this, type, element); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Calling listeners for " + newevent + " in group " + group.getPeerGroupID()); - } - - for (Object o : Arrays.asList(rpvListeners.toArray())) { - PeerViewListener pvl = (PeerViewListener) o; - - try { - pvl.peerViewEvent(newevent); - } catch (Throwable ignored) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in PeerViewEvent listener : (" + pvl.getClass().getName() + ")" - , - ignored); - } - } - } - } - - static PipeAdvertisement makeWirePipeAdvertisement(PeerGroup destGroup, PeerGroup group, String name) { - - PipeAdvertisement adv = (PipeAdvertisement) AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType()); - - // Create a pipe advertisement for this group. - // Generate a well known but unique ID. - // FIXME bondolo 20040507 The ID created is really poor, it has only - // 2 unique bytes on average. it would be much better to hash something - // also, since the the definition of how to use the seed bytes is not - // fixed, it's not reliable. - PipeID pipeId = IDFactory.newPipeID(destGroup.getPeerGroupID() - , - (SERVICE_NAME + group.getPeerGroupID().getUniqueValue().toString() + name).getBytes()); - - adv.setPipeID(pipeId); - adv.setType(PipeService.PropagateType); - adv.setName(SERVICE_NAME + " pipe for " + group.getPeerGroupID()); - - return adv; - } - - private synchronized void openWirePipes() { - - PipeService pipes = group.getPipeService(); - - if (null == pipes) { - scheduleOpenPipes(TimeUtils.ASECOND); // Try again in one second. - return; - } - - try { - // First, listen to in our own PeerGroup - if (null == localGroupWirePipeInputPipe) { - localGroupWirePipeInputPipe = pipes.createInputPipe(localGroupWirePipeAdv, new WirePipeListener()); - } - - if (null == localGroupWirePipeOutputPipe) { - // Creates the OutputPipe - note that timeout is irrelevant for - // propagated pipe. - - localGroupWirePipeOutputPipe = pipes.createOutputPipe(localGroupWirePipeAdv, 1 * TimeUtils.ASECOND); - } - - if (localGroupWirePipeOutputPipe == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Cannot get OutputPipe for current group"); - } - } - } catch (Exception failed) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("PipeService not ready yet. Trying again in 1 second."); - } - // Try again in one second. - scheduleOpenPipes(TimeUtils.ASECOND); - return; - } - - if (advertisingGroup != null) { - try { - pipes = advertisingGroup.getPipeService(); - - if (null == pipes) { - // Try again in one second. - scheduleOpenPipes(TimeUtils.ASECOND); - return; - } - - if (null == wirePipeInputPipe) { - wirePipeInputPipe = pipes.createInputPipe(advGroupPropPipeAdv, new WirePipeListener()); - } - - if (null == wirePipeOutputPipe) { - wirePipeOutputPipe = pipes.createOutputPipe(advGroupPropPipeAdv, 1 * TimeUtils.ASECOND); - } - - if (wirePipeOutputPipe == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Cannot get OutputPipe for current group"); - } - } - } catch (Exception failed) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Could not open pipes in local group. Trying again in 1 second."); - } - // Try again in one second. - scheduleOpenPipes(TimeUtils.ASECOND); - return; - } - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Propagate Pipes opened."); - } - } - - private synchronized void closeWirePipes() { - - if (localGroupWirePipeInputPipe != null) { - localGroupWirePipeInputPipe.close(); - localGroupWirePipeInputPipe = null; - } - - if (localGroupWirePipeOutputPipe != null) { - localGroupWirePipeOutputPipe.close(); - localGroupWirePipeOutputPipe = null; - } - - if (wirePipeInputPipe != null) { - wirePipeInputPipe.close(); - wirePipeInputPipe = null; - } - - if (wirePipeOutputPipe != null) { - wirePipeOutputPipe.close(); - wirePipeOutputPipe = null; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Propagate Pipes closed."); - } - } - - /** - * Adapter class for receiving wire pipe messages - */ - private class WirePipeListener implements PipeMsgListener { - - /** - * {@inheritDoc} - */ - public void pipeMsgEvent(PipeMsgEvent event) { - - Message msg = event.getMessage(); - - boolean failure = (null != msg.getMessageElement(MESSAGE_NAMESPACE, FAILURE_ELEMENT_NAME)); - boolean response = (null != msg.getMessageElement(MESSAGE_NAMESPACE, RESPONSE_ELEMENT_NAME)); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "Received a PeerView " + (failure ? "failure " : "") + (response ? "response " : "") + "message [" + msg - + "] on propagated pipe " + event.getPipeID()); - } - - if (!failure && !response) { - - // If this is not a failure message then decide if we will respond. - // - // We play a game that is tuned by the view size so that the expectation of number of responses is equal to - // minHappyPeerView. The game is to draw a number between 0 and the pv size. If the result is < minHappyPeerView, - // then we win (respond) else we lose (stay silent). The probability of winning is HAPPY_SIZE/viewsize. If each of - // the viewsize peers plays the same game, on average HAPPY_SIZE of them win (with a significant variance, but - // that is good enough). If viewsize is <= HAPPY_SIZE, then all respond. This is approximate, of course, since - // the view size is not always consistent among peers. - - int viewsize = PeerView.this.localView.size(); - - if (viewsize > minHappyPeerView) { - int randinview = random.nextInt(viewsize); - - if (randinview >= minHappyPeerView) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Ignoring " + msg + " from pipe " + event.getPipeID()); - } - // We "lose". - return; - } - } // Else, we always win; don't bother playing. - } - - // Fabricate dummy src and dst addrs so that we can call processIncoming. These are - // only used for traces. The merit of using the pipeID is that it is recognizable - // in these traces. - EndpointAddress src = new EndpointAddress(event.getPipeID(), SERVICE_NAME, null); - EndpointAddress dest = new EndpointAddress(event.getPipeID(), SERVICE_NAME, null); - - try { - // call the peerview. - PeerView.this.processIncomingMessage(msg, src, dest); - } catch (Throwable ez) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed processing " + msg + " from pipe " + event.getPipeID(), ez); - } - } - } - } - - private synchronized void scheduleAdvertisingGroupQuery(long delay) { - - if (closed) { - return; - } - - TimerTask task = new AdvertisingGroupQueryTask(); - - addTask(task, delay, -1); - } - - /** - * Class implementing the query request on the AdvertisingGroup - */ - private final class AdvertisingGroupQueryTask extends TimerTask { - - /** - * {@inheritDoc} - */ - @Override - public boolean cancel() { - boolean res = super.cancel(); - return res; - } - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - if (closed) { - return; - } - - OutputPipe op = wirePipeOutputPipe; - - if (null != op) { - Message msg = makeMessage(self, false, false); - - op.send(msg); - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } finally { - removeTask(this); - } - } - } - - /** - * Get a copy of the PeerView for this group. - * - * @return A SortedSet which is the current local view of the peerview - */ - public SortedSet getView() { - synchronized (localView) { - return new TreeSet((SortedSet)localView); - } - } - - /** - * Add the provided element to the local peerview. - * - * @param pve the PeerViewElement to add. - * @return true if the element was not present and added - * otherwise false. - */ - private boolean addPeerViewElement(PeerViewElement pve) { - boolean added; - - if (null == pve.getRdvAdvertisement()) { - throw new IllegalStateException("Cannot add a seed pve to local view"); - } - - synchronized (localView) { - added = localView.add(pve); - - if (added) { - // Refresh, if necessary, our up and down peers. - updateUpAndDownPeers(); - } - } - - if (added) { - pve.setPeerView(this); - } - - return added; - } - - /** - * Remove the provided element from the local peerview. - * - * @param pve the PeerViewElement to remove. - * @return true if the element was present and removed - * otherwise false. - */ - private boolean removePeerViewElement(PeerViewElement pve) { - boolean removed; - - synchronized (localView) { - removed = localView.remove(pve); - - if (removed) { - // Refresh, if necessary, our up and down peers. - updateUpAndDownPeers(); - } - } - - if (removed) { - pve.setPeerView(null); - } - - return removed; - } - - /** - * Return from the local view, the PeerViewElement that is equal to the - * given PeerViewDestination, if one exists or null if it is - * not present. Identity is defined by {@link PeerViewDestination#equals} - * which only looks at the destination address. Thus a PeerViewDestination - * is enough. A full PeerViewElement may be passed as well. This method - * does not require external synchronization. - * - * @param wanted PeerViewDestination matching the desired one. - * @return the matching PeerViewElement or null if it could not - * be found. - */ - public PeerViewElement getPeerViewElement(PeerViewDestination wanted) { - - try { - PeerViewElement found = (PeerViewElement) localView.tailSet(wanted).first(); - - if (wanted.equals(found)) { - return found; - } - } catch (NoSuchElementException nse) {// This can happen if the tailset is empty. We could test for it, - // but it could still become empty after the test, since it reflects - // concurrent changes to localView. Not worth synchronizing for that - // rare occurence. The end-result is still correct. - } - - return null; - } - - /** - * Get from the local view, the PeerViewElement for the given PeerID, if one - * exists. Null otherwise. This method does not require external - * synchronization. - * - * @param pid the PeerID of the desired element. - * @return the matching PeerViewElement null if it could not be found. - */ - public PeerViewElement getPeerViewElement(ID pid) { - - return getPeerViewElement(new PeerViewDestination(pid)); - } - - /** - * Get the down peer from the local peer. - * - * @return the down PeerViewElement or null if there is no such peer. - */ - public PeerViewElement getDownPeer() { - return downPeer; - } - - /** - * Get the local peer. - * - * @return the local PeerViewElement - */ - public PeerViewElement getSelf() { - return self; - } - - /** - * Get the up peer from the local peer. - * - * @return the up PeerViewElement or null if there is no such peer. - */ - public PeerViewElement getUpPeer() { - return upPeer; - } - - /** - * update Up and Down Peers - */ - private void updateUpAndDownPeers() { - - synchronized (localView) { - final PeerViewElement oldDown = downPeer; - final PeerViewElement oldUp = upPeer; - - SortedSet headSet = localView.headSet(self); - - if (!headSet.isEmpty()) { - downPeer = (PeerViewElement) headSet.last(); - } else { - downPeer = null; - } - - SortedSet tailSet = localView.tailSet(self); - - if (!tailSet.isEmpty()) { - if (self.equals(tailSet.first())) { - Iterator eachTail = tailSet.iterator(); - - eachTail.next(); // self - - if (eachTail.hasNext()) { - upPeer = (PeerViewElement) eachTail.next(); - } else { - upPeer = null; - } - } else { - upPeer = (PeerViewElement) tailSet.first(); - } - } else { - upPeer = null; - } - - if ((oldDown != downPeer) && (downPeer != null)) { - downPeer.setLastUpdateTime(TimeUtils.timeNow()); - } - - if ((oldUp != upPeer) && (upPeer != null)) { - upPeer.setLastUpdateTime(TimeUtils.timeNow()); - } - } - } - - /** - * A task that checks on upPeer and downPeer. - */ - private final class WatchdogTask extends TimerTask { - - /** - * The number of iterations that the watchdog task has executed. - */ - int iterations = 0; - - WatchdogTask() {} - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - if (closed) { - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Watchdog task executing for group " + PeerView.this.group.getPeerGroupID()); - } - - refreshSelf(); - - if(0 == (iterations % 5)) { - DiscoveryService discovery = group.getDiscoveryService(); - if(null != discovery) { - discovery.publish(self.getRdvAdvertisement(), WATCHDOG_PERIOD * 10, WATCHDOG_PERIOD * 5); - } - } - - PeerViewElement up = PeerView.this.getUpPeer(); - - if (up != null) { - if (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), up.getLastUpdateTime()) > WATCHDOG_GRACE_DELAY) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("UP peer has gone MIA : " + up); - } - - notifyFailure(up, true); - - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Checking on UP peer : " + up); - } - - PeerView.this.send(up, PeerView.this.getSelf(), false, false); - } - } - - PeerViewElement down = PeerView.this.getDownPeer(); - - if (down != null) { - if (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), down.getLastUpdateTime()) > WATCHDOG_GRACE_DELAY) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("DOWN peer has gone MIA : " + down); - } - - notifyFailure(down, true); - - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Checking on DOWN peer : " + down); - } - - PeerView.this.send(down, PeerView.this.getSelf(), false, false); - } - } - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } - - iterations++; - } - } - - - /** - * Class implementing the kicker - */ - private final class KickerTask extends TimerTask { - - /** - * {@inheritDoc} - */ - @Override - public void run() { - try { - if (closed) { - return; - } - - PeerView.this.kick(); - } catch (Throwable all) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread : " + Thread.currentThread().getName(), all); - } - } finally { - removeTask(this); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewDestination.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewDestination.java deleted file mode 100644 index 27a25946..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewDestination.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rpv; - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.id.ID; - -/** - * This class contains only the comparable portion of PeerViewElement, so that it is possible - * to search for elements in the sorted set that the local PeerView is, without having - * enough information to create a valid PeerViewElement. - */ -class PeerViewDestination implements Comparable { - - /** - * The peer which is associated with this element. - */ - private final ID peerid; - - /** - * Constructs a PeerViewDestination from a (peer)ID. - */ - PeerViewDestination(ID destination) { - peerid = destination; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object other) { - return this == other || other instanceof PeerViewDestination && 0 == compareTo((PeerViewDestination) other); - - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return peerid.hashCode(); - } - - /** - * {@inheritDoc} - *

            - * Note that this compares the unique value of the id. - */ - public int compareTo(PeerViewDestination pve) { - String myUniqueValue = peerid.getUniqueValue().toString(); - String itsUniqueValue = pve.peerid.getUniqueValue().toString(); - - return myUniqueValue.compareTo(itsUniqueValue); - } - - /** - * Get the peer id of the peer associated with this connection. - * - * @return The peer id of the connected peer. - */ - public ID getPeerID() { - return peerid; - } - - /** - * returns the destination address. - * - * @return The endpoint address of the connected peer. - */ - public EndpointAddress getDestAddress() { - return new EndpointAddress(peerid, null, null); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewElement.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewElement.java deleted file mode 100644 index fab64a4d..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewElement.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rpv; - -import java.io.IOException; - -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.OutgoingMessageEvent; -import net.jxta.endpoint.OutgoingMessageEventListener; -import net.jxta.impl.util.TimeUtils; -import net.jxta.protocol.RdvAdvertisement; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -/** - * An element of the PeerView. - * - *

            The destination address (peerID) is part of PeerViewDestination, which implements the - * comparable interface. That makes it possible to sort and create ordered lists of - * PeerViewElements, and to search these lists while knowing only a destination address. - */ -public final class PeerViewElement extends PeerViewDestination implements OutgoingMessageEventListener { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(PeerViewElement.class.getName()); - - /** - * EndpointService that this PeerViewElement must use. - */ - private final EndpointService endpoint; - - /** - * Absolute time in milliseconds at which this element was created. - */ - private final long created; - - /** - * Absolute time in milliseconds at which this element was created. - */ - private long lastUpdate = 0; - - /** - * The encapsulated RdvAdvertisement for the Peer this instance - * represents. - */ - private RdvAdvertisement radv = null; - - /** - * True is the remote peer is known to be alive, false otherwise. - * It is always alive at birth. It may die soon after and we want to - * generate an event in that case. - */ - private boolean alive = true; - - /** - * If true then we are not accepting new messages until something unclogs. - */ - private volatile boolean throttling = false; - - /** - * PeerView that owns this PeerViewElement. - */ - private PeerView peerview = null; - - /** - * A cached Messenger for sending to the destination peer. - */ - private Messenger cachedMessenger = null; - - /** - * Initialize from a RdvAdvertisement. - * - * @param endpoint The endpoint service. - * @param radv the RdvAdvertisement from which to initialize - */ - PeerViewElement(EndpointService endpoint, RdvAdvertisement radv) { - - super(radv.getPeerID()); - - this.endpoint = endpoint; - this.radv = radv; - - created = TimeUtils.timeNow(); - lastUpdate = created; - } - - /** - * {@inheritDoc} - *

            - * A simple implementation for debugging. Do not attempt to parse this value! - */ - @Override - public String toString() { - StringBuilder asString = new StringBuilder(); - - asString.append('\"'); - asString.append(radv.getName()); - asString.append('\"'); - asString.append(alive ? " A " : " a "); - asString.append(isInPeerView() ? " P " : " p "); - asString.append(throttling ? " T " : " t "); - asString.append(" ["); - asString.append(TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), created) / TimeUtils.ASECOND); - asString.append("/"); - asString.append(TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), lastUpdate) / TimeUtils.ASECOND); - asString.append("]"); - return asString.toString(); - } - - /** - * {@inheritDoc} - */ - public void messageSendSucceeded(OutgoingMessageEvent e) { - - // As far as we know, connectivity is fine. - setAlive(true, true); - - throttling = false; - } - - /** - * {@inheritDoc} - */ - public void messageSendFailed(OutgoingMessageEvent e) { - - // As far as we know, connectivity is down. - // Except if failure is null; then it's just a queue overflow. - - if (null != e.getFailure()) { - setAlive(false, true); - } - - throttling = (e.getFailure() == null); - } - - /** - * Return true if the remote peer is known to be alive, - * false otherwise. - * - * @return Return true if the remote peer is known to be - * alive, false otherwise. - */ - public boolean isAlive() { - return alive; - } - - /** - * Update the connection status based upon the result of the last message - * send. - * - *

            We track the current dead-alive state and If we're in a peerview - * notify it of the transitions from alive to dead. - * - * @param live The known liveness of our connection to this peer. - * @param doNotify {@code true} will cause failure notifications to be sent. - * {@code false} makes notifications the caller's responsibility. - * @return {@code true} if a failure notification needs to be sent otherwise - * {@code false}. - */ - boolean setAlive(boolean live, boolean doNotify) { - boolean mustNotify; - - synchronized (this) { - mustNotify = alive && !live; - alive = live; - } - - // Since we do this out of sync, it is in theory possible that our alive - // status has already changed. It is rare but will only cause a little - // shake. So leave the sync behind, it causes a deadlock. - if (mustNotify && doNotify) { - PeerView temp = peerview; - - if (null != temp) { - temp.notifyFailure(this, true); - } - } - - return mustNotify; - } - - boolean isInPeerView() { - return (null != peerview); - } - - /** - * Sets the peerview - */ - synchronized void setPeerView(PeerView pv) { - if ((null != peerview) && (null != pv)) { - throw new IllegalStateException("Element already in " + peerview); - } - - peerview = pv; - } - - /** - * Return the time in absolute milliseconds at which we last updated this peer. - */ - long getLastUpdateTime() { - return lastUpdate; - } - - /** - * Sets the time in absolute milliseconds at which we last updated this peer. - */ - void setLastUpdateTime(long last) { - lastUpdate = last; - } - - /** - * Send a message to the peer which is represented by the current - * PeerViewElement. - * - * @param msg the message to send - * - * @param serviceName the service name on the destination peer to - * which the message will be demultiplexed - * - * @param serviceParam the service param on the destination peer - * to which the message will be demultiplexed - * - * @return true if the message was successfully handed off to the - * endpoint for delivery, false otherwise - */ - public boolean sendMessage(Message msg, String serviceName, String serviceParam) { - - if (throttling) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Declining to send -- throttling on " + this); - } - return false; - } - - Messenger sendVia = getCachedMessenger(); - - if (null == sendVia) { - // There is nothing really we can do. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Could not get messenger for " + getPeerID()); - } - - OutgoingMessageEvent event = new OutgoingMessageEvent(msg, - new IOException("Couldn't get messenger for " + getPeerID())); - - messageSendFailed(event); - return false; - } - - sendVia.sendMessage(msg, serviceName, serviceParam, this); - - return true; - } - - /** - * Get the encapsulated Peer Advertisement. - * - * @return the Advertisement of the Peer represented by this - * object - */ - public RdvAdvertisement getRdvAdvertisement() { - return radv; - } - - /** - * Set the encapsulated Peer Advertisement. - * - * @param adv is the RdvAdvertisement to be set. - * @return RdvAdvertisement the old Advertisement of the Peer represented by this - * object - */ - RdvAdvertisement setRdvAdvertisement(RdvAdvertisement adv) { - - if (!radv.getPeerID().equals(adv.getPeerID())) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("adv refers to a different peer"); - } - - throw new IllegalArgumentException("adv refers to a different peer"); - } - - RdvAdvertisement old = radv; - - this.radv = adv; - - setLastUpdateTime(TimeUtils.timeNow()); - - return old; - } - - /** - * Return a messenger suitable for sending to this peer. - * - * @return a messenger to this PVE peer or if {@code null} if peer is - * unreachable. - */ - private Messenger getCachedMessenger() { - - boolean mustNotify = false; - - synchronized (this) { - if ((null == cachedMessenger) || ((cachedMessenger.getState() & Messenger.USABLE) == 0)) { - cachedMessenger = null; - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting cached Messenger for " + radv.getName()); - } - - cachedMessenger = endpoint.getMessengerImmediate(getDestAddress(), radv.getRouteAdv()); - - if (null == cachedMessenger) { - mustNotify = setAlive(false, false); - } else if ((cachedMessenger.getState() & Messenger.RESOLVED) != 0) { - mustNotify = setAlive(true, false); - } - } - } - - // Since we do this out of sync, it is in theory possible that our alive - // status has already changed. It is rare but will only cause a little - // shake. So leave the sync behind, it causes a deadlock. - if (mustNotify) { - PeerView temp = peerview; - - if (null != temp) { - temp.notifyFailure(this, true); - } - } - - return cachedMessenger; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewEvent.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewEvent.java deleted file mode 100644 index 023bc5ea..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewEvent.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rpv; - -import java.util.EventObject; - -/** - * Container for PeerViewEvent events. - */ -public class PeerViewEvent extends EventObject { - - public static final int ADD = 10; - public static final int REMOVE = 11; - public static final int FAIL = 12; - - private static final String EVENTNAMES[] = { - "ADD", "REMOVE", "FAIL" - }; - - private int type; - private PeerViewElement element; - - /** - * Creates a new event - * - * @param source The peer view which is generating the event. - * @param type the event type - * @param element the peer associated with the event - */ - public PeerViewEvent(Object source, int type, PeerViewElement element) { - super(source); - this.type = type; - this.element = element; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - String eventType; - - if ((type >= ADD) && (type <= FAIL)) { - eventType = EVENTNAMES[type - ADD]; - } else { - eventType = "UNKNOWN (" + type + ")"; - } - - return super.toString() + " : " + eventType + " for " + element; - } - - /** - * Returns the event type - * - * @return int type - */ - public int getType() { - return type; - } - - /** - * Returns the PeerViewElement - * - * @return the peer view element associated with the event - */ - public PeerViewElement getPeerViewElement() { - - return element; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewListener.java deleted file mode 100644 index cdad84e8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewListener.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rpv; - -import java.util.EventListener; - -/** - * The listener interface for receiving PeerView events - */ -public interface PeerViewListener extends EventListener { - - /** - * Called when a peer view event occurs - * @param event the peerViewEvent event - */ - void peerViewEvent(PeerViewEvent event); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewRandomStrategy.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewRandomStrategy.java deleted file mode 100644 index 08a73711..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewRandomStrategy.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2002 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rpv; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.SortedSet; - -/** - * Random without replacement - */ -final class PeerViewRandomStrategy implements PeerViewStrategy { - - private SortedSet set; - private List copy = new ArrayList(); - - PeerViewRandomStrategy(SortedSet set) { - this.set = set; - reset(); - } - - /** - * {@inheritDoc} - */ - public void reset() { - copy.clear(); - copy.addAll(set); - Collections.shuffle(copy); - } - - /** - * {@inheritDoc} - */ - public PeerViewElement next() { - synchronized (set) { - if (set.isEmpty()) { - copy.clear(); - return null; - } - - if (copy.isEmpty()) { - reset(); - } - - PeerViewElement pve = (PeerViewElement) copy.remove(0); - - if (set.contains(pve)) { - return pve; - } - } - return next(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewRandomWithReplaceStrategy.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewRandomWithReplaceStrategy.java deleted file mode 100644 index 99b08981..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewRandomWithReplaceStrategy.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2002 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rpv; - -import java.util.Random; -import java.util.SortedSet; -import java.util.Iterator; - -/** - * Random with replacement - */ -class PeerViewRandomWithReplaceStrategy implements PeerViewStrategy { - - private static Random random = new Random(); - private SortedSet set = null; - - PeerViewRandomWithReplaceStrategy(SortedSet set) { - this.set = set; - } - - /** - * {@inheritDoc} - */ - public void reset() { - } - - /** - * {@inheritDoc} - */ - public PeerViewElement next() { - synchronized (set) { - if (set.isEmpty()) { - return null; - } - - int i = random.nextInt(set.size()); - - // return the ith element - int n = 0; - Iterator si = set.iterator(); - - while (n < i) { - si.next(); - n++; - } - return (PeerViewElement) si.next(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewSequentialStrategy.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewSequentialStrategy.java deleted file mode 100644 index 59c707a5..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewSequentialStrategy.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2002-2004 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rpv; - -import java.util.SortedSet; -import java.util.Iterator; - -/** - * Sequential - */ -class PeerViewSequentialStrategy implements PeerViewStrategy { - - private final SortedSet set; - private PeerViewElement current; - - PeerViewSequentialStrategy(SortedSet aset) { - set = aset; - reset(); - } - - /** - * {@inheritDoc} - */ - public void reset() { - current = null; - } - - /** - * {@inheritDoc} - */ - public PeerViewElement next() { - - synchronized (set) { - do { - if (null == current) { - if (!set.isEmpty()) { - // no current, take the first - current = (PeerViewElement) set.first(); - break; - } else { - // no first, return null - break; - } - } else { - SortedSet tail = set.tailSet(current); - - Iterator fromTail = tail.iterator(); - - if (fromTail.hasNext()) { - PeerViewDestination tailFirst = fromTail.next(); - - if (0 == current.compareTo(tailFirst)) { - if (fromTail.hasNext()) { - // first in tail is current so the new current - // is second in tail. - current = (PeerViewElement) fromTail.next(); - break; - } else { - // none left in tail after current, start over. - current = null; - } - } else { - // current is not in the tail set, so first in tail - // is new current - current = (PeerViewElement) tailFirst; - break; - } - } else { - // none in tail, start over. - current = null; - } - } - //FIXME by hamada this does not loop, current is always null, is the intended behavior? - } while (null == current); - } - - return current; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewStrategy.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewStrategy.java deleted file mode 100644 index 7ce022e3..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerViewStrategy.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2002 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rpv; - -/** - * Describes a strategy for iterating over the values in a peerview. - */ -interface PeerViewStrategy { - - /** - * Reset the strategy. The meaning of reset depends entirely on the strategy - * which is used to return peer view elements. - */ - void reset(); - - /** - * Return the next PeerView Element using the strategy applied by this - * instance. - * - * @return the next peer view element in sequence or null if the peerview - * is empty. - */ - PeerViewElement next(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerviewSeedingManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerviewSeedingManager.java deleted file mode 100644 index f456b30e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/rendezvous/rpv/PeerviewSeedingManager.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.rendezvous.rpv; - -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import java.util.logging.Logger; -import java.util.logging.Level; - -import net.jxta.logging.Logging; - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.TextDocumentMessageElement; - -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.RouteAdvertisement; - -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.impl.util.ACLSeedingManager; -import net.jxta.impl.util.TimeUtils; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.PipeAdvertisement; - -/** - * A Seeding Manager which uses the peerview advertisement pipes in order to - * locate seed peers for a given peer group. - */ -public class PeerviewSeedingManager extends ACLSeedingManager implements EndpointListener { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(PeerviewSeedingManager.class.getName()); - - /** - * This is the minimum interval at which we will refresh our "peerview" - */ - protected final static long MINIMUM_PEERVIEW_REFRESH_INTERVAL = 1 * TimeUtils.AMINUTE; - - /** - * The standard time interval after which we will refresh our "peerview" - */ - protected final static long STANDARD_PEERVIEW_REFRESH_INTERVAL = 20 * TimeUtils.AMINUTE; - - /** - * Our mock peerview we use to keep responses. - */ - protected Set peerview = new HashSet(); - - /** - * The absolute time at which we will refresh our "PeerView" - */ - protected long nextPeerViewRefresh = 0; - - /** - * The absolute time at which we will refresh our "PeerView" - */ - protected int unsuccessfulProbes = 0; - - protected final PeerGroup advGroup; - - protected final PeerGroup group; - - protected final String name; - - protected final PipeAdvertisement advPipeAdv; - - /** - * Creates a new instance of PeerviewSeedingManager - * - * @param aclLocation ACL uri - * @param group the group context - * @param advGroup the advertising group - * @param name service name - */ - public PeerviewSeedingManager(URI aclLocation, PeerGroup group, PeerGroup advGroup, String name) { - super(aclLocation); - - this.group = group; - this.advGroup = advGroup; - this.name = name; - - advPipeAdv = PeerView.makeWirePipeAdvertisement(advGroup, group, name); - - group.getEndpointService().addIncomingMessageListener(this, PeerView.SERVICE_NAME, group.getPeerGroupID().getUniqueValue().toString()); - } - - /** - * {@inheritDoc} - */ - public void stop() { - group.getEndpointService().removeIncomingMessageListener(PeerView.SERVICE_NAME, group.getPeerGroupID().getUniqueValue().toString()); - } - - /** - * Adds a rpv seed - * - * @param seed the seed - */ - public void addSeed(RouteAdvertisement seed) { - peerview.add(seed); - } - - /** - * {@inheritDoc} - */ - public URI[] getActiveSeedURIs() { - throw new UnsupportedOperationException("Not supported."); - } - - /** - * {@inheritDoc} - */ - public synchronized RouteAdvertisement[] getActiveSeedRoutes() { - refreshActiveSeeds(); - - List result = new ArrayList(); - - for (RouteAdvertisement anRA : peerview) { - result.add(anRA.clone()); - } - - return result.toArray(new RouteAdvertisement[result.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized boolean isAcceptablePeer(RouteAdvertisement radv) { - boolean acceptable = peerview.contains(radv); - - return acceptable && super.isAcceptablePeer(radv); - } - - protected void refreshActiveSeeds() { - if (TimeUtils.timeNow() < nextPeerViewRefresh) { - return; - } - - // remove the old stale entries. - peerview.clear(); - - Message message = makeMessage(); - - try { - PipeService pipes = advGroup.getPipeService(); - - OutputPipe output = pipes.createOutputPipe(advPipeAdv, 30 * TimeUtils.ASECOND); - - output.send(message); - - output.close(); - - // Only update the refresh if we we able to send. - - long untilNextRefresh; - - if (peerview.isEmpty()) { - unsuccessfulProbes++; - untilNextRefresh = Math.min(unsuccessfulProbes * MINIMUM_PEERVIEW_REFRESH_INTERVAL, - STANDARD_PEERVIEW_REFRESH_INTERVAL); - } else { - untilNextRefresh = STANDARD_PEERVIEW_REFRESH_INTERVAL; - } - - nextPeerViewRefresh = TimeUtils.toAbsoluteTimeMillis(untilNextRefresh); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed sending " + message + ".", failed); - } - } - } - - /** - * Make a PeerView Message. - * - * @return a peer view message - */ - private Message makeMessage() { - - Message msg = new Message(); - - msg.addMessageElement(PeerView.MESSAGE_NAMESPACE, PeerView.EDGE_ELEMENT); - - RdvAdvertisement radv = PeerView.createRdvAdvertisement(group.getPeerAdvertisement(), name); - - XMLDocument doc = (XMLDocument) radv.getDocument(MimeMediaType.XMLUTF8); - - MessageElement msge = new TextDocumentMessageElement(PeerView.MESSAGE_ELEMENT_NAME, doc, null); - - msg.addMessageElement(PeerView.MESSAGE_NAMESPACE, msge); - - return msg; - } - - /** - * {@inheritDoc} - *

            - *

            Listener for "PeerView"/<peergroup-unique-id> and propagate pipes. - */ - public synchronized void processIncomingMessage(Message msg, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - // check what kind of message this is (response or not). - boolean isResponse = false; - MessageElement me = msg.getMessageElement(PeerView.MESSAGE_NAMESPACE, PeerView.MESSAGE_ELEMENT_NAME); - - if (me == null) { - me = msg.getMessageElement(PeerView.MESSAGE_NAMESPACE, PeerView.RESPONSE_ELEMENT_NAME); - if (me == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Discarding damaged " + msg + "."); - } - return; - } else { - isResponse = true; - } - } - - Advertisement adv; - - try { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(me); - - adv = AdvertisementFactory.newAdvertisement(asDoc); - } catch (RuntimeException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building rdv advertisement from message element", failed); - } - return; - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building rdv advertisement from message element", failed); - } - return; - } - - if (!(adv instanceof RdvAdvertisement)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Response does not contain radv (" + adv.getAdvertisementType() + ")"); - } - return; - } - - RdvAdvertisement radv = (RdvAdvertisement) adv; - - if (null == radv.getRouteAdv()) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Radv does not contain route"); - } - return; - } - - // See if we can find a src route adv in the message.s - me = msg.getMessageElement(PeerView.MESSAGE_NAMESPACE, PeerView.SRCROUTEADV_ELEMENT_NAME); - if (me != null) { - try { - XMLDocument asDoc = (XMLDocument) StructuredDocumentFactory.newStructuredDocument(me); - Advertisement routeAdv = AdvertisementFactory.newAdvertisement(asDoc); - - if (!(routeAdv instanceof RouteAdvertisement)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Advertisement is not a RouteAdvertisement"); - } - } else { - RouteAdvertisement rdvRouteAdv = radv.getRouteAdv().clone(); - - // XXX we stich them together even if in the end it gets optimized away - RouteAdvertisement.stichRoute(rdvRouteAdv, (RouteAdvertisement) routeAdv); - radv.setRouteAdv(rdvRouteAdv); - } - } catch (RuntimeException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building route adv from message element", failed); - } - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building route adv from message element", failed); - } - } - } - me = null; - - // Is this a message about ourself? - if (group.getPeerID().equals(radv.getPeerID())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Received a PeerView message about self. Discard."); - } - - return; - } - - // Collect the various flags. - - boolean isFailure = (msg.getMessageElement(PeerView.MESSAGE_NAMESPACE, PeerView.FAILURE_ELEMENT_NAME) != null); - boolean isCached = (msg.getMessageElement(PeerView.MESSAGE_NAMESPACE, PeerView.CACHED_RADV_ELEMENT_NAME) != null); - boolean isFromEdge = (msg.getMessageElement(PeerView.MESSAGE_NAMESPACE, PeerView.EDGE_ELEMENT_NAME) != null); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - String srcPeer = srcAddr.toString(); - LOG.fine("[" + group.getPeerGroupID() + "] Received a" + (isCached ? " cached" : "") + (isResponse ? " response" : "") - + (isFailure ? " failure" : "") + " message (" + msg.toString() + ")" + (isFromEdge ? " from edge" : "") - + " regarding \"" + radv.getName() + "\" from " + srcPeer); - } - - if (!isResponse || isFailure || isCached || isFromEdge) { - // We don't care about anything except responses from active rdvs. - return; - } - - peerview.add(radv.getRouteAdv()); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/InternalQueryHandler.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/InternalQueryHandler.java deleted file mode 100644 index 03171ed6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/InternalQueryHandler.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver; - - -import net.jxta.resolver.QueryHandler; -import net.jxta.protocol.ResolverResponseMsg; -import net.jxta.protocol.ResolverQueryMsg; -import net.jxta.endpoint.EndpointAddress; - - -/** - * Services that wish to act as a resolver handler must implement this interface. - *

            - * This interface extends the normal resolver query handler interface to add the - * source of the query. Typically this the query's last hop which may or may not - * be the same as the query's originator. Knowing the source of the query can be - * useful for sending NAK messages. - * - * @see net.jxta.resolver.ResolverService - * @see net.jxta.protocol.ResolverQueryMsg - */ -public interface InternalQueryHandler extends QueryHandler { - - /** - * Process the resolver query, and generate response - * it is the responsibility of the handler to send the response - * - *

            -     * result = processIncommingQuery(query);
            -     * if (result != null) {
            -     *   resolver.sendResponse(query.getSrc(), response);
            -     *   return resolver.OK;
            -     *  } else return resolver.Repropagate;
            -     * 
            - * - * @param srcAddr source address - * @param query ResolverQueryMsg query - * @return int status, {@link net.jxta.resolver.ResolverService#OK OK} success, - * {@link net.jxta.resolver.ResolverService#Repropagate Repropagate} to - * indicate a re-propagation is needed - */ - - public int processQuery(ResolverQueryMsg query, EndpointAddress srcAddr); - - /** - * Called when messages are received by the ResolverService - * it calls back this method to deal with received responses - * - * @param response ResolverQueryMsg response - * @param srcAddr source address - */ - public void processResponse(ResolverResponseMsg response, EndpointAddress srcAddr); - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/ResolverServiceImpl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/ResolverServiceImpl.java deleted file mode 100644 index e505e26b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/ResolverServiceImpl.java +++ /dev/null @@ -1,1293 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver; - -import net.jxta.credential.Credential; -import net.jxta.document.Advertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.XMLDocument; -import net.jxta.endpoint.*; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.impl.endpoint.router.EndpointRouter; -import net.jxta.impl.endpoint.router.RouteControl; -import net.jxta.impl.meter.MonitorManager; -import net.jxta.impl.protocol.ResolverQuery; -import net.jxta.impl.protocol.ResolverResponse; -import net.jxta.impl.protocol.ResolverSrdiMsgImpl; -import net.jxta.impl.resolver.resolverMeter.QueryHandlerMeter; -import net.jxta.impl.resolver.resolverMeter.ResolverMeter; -import net.jxta.impl.resolver.resolverMeter.ResolverMeterBuildSettings; -import net.jxta.impl.resolver.resolverMeter.ResolverServiceMonitor; -import net.jxta.impl.resolver.resolverMeter.SrdiHandlerMeter; -import net.jxta.logging.Logging; -import net.jxta.membership.MembershipService; -import net.jxta.meter.MonitorResources; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.ResolverQueryMsg; -import net.jxta.protocol.ResolverResponseMsg; -import net.jxta.protocol.ResolverSrdiMsg; -import net.jxta.protocol.RouteAdvertisement; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.rendezvous.RendezVousStatus; -import net.jxta.resolver.QueryHandler; -import net.jxta.resolver.ResolverService; -import net.jxta.resolver.SrdiHandler; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -/** - * Implements the {@link net.jxta.resolver.ResolverService} using the standard - * JXTA Endpoint Resolver Protocol (ERP). - * - * @see net.jxta.resolver.ResolverService - * @see JXTA Protocols Specification : Endpoint Resolver Protocol - */ -public class ResolverServiceImpl implements ResolverService { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(ResolverServiceImpl.class.getName()); - - /** - * Resolver query endpoint postfix - */ - public final static String outQueNameShort = "ORes"; - - /** - * Resolver response endpoint postfix - */ - public final static String inQueNameShort = "IRes"; - - /** - * Resolver srdi endpoint postfix - */ - public final static String srdiQueNameShort = "Srdi"; - - /** - * MIME Type for gzipped SRDI messages. - */ - private final static MimeMediaType GZIP_MEDIA_TYPE = new MimeMediaType("application/gzip").intern(); - - private String outQueName = outQueNameShort; - private String inQueName = inQueNameShort; - private String srdiQueName = srdiQueNameShort; - - private String handlerName = null; - private PeerGroup group = null; - private ModuleImplAdvertisement implAdvertisement = null; - private EndpointService endpoint = null; - private MembershipService membership = null; - - private RouteControl routeControl = null; - - private final Map handlers = Collections.synchronizedMap(new HashMap(5)); - private final Map srdiHandlers = Collections.synchronizedMap(new HashMap(5)); - - private EndpointListener queryListener = null; - private EndpointListener responseListener = null; - private EndpointListener srdiListener = null; - - private ResolverServiceMonitor resolverServiceMonitor; - private ResolverMeter resolverMeter; - - /** - * the resolver interface object - */ - private ResolverService resolverInterface = null; - - /** - * Encapsulates current Membership Service credential. - */ - final static class CurrentCredential { - - /** - * The current default credential - */ - final Credential credential; - - /** - * The current default credential in serialized XML form. - */ - final XMLDocument credentialDoc; - - CurrentCredential(Credential credential, XMLDocument credentialDoc) { - this.credential = credential; - this.credentialDoc = credentialDoc; - } - } - - /** - * The current Membership service default credential. - */ - CurrentCredential currentCredential; - - /** - * Listener we use for membership property events. - */ - private class CredentialListener implements PropertyChangeListener { - - /** - * Standard Constructor - */ - CredentialListener() { - } - - /** - * {@inheritDoc} - */ - public void propertyChange(PropertyChangeEvent evt) { - if (MembershipService.DEFAULT_CREDENTIAL_PROPERTY.equals(evt.getPropertyName())) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("New default credential event"); - } - - synchronized (ResolverServiceImpl.this) { - Credential cred = (Credential) evt.getNewValue(); - XMLDocument credentialDoc; - - if (null != cred) { - try { - credentialDoc = (XMLDocument) cred.getDocument(MimeMediaType.XMLUTF8); - currentCredential = new CurrentCredential(cred, credentialDoc); - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not generate credential document", all); - } - currentCredential = null; - } - } else { - currentCredential = null; - } - } - } - } - } - - final CredentialListener membershipCredListener = new CredentialListener(); - - /** - * Convenience method for constructing an endpoint address from an id - * - * @param destPeer peer id - * @param serv the service name (if any) - * @param parm the service param (if any) - * @return endpointAddress for this peer id. - */ - private static EndpointAddress mkAddress(ID destPeer, String serv, String parm) { - return new EndpointAddress("jxta", destPeer.getUniqueValue().toString(), serv, parm); - } - - /** - * {@inheritDoc} - */ - public void init(PeerGroup group, ID assignedID, Advertisement impl) { - implAdvertisement = (ModuleImplAdvertisement) impl; - - this.group = group; - handlerName = assignedID.toString(); - String uniqueStr = group.getPeerGroupID().getUniqueValue().toString(); - - outQueName = uniqueStr + outQueNameShort; - inQueName = uniqueStr + inQueNameShort; - srdiQueName = uniqueStr + srdiQueNameShort; - - if (ResolverMeterBuildSettings.RESOLVER_METERING) { // Fix-Me: This needs to be moved to startApp() when the load order issue is resolved - resolverServiceMonitor = (ResolverServiceMonitor) MonitorManager.getServiceMonitor(group, - MonitorResources.resolverServiceMonitorClassID); - if (resolverServiceMonitor != null) { - resolverMeter = resolverServiceMonitor.getResolverMeter(); - } - } - - // Tell tell the world about our configuration. - if (Logging.SHOW_CONFIG && LOG.isLoggable(Level.CONFIG)) { - StringBuilder configInfo = new StringBuilder("Configuring Resolver Service : " + assignedID); - - if (implAdvertisement != null) { - configInfo.append("\n\tImplementation :"); - configInfo.append("\n\t\tModule Spec ID: ").append(implAdvertisement.getModuleSpecID()); - configInfo.append("\n\t\tImpl Description : ").append(implAdvertisement.getDescription()); - configInfo.append("\n\t\tImpl URI : ").append(implAdvertisement.getUri()); - configInfo.append("\n\t\tImpl Code : ").append(implAdvertisement.getCode()); - } - - configInfo.append("\n\tGroup Params :"); - configInfo.append("\n\t\tGroup : ").append(group); - configInfo.append("\n\t\tPeer ID : ").append(group.getPeerID()); - - configInfo.append("\n\tConfiguration:"); - configInfo.append("\n\t\tIn Queue name: ").append(outQueName); - configInfo.append("\n\t\tOut Queue name: ").append(inQueName); - configInfo.append("\n\t\tSRDI Queue name: ").append(srdiQueName); - - LOG.config(configInfo.toString()); - } - } - - /** - * {@inheritDoc} - */ - public int startApp(String[] arg) { - endpoint = group.getEndpointService(); - - if (null == endpoint) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is an endpoint service"); - } - return Module.START_AGAIN_STALLED; - } - - membership = group.getMembershipService(); - - if (null == membership) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Stalled until there is a membership service"); - } - return Module.START_AGAIN_STALLED; - } - - // Register Listeners - try { - // Register Query Listener - queryListener = new DemuxQuery(); - if (!endpoint.addIncomingMessageListener(queryListener, handlerName, outQueName)) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Cannot register listener (already registered)"); - } - } - - // Register Response Listener - responseListener = new DemuxResponse(); - if (!endpoint.addIncomingMessageListener(responseListener, handlerName, inQueName)) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Cannot register listener (already registered)"); - } - } - - // Register SRDI Listener - srdiListener = new DemuxSrdi(); - if (!endpoint.addIncomingMessageListener(srdiListener, handlerName, srdiQueName)) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.severe("Cannot register listener (already registered)"); - } - } - } catch (Exception e) { - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - LOG.log(Level.SEVERE, "failed to add listeners", e); - } - return -1; - } - - synchronized (this) { - // register our credential listener. - membership.addPropertyChangeListener(MembershipService.DEFAULT_CREDENTIAL_PROPERTY, membershipCredListener); - try { - // set the initial version of the default credential. - currentCredential = null; - Credential credential = membership.getDefaultCredential(); - XMLDocument credentialDoc; - if (null != credential) { - credentialDoc = (XMLDocument) credential.getDocument(MimeMediaType.XMLUTF8); - currentCredential = new CurrentCredential(credential, credentialDoc); - } - } catch (Exception all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "could not get default credential", all); - } - } - } - return Module.START_OK; - } - - /** - * {@inheritDoc} - */ - public void stopApp() { - endpoint.removeIncomingMessageListener(handlerName, outQueName); - endpoint.removeIncomingMessageListener(handlerName, inQueName); - - if (null != srdiListener) { - endpoint.removeIncomingMessageListener(handlerName, srdiQueName); - } - - queryListener = null; - responseListener = null; - srdiListener = null; - - membership.removePropertyChangeListener("defaultCredential", membershipCredListener); - currentCredential = null; - - routeControl = null; - membership = null; - group = null; - } - - /** - * {@inheritDoc} - */ - public synchronized ResolverService getInterface() { - if (resolverInterface == null) { - resolverInterface = new ResolverServiceInterface(this); - } - return resolverInterface; - } - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return implAdvertisement; - } - - /** - * {@inheritDoc} - */ - public QueryHandler registerHandler(String name, QueryHandler handler) { - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - resolverServiceMonitor.registerQueryHandlerMeter(name); - } - return handlers.put(name, handler); - } - - /** - * {@inheritDoc} - */ - public QueryHandler unregisterHandler(String name) { - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - resolverServiceMonitor.unregisterQueryHandlerMeter(name); - } - return handlers.remove(name); - } - - /** - * given a name returns the query handler associated with it - * - * @param name the handler to lookup - * @return returns the query handler - */ - public QueryHandler getHandler(String name) { - return handlers.get(name); - } - - /** - * {@inheritDoc} - */ - public SrdiHandler registerSrdiHandler(String name, SrdiHandler handler) { - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - resolverServiceMonitor.registerSrdiHandlerMeter(name); - } - return srdiHandlers.put(name, handler); - } - - /** - * {@inheritDoc} - */ - public SrdiHandler unregisterSrdiHandler(String name) { - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - resolverServiceMonitor.unregisterSrdiHandlerMeter(name); - } - return srdiHandlers.remove(name); - } - - /** - * given a name returns the srdi handler associated with it - * - * @param name the handler to lookup - * @return returns the SRDI handler - */ - public SrdiHandler getSrdiHandler(String name) { - return srdiHandlers.get(name); - } - - /** - * {@inheritDoc} - */ - public void sendQuery(String destPeer, ResolverQueryMsg query) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("sending query to resolver handler: " + query.getHandlerName()); - } - - // NOTE: Add route information about the issuing peer, so the - // resolver query responding peer can respond to the issuer without - // requiring any route discovery. In most case the responding peer - // is unlikely to know the route to the query issuer. This is a good - // optimization for edge peers. This optimzation is much less - // important for RDV peers as they are more likely to have a route - // to peers. Also, there is the concern that adding route info - // in resolver query exchanged between RDV will increase overhead due - // to the larger amount of information exchanged between RDV. - // Only update query if the query does not already contain any route - // information. We are mostly interested in the original src - // route information. - if (query.getSrcPeerRoute() == null) { - if (getRouteControl() != null) { - // FIXME tra 20031102 Until the new subscription service - // is implemented, we use the Router Control IOCTL - RouteAdvertisement route = routeControl.getMyLocalRoute(); - - if (route != null) { - query.setSrcPeerRoute(route.clone()); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending query with route info to " + destPeer); - } - } else { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No route control--could not set local route on query"); - } - } - } - - String queryHandlerName = query.getHandlerName(); - QueryHandlerMeter queryHandlerMeter = null; - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(queryHandlerName); - } - - if (destPeer == null) { - try { - Message queryMsg = new Message(); - XMLDocument asDoc = (XMLDocument) query.getDocument(MimeMediaType.XMLUTF8); - MessageElement docElem = new TextDocumentMessageElement(outQueName, asDoc, null); - queryMsg.addMessageElement("jxta", docElem); - RendezVousService rendezvous = group.getRendezVousService(); - - if (null != rendezvous) { - if (rendezvous.getRendezVousStatus() != RendezVousStatus.ADHOC) { - // Walk the message - rendezvous.walk(queryMsg.clone(), handlerName, outQueName, RendezVousService.DEFAULT_TTL); - } - // propagate to local net as well - rendezvous.propagateToNeighbors(queryMsg, handlerName, outQueName, 2); - } else { - endpoint.propagate(queryMsg, handlerName, outQueName); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - queryHandlerMeter.querySentInGroup(query); - } - } catch (IOException e) { - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - queryHandlerMeter.queryPropagateError(); - } - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure during propagate", e); - } - } - } else { - // unicast instead - boolean success = sendMessage(destPeer, null, handlerName, outQueName, outQueName, - (XMLDocument) query.getDocument(MimeMediaType.XMLUTF8), false); - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - if (success) { - queryHandlerMeter.querySentViaUnicast(destPeer, query); - } else { - queryHandlerMeter.querySendError(); - } - } - } - } - - /** - * {@inheritDoc} - */ - public void sendResponse(String destPeer, ResolverResponseMsg response) { - - if (destPeer == null) { - propagateResponse(response); - } else { - QueryHandlerMeter queryHandlerMeter = null; - try { - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(response.getHandlerName()); - } - - // Check if an optional route information is available to send the response - RouteAdvertisement route = response.getSrcPeerRoute(); - boolean success = sendMessage(destPeer, route, handlerName, inQueName, inQueName, - (XMLDocument) response.getDocument(MimeMediaType.XMLUTF8), false); - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - if (success) { - queryHandlerMeter.responseSentViaUnicast(destPeer, response); - } else { - queryHandlerMeter.responseSendError(); - } - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Error in sending response", e); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - queryHandlerMeter.responseSendError(); - } - } - } - } - - /** - * {@inheritDoc} - */ - public void sendSrdi(String destPeer, ResolverSrdiMsg srdi) { - String srdiHandlerName = srdi.getHandlerName(); - SrdiHandlerMeter srdiHandlerMeter = null; - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - srdiHandlerMeter = resolverServiceMonitor.getSrdiHandlerMeter(srdiHandlerName); - } - - if (destPeer == null) { - RendezVousService rendezvous = group.getRendezVousService(); - - if (rendezvous == null) { - // no rendezvous service, dump it. - return; - } - Message propagateMsg = new Message(); - - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gos = new GZIPOutputStream(baos); - - srdi.getDocument(MimeMediaType.XMLUTF8).sendToStream(gos); - gos.finish(); - gos.close(); - byte gzipBytes[] = baos.toByteArray(); - - MessageElement zipElem = new ByteArrayMessageElement(srdiQueName, GZIP_MEDIA_TYPE, gzipBytes, null); - - propagateMsg.addMessageElement("jxta", zipElem); - - if (rendezvous.getRendezVousStatus() != RendezVousStatus.ADHOC) { - rendezvous.walk(propagateMsg, handlerName, srdiQueName, RendezVousService.DEFAULT_TTL); - } - - // propagate to local net as well - rendezvous.propagateToNeighbors(propagateMsg, handlerName, srdiQueName, 2); - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (srdiHandlerMeter != null)) { - srdiHandlerMeter.messageSentViaWalker(srdi); - } - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure sending srdi message", e); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (srdiHandlerMeter != null)) { - srdiHandlerMeter.errorPropagatingMessage(); - } - } - } else { - try { - boolean success = sendMessage(destPeer, null, handlerName, srdiQueName, srdiQueName, - (XMLDocument) srdi.getDocument(MimeMediaType.XMLUTF8), - // compression - true); - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (srdiHandlerMeter != null)) { - if (success) { - srdiHandlerMeter.messageSentViaUnicast(destPeer, srdi); - } else { - srdiHandlerMeter.errorSendingMessage(); - } - } - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Error in sending srdi message", e); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (srdiHandlerMeter != null)) { - srdiHandlerMeter.errorSendingMessage(); - } - } - } - } - - private void repropagateQuery(Message msg, ResolverQueryMsg query) { - RendezVousService rendezvous = group.getRendezVousService(); - - if ((null != rendezvous) && !group.isRendezvous()) { - // not a Rendezvous peer? Let someone else forward it. - return; - } - - // just in case an excessive of attempt to forward a query - // hopCount is used to determine forward counts independent of any other TTL - if (query.getHopCount() > 3) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("discarding ResolverQuery. HopCount exceeded : " + query.getHopCount()); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.propagationQueryDropped(query); - } - return; - } - - XMLDocument asDoc = (XMLDocument) query.getDocument(MimeMediaType.XMLUTF8); - MessageElement docElem = new TextDocumentMessageElement(outQueName, asDoc, null); - - msg.replaceMessageElement("jxta", docElem); - - // Re-propagate the message. - // Loop and TTL control is done in demux and propagate(). The TTL - // below is just a default it will be reduced appropriately. - - try { - if (null != rendezvous) { - if (rendezvous.getRendezVousStatus() != RendezVousStatus.ADHOC) { - rendezvous.walk(msg, handlerName, outQueName, RendezVousService.DEFAULT_TTL); - } - // propagate to local net as well - rendezvous.propagateToNeighbors(msg, handlerName, outQueName, 2); - } else { - endpoint.propagate(msg, handlerName, inQueName); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.queryPropagatedViaWalker(query); - } - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure propagating query", e); - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.queryPropagationError(query); - } - } - } - } - - /** - * Process a resolver query. - * - * @param query The query. - * @param srcAddr Who sent the query to us. May not be the same as the - * query originator. - * @return the query id assigned to the query - */ - private int processQuery(ResolverQueryMsg query, EndpointAddress srcAddr) { - String queryHandlerName = query.getHandlerName(); - QueryHandler theHandler = getHandler(queryHandlerName); - - if (query.getHopCount() > 2) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Discarding query #" + query.getQueryId() + " hopCount > 2 : " + query.getHopCount()); - } - - // query has been forwarded too many times stop - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - QueryHandlerMeter queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(queryHandlerName); - if (queryHandlerMeter != null) { - queryHandlerMeter.queryHopCountDropped(); - } else { - resolverMeter.invalidQueryDiscarded(srcAddr); - } - } - return ResolverService.OK; - } - - if (theHandler == null) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Discarding query #" + query.getQueryId() + ", no handler for :" + queryHandlerName); - } - // If this peer is a rendezvous peer, it needs to repropagate the query to other rendezvous peer that - // may have a handler. - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.unknownHandlerForQuery(query); - } - return ResolverService.Repropagate; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Handing query #" + query.getQueryId() + " to : " + queryHandlerName); - } - - QueryHandlerMeter queryHandlerMeter = null; - long startTime = 0; - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - startTime = System.currentTimeMillis(); - queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(queryHandlerName); - } - - try { - int result; - if (theHandler instanceof InternalQueryHandler) { - result = ((InternalQueryHandler) theHandler).processQuery(query, srcAddr); - } else { - result = theHandler.processQuery(query); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - queryHandlerMeter.queryProcessed(query, result, System.currentTimeMillis() - startTime); - } - return result; - } catch (Throwable any) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught Throwable from handler for : " + queryHandlerName, any); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - queryHandlerMeter.errorWhileProcessingQuery(query); - } - // stop repropagation - return ResolverService.OK; - } - } - - /** - * Process a resolver response. - * - * @param resp The response. - * @param srcAddr Who sent the response. May not be the same as the - * originator response. - */ - private void processResponse(ResolverResponseMsg resp, EndpointAddress srcAddr) { - String handlerName = resp.getHandlerName(); - - if (handlerName == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Missing handlername in response"); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.invalidResponseDiscarded(srcAddr); - } - return; - } - - QueryHandler theHandler = getHandler(handlerName); - if (theHandler == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("No handler for :" + handlerName); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.unknownHandlerForResponse(srcAddr, resp); - } - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Process response to query #" + resp.getQueryId() + " with " + handlerName); - } - - QueryHandlerMeter queryHandlerMeter = null; - long startTime = 0; - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - startTime = System.currentTimeMillis(); - queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(handlerName); - } - - try { - if (theHandler instanceof InternalQueryHandler) { - ((InternalQueryHandler) theHandler).processResponse(resp, srcAddr); - } else { - theHandler.processResponse(resp); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - queryHandlerMeter.responseProcessed(resp, System.currentTimeMillis() - startTime, srcAddr); - } - } catch (Throwable all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught Throwable from handler for: " + handlerName, all); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - queryHandlerMeter.errorWhileProcessingResponse(srcAddr); - } - } - } - - /** - * propagate a response - * - * @param response response message to propagate - */ - private void propagateResponse(ResolverResponseMsg response) { - - Message propagateMsg = new Message(); - - String queryHandlerName = response.getHandlerName(); - QueryHandlerMeter queryHandlerMeter = null; - - try { - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(queryHandlerName); - } - - XMLDocument responseDoc = (XMLDocument) response.getDocument(MimeMediaType.XMLUTF8); - MessageElement elemDoc = new TextDocumentMessageElement(inQueName, responseDoc, null); - propagateMsg.addMessageElement("jxta", elemDoc); - RendezVousService rendezvous = group.getRendezVousService(); - - if (null != rendezvous) { - rendezvous.walk(propagateMsg, handlerName, inQueName, RendezVousService.DEFAULT_TTL); - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - queryHandlerMeter.responseSentViaWalker(response); - } - } else { - endpoint.propagate(propagateMsg, handlerName, inQueName); - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - // FIXME bondolo 20040909 not technically the correct metric - queryHandlerMeter.responseSentViaWalker(response); - } - } - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "failure during propagateResponse", e); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (queryHandlerMeter != null)) { - queryHandlerMeter.responsePropagateError(); - } - } - } - - /** - * Process an SRDI message. - * - * @param srdimsg The SRDI message. - * @param srcAddr Who sent the message. May not be the same as the - * originator of the message. - */ - private void processSrdi(ResolverSrdiMsgImpl srdimsg, EndpointAddress srcAddr) { - String handlerName = srdimsg.getHandlerName(); - - if (handlerName == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Missing handlername in response"); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.invalidSrdiMessageDiscarded(srcAddr); - } - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Processing an SRDI msg for : " + handlerName + " in Group ID:" + group.getPeerGroupID()); - } - - SrdiHandler theHandler = getSrdiHandler(handlerName); - if (theHandler != null) { - SrdiHandlerMeter srdiHandlerMeter = null; - - try { - long startTime = 0; - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverServiceMonitor != null)) { - startTime = System.currentTimeMillis(); - srdiHandlerMeter = resolverServiceMonitor.getSrdiHandlerMeter(handlerName); - } - - theHandler.processSrdi(srdimsg); - if (ResolverMeterBuildSettings.RESOLVER_METERING && (srdiHandlerMeter != null)) { - srdiHandlerMeter.messageProcessed(srdimsg, System.currentTimeMillis() - startTime, srcAddr); - } - } catch (Throwable all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught Throwable from handler for: " + handlerName, all); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (srdiHandlerMeter != null)) { - srdiHandlerMeter.errorWhileProcessing(srcAddr); - } - } - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING) && group.isRendezvous()) { - LOG.warning("No srdi handler registered :" + handlerName + " for Group ID:" + group.getPeerGroupID()); - } else if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("No srdi handler registered :" + handlerName + " for Group ID:" + group.getPeerGroupID()); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.unknownHandlerForSrdiMessage(srcAddr, handlerName); - } - } - } - - /** - * Send a resolver message to a peer - * - * @param destPeer destination peer - * @param route destination route advertisement - * @param pName service name on the destination - * @param pParam service param on the destination - * @param tagName tag name of the message element - * @param body the body of the message element - * @param gzip If true then encode the message body using gzip. - * @return {@code true} if successful - */ - private boolean sendMessage(String destPeer, RouteAdvertisement route, String pName, String pParam, String tagName, XMLDocument body, boolean gzip) { - // Get the messenger ready - ID dest; - try { - dest = IDFactory.fromURI(new URI(destPeer)); - } catch (URISyntaxException badpeer) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "bad destination peerid : " + destPeer, badpeer); - } - - return false; - } - - EndpointAddress destAddress = mkAddress(dest, pName, pParam); - - // FIXME add route to responses as well - Messenger messenger = null; - if (route == null) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("No route info available for " + destPeer); - } - } else { - // ok we have a route let's pass it to the router - if ((null == getRouteControl()) || (routeControl.addRoute(route) == RouteControl.FAILED)) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed to add route for " + route.getDestPeerID()); - } - } else { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Added route for " + route.getDestPeerID()); - } - } - } - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Creating a messenger immediate for :" + destAddress); - } - - messenger = endpoint.getMessengerImmediate(destAddress, route); - if (null == messenger) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Failed creating messenger for " + destAddress); - } - return false; - } - - Message msg = new Message(); - try { - MessageElement msgEl; - if (gzip) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gos = new GZIPOutputStream(baos); - - body.sendToStream(gos); - gos.finish(); - gos.close(); - byte gzipBytes[] = baos.toByteArray(); - - msgEl = new ByteArrayMessageElement(tagName, GZIP_MEDIA_TYPE, gzipBytes, null); - } else { - msgEl = new TextDocumentMessageElement(tagName, body, null); - } - msg.addMessageElement("jxta", msgEl); - } catch (Exception ez1) { - // Not much we can do - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed building message", ez1); - } - return false; - } - - // Send the message - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending " + msg + " to " + destAddress + " " + tagName); - } - - // XXX 20040924 bondolo Convert this to ListenerAdaptor - messenger.sendMessage(msg, null, null, new FailureListener(dest)); - - return true; - } - - private RouteControl getRouteControl() { - // Obtain the route control object to manipulate route information when sending and receiving resolver queries. - if (routeControl == null) { - // insignificant race condition here - MessageTransport endpointRouter = endpoint.getMessageTransport("jxta"); - if (endpointRouter != null) { - routeControl = (RouteControl) endpointRouter.transportControl(EndpointRouter.GET_ROUTE_CONTROL, null); - } else { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed to get RouteControl object. Resolver will not set route hints."); - } - } - } - return routeControl; - } - - /** - * Inner class to handle incoming queries - */ - private class DemuxQuery implements EndpointListener { - - /** - * {@inheritDoc} - */ - public void processIncomingMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Demuxing a query message from " + srcAddr); - } - - MessageElement element = message.getMessageElement("jxta", outQueName); - if (element == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Message does not contain a query. Discarding message"); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.invalidQueryDiscarded(srcAddr); - } - return; - } - - ResolverQueryMsg query; - try { - StructuredDocument asDoc = StructuredDocumentFactory.newStructuredDocument(element); - query = new ResolverQuery(asDoc); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Ill formatted resolver query, ignoring.", e); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.invalidQueryDiscarded(srcAddr); - } - return; - } catch (IllegalArgumentException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Ill formatted resolver query, ignoring.", e); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.invalidQueryDiscarded(srcAddr); - } - return; - } - - int res = processQuery(query, srcAddr); - if (ResolverService.Repropagate == res) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Repropagating query " + message + " from " + srcAddr); - } - repropagateQuery(message, query); - } - } - } - - /** - * Inner class to handle incoming responses - */ - private class DemuxResponse implements EndpointListener { - - /** - * @inheritDoc - */ - public void processIncomingMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Demuxing a response from " + srcAddr); - } - - MessageElement element = message.getMessageElement("jxta", inQueName); - if (null == element) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Message does not contain a response. Discarding message"); - } - - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.invalidResponseDiscarded(srcAddr); - } - return; - } - - ResolverResponse resolverResponse; - try { - StructuredDocument asDoc = StructuredDocumentFactory.newStructuredDocument(element); - resolverResponse = new ResolverResponse(asDoc); - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Ill formatted resolver response, ignoring.", e); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.invalidResponseDiscarded(srcAddr); - } - return; - } catch (IllegalArgumentException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Ill formatted resolver response, ignoring.", e); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.invalidResponseDiscarded(srcAddr); - } - return; - } - processResponse(resolverResponse, srcAddr); - } - } - - /** - * Inner class to handle SRDI messages - */ - private class DemuxSrdi implements EndpointListener { - - /** - * @inheritDoc - */ - public void processIncomingMessage(Message message, EndpointAddress srcAddr, EndpointAddress dstAddr) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Demuxing an SRDI message from : " + srcAddr); - } - - MessageElement element = message.getMessageElement("jxta", srdiQueName); - if (element == null) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Message does not contain a SRDI element. Discarding message"); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.invalidSrdiMessageDiscarded(srcAddr); - } - return; - } - - ResolverSrdiMsgImpl srdimsg; - try { - if (element.getMimeType().getBaseMimeMediaType().equals(GZIP_MEDIA_TYPE)) { - InputStream gzipStream = new GZIPInputStream(element.getStream()); - StructuredDocument asDoc = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, gzipStream); - srdimsg = new ResolverSrdiMsgImpl(asDoc, membership); - } else { - StructuredDocument asDoc = StructuredDocumentFactory.newStructuredDocument(element); - srdimsg = new ResolverSrdiMsgImpl(asDoc, membership); - } - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Ill formatted SRDI message, ignoring.", e); - } - if (ResolverMeterBuildSettings.RESOLVER_METERING && (resolverMeter != null)) { - resolverMeter.invalidSrdiMessageDiscarded(srcAddr); - } - return; - } - processSrdi(srdimsg, srcAddr); - } - } - - /** - * Listener to find bad destinations and clean srdi tables for them. - */ - class FailureListener implements OutgoingMessageEventListener { - final ID dest; - - FailureListener(ID dest) { - this.dest = dest; - } - - /** - * {@inheritDoc} - */ - public void messageSendFailed(OutgoingMessageEvent event) { - // Ignore the failure if it's a case of queue overflow. - if (event.getFailure() == null) { - return; - } - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Clearing SRDI tables for failed peer : " + dest); - } - - for (Object o : Arrays.asList(srdiHandlers.values().toArray())) { - SrdiHandler theHandler = (SrdiHandler) o; - try { - theHandler.messageSendFailed((PeerID) dest, event); - } catch (Throwable all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught Throwable from handler : " + theHandler, all); - } - } - } - } - - /** - * {@inheritDoc} - */ - public void messageSendSucceeded(OutgoingMessageEvent event) {// great! - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/ResolverServiceInterface.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/ResolverServiceInterface.java deleted file mode 100644 index c3e9bcb0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/ResolverServiceInterface.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver; - - -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.platform.Module; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.ResolverQueryMsg; -import net.jxta.protocol.ResolverResponseMsg; -import net.jxta.protocol.ResolverSrdiMsg; -import net.jxta.resolver.QueryHandler; -import net.jxta.resolver.ResolverService; -import net.jxta.resolver.SrdiHandler; -import net.jxta.service.Service; - - -/** - * Provides a controlled interface to the Resolver Service. - **/ -public class ResolverServiceInterface implements ResolverService { - - private final ResolverServiceImpl impl; - - /** - * Only authorized constructor - * @param theRealThing reference to the impl - */ - ResolverServiceInterface(ResolverServiceImpl theRealThing) { - impl = theRealThing; - } - - /** - * {@inheritDoc} - * - *

            Since THIS is already such an object, it returns itself. - * FIXME: it is kind of absurd to have this method part of the - * interface but we do not want to define two levels of Service interface - * just for that. - */ - public ResolverService getInterface() { - return this; - } - - /** - * {@inheritDoc} - * - *

            FIXME: This is meaningless for the interface object; - * it is there only to satisfy the requirements of the - * interface that we implement. Ultimately, the API should define - * two levels of interfaces: one for the real service implementation - * and one for the interface object. Right now it feels a bit heavy - * to so that since the only different between the two would be - * init() and may-be getName(). - */ - public void init(PeerGroup g, ID assignedID, Advertisement impl) {} - - /** - * {@inheritDoc} - * - *

            Does nothing in the interface object. - */ - public int startApp(String[] arg) { - return Module.START_OK; - } - - /** - * {@inheritDoc} - * - *

            Does nothing in the interface object. - */ - public void stopApp() {} - - /** - * {@inheritDoc} - */ - public ModuleImplAdvertisement getImplAdvertisement() { - return impl.getImplAdvertisement(); - } - - /** - * {@inheritDoc} - */ - public QueryHandler registerHandler(String name, QueryHandler handler) { - return impl.registerHandler(name, handler); - } - - /** - * {@inheritDoc} - */ - public QueryHandler unregisterHandler(String name) { - return impl.unregisterHandler(name); - } - - /** - * {@inheritDoc} - */ - public SrdiHandler registerSrdiHandler(String name, SrdiHandler handler) { - return impl.registerSrdiHandler(name, handler); - } - - /** - * {@inheritDoc} - */ - public SrdiHandler unregisterSrdiHandler(String name) { - return impl.unregisterSrdiHandler(name); - } - - /** - * {@inheritDoc} - */ - public void sendQuery(String rdvPeer, ResolverQueryMsg query) { - impl.sendQuery(rdvPeer, query); - } - - /** - * {@inheritDoc} - */ - public void sendResponse(String destPeer, ResolverResponseMsg response) { - impl.sendResponse(destPeer, response); - } - - /** - * {@inheritDoc} - */ - public void sendSrdi(String destPeer, ResolverSrdiMsg srdi) { - impl.sendSrdi(destPeer, srdi); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/package.html deleted file mode 100644 index 595f5713..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/package.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - A JXTA {@link net.jxta.resolver.ResolverService} implementation which - implements the standard JXTA Endpoint Resolver Protocol (ERP). - - @see net.jxta.resolver.ResolverService - @see JXTA Protocols Specification : Endpoint Resolver Protocol - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ConditionalResolverMeterBuildSettings.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ConditionalResolverMeterBuildSettings.java deleted file mode 100644 index c326f196..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ConditionalResolverMeterBuildSettings.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * The Sun Project JXTA(TM) Software License - * - * Copyright (c) 2001-2006 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: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at https://jxta.dev.java.net. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * https://jxta.dev.java.net/ - * - * This license is based on the BSD license adopted by the Apache Foundation. - * - */ - - -/* **** THIS IS A GENERATED FILE. DO NOT EDIT. **** */ - -package net.jxta.impl.resolver.resolverMeter; - -import java.util.ResourceBundle; -import net.jxta.impl.meter.*; - -public class ConditionalResolverMeterBuildSettings { - public static boolean isRuntimeMetering() { - boolean runtimeMetering = false; - - try { - ResourceBundle userResourceBundle = ResourceBundle.getBundle( "net.jxta.user" ); - String meteringProperty = "net.jxta.meter.conditionalResolverMetering"; - String meteringValue = userResourceBundle.getString( meteringProperty ); - runtimeMetering = "on".equalsIgnoreCase( meteringValue ); - } catch (Exception ignored) { - } - - return runtimeMetering; - } -} \ No newline at end of file diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryDestinationMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryDestinationMeter.java deleted file mode 100644 index 5b6cd6ac..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryDestinationMeter.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.peer.*; -import net.jxta.endpoint.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.util.*; -import java.util.*; - - -public class QueryDestinationMeter { - private PeerID peerID; - private QueryDestinationMetric cumulativeMetrics; - private QueryDestinationMetric deltaMetrics; - - public QueryDestinationMeter(PeerID peerID) { - cumulativeMetrics = new QueryDestinationMetric(peerID); - } - - public synchronized QueryDestinationMetric collectMetrics() { - QueryDestinationMetric prevDelta = deltaMetrics; - - deltaMetrics = null; - return prevDelta; - } - - public QueryDestinationMetric getCumulativeMetrics() { - return cumulativeMetrics; - } - - private void createDeltaMetric() { - deltaMetrics = new QueryDestinationMetric(peerID); - } - - protected void querySentViaUnicast() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.querySentViaUnicast(); - cumulativeMetrics.querySentViaUnicast(); - } - - protected void responseSentViaUnicast() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.responseSentViaUnicast(); - cumulativeMetrics.responseSentViaUnicast(); - } - - protected void responseProcessed() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.responseProcessed(); - cumulativeMetrics.responseProcessed(); - } - - protected void responseToUnregisteredHandler() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.responseToUnregisteredHandler(); - cumulativeMetrics.responseToUnregisteredHandler(); - } - - protected void errorWhileProcessingResponse() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.errorWhileProcessingResponse(); - cumulativeMetrics.errorWhileProcessingResponse(); - } - - protected void queryProcessed() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.queryProcessed(); - cumulativeMetrics.queryProcessed(); - } - - protected void queryToUnregisteredHandler() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.queryToUnregisteredHandler(); - cumulativeMetrics.queryToUnregisteredHandler(); - } - - protected void errorWhileProcessingQuery() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.errorWhileProcessingQuery(); - cumulativeMetrics.errorWhileProcessingQuery(); - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryDestinationMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryDestinationMetric.java deleted file mode 100644 index e50e03aa..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryDestinationMetric.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.peer.*; -import net.jxta.endpoint.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.util.*; -import net.jxta.impl.meter.*; - -import java.util.*; - - -/** - * Metrics for a specific Query Destination for a specific handler - **/ -public class QueryDestinationMetric implements DocumentSerializable { - private PeerID peerID; - private int errorWhileProcessingQuery; - private int queryProcessed; - private int errorWhileProcessingResponse; - private int responseProcessed; - private int responseSentViaUnicast; - private int querySentViaUnicast; - - private int queryToUnregisteredHandler; - private int responseToUnregisteredHandler; - - public QueryDestinationMetric(PeerID pid) { - this.peerID = pid; - } - - public QueryDestinationMetric(QueryDestinationMetric prototype) { - this.peerID = prototype.peerID; - } - - public QueryDestinationMetric() {} - - public PeerID getPeerID() { - return peerID; - } - - void querySentViaUnicast() { - querySentViaUnicast++; - } - - /** Get Queries Sent via Unicast to this destinations **/ - public int getQueriesSentViaUnicast() { - return querySentViaUnicast; - } - - void responseSentViaUnicast() { - responseSentViaUnicast++; - } - - /** Get Responses Sent via Unicast to this destinations **/ - public int getResponsesSentViaUnicast() { - return responseSentViaUnicast; - } - - void responseToUnregisteredHandler() { - responseToUnregisteredHandler++; - } - - /** Get Responses Recieved to this handler when not registered **/ - public int getResponseToUnregisteredHandler() { - return responseToUnregisteredHandler; - } - - void responseProcessed() { - responseProcessed++; - } - - /** Get Responses received and processed locally **/ - public int getResponsesProcessed() { - return responseProcessed; - } - - void errorWhileProcessingResponse() { - errorWhileProcessingResponse++; - } - - /** Get Responses received but failing when processed locally **/ - public int getErrorsWhileProcessingResponse() { - return errorWhileProcessingResponse; - } - - void queryProcessed() { - queryProcessed++; - } - - /** Get Queries received and processed locally **/ - public int getQueriesProcessed() { - return queryProcessed; - } - - void queryToUnregisteredHandler() { - queryToUnregisteredHandler++; - } - - /** Get Queries Recieved to this handler when not registered **/ - public int getQueryToUnregisteredHandler() { - return queryToUnregisteredHandler; - } - - void errorWhileProcessingQuery() { - errorWhileProcessingQuery++; - } - - /** Get Queries received but failing when processed locally **/ - public int getErrorsWhileProcessingQuery() { - return errorWhileProcessingQuery; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - if (peerID != null) { - DocumentSerializableUtilities.addString(element, "peerID", peerID.toString()); - } - if (errorWhileProcessingQuery != 0) { - DocumentSerializableUtilities.addInt(element, "errorWhileProcessingQuery", errorWhileProcessingQuery); - } - if (queryProcessed != 0) { - DocumentSerializableUtilities.addInt(element, "queryProcessed", queryProcessed); - } - if (errorWhileProcessingResponse != 0) { - DocumentSerializableUtilities.addInt(element, "errorWhileProcessingResponse", errorWhileProcessingResponse); - } - if (responseProcessed != 0) { - DocumentSerializableUtilities.addInt(element, "responseProcessed", responseProcessed); - } - if (responseSentViaUnicast != 0) { - DocumentSerializableUtilities.addInt(element, "responseSentViaUnicast", responseSentViaUnicast); - } - if (querySentViaUnicast != 0) { - DocumentSerializableUtilities.addInt(element, "querySentViaUnicast", querySentViaUnicast); - } - if (queryToUnregisteredHandler != 0) { - DocumentSerializableUtilities.addInt(element, "queryToUnregisteredHandler", queryToUnregisteredHandler); - } - if (responseToUnregisteredHandler != 0) { - DocumentSerializableUtilities.addInt(element, "responseToUnregisteredHandler", responseToUnregisteredHandler); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("peerID")) { - String peerIDText = DocumentSerializableUtilities.getString(childElement); - - peerID = MetricUtilities.getPeerIdFromString(peerIDText); - } else if (tagName.equals("errorWhileProcessingQuery")) { - errorWhileProcessingQuery = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("queryProcessed")) { - queryProcessed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("errorWhileProcessingResponse")) { - errorWhileProcessingResponse = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("responseProcessed")) { - responseProcessed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("responseSentViaUnicast")) { - responseSentViaUnicast = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("querySentViaUnicast")) { - querySentViaUnicast = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("queryToUnregisteredHandler")) { - queryToUnregisteredHandler = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("responseToUnregisteredHandler")) { - responseToUnregisteredHandler = DocumentSerializableUtilities.getInt(childElement); - } - } - } - - public void mergeMetrics(QueryDestinationMetric otherQueryDestinationMetric) { - this.errorWhileProcessingQuery += otherQueryDestinationMetric.errorWhileProcessingQuery; - this.queryProcessed += otherQueryDestinationMetric.queryProcessed; - this.errorWhileProcessingResponse += otherQueryDestinationMetric.errorWhileProcessingResponse; - this.responseProcessed += otherQueryDestinationMetric.responseProcessed; - this.responseSentViaUnicast += otherQueryDestinationMetric.responseSentViaUnicast; - this.querySentViaUnicast += otherQueryDestinationMetric.querySentViaUnicast; - this.queryToUnregisteredHandler += otherQueryDestinationMetric.queryToUnregisteredHandler; - this.responseToUnregisteredHandler += otherQueryDestinationMetric.responseToUnregisteredHandler; - } - - @Override - public int hashCode() { - return peerID.hashCode(); - } - - @Override - public boolean equals(Object other) { - if (other instanceof QueryDestinationMetric) { - QueryDestinationMetric otherQueryDestinationMetric = (QueryDestinationMetric) other; - - return peerID.equals(otherQueryDestinationMetric.peerID); - } else { - return false; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryHandlerMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryHandlerMeter.java deleted file mode 100644 index f08337c7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryHandlerMeter.java +++ /dev/null @@ -1,522 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.peer.*; -import net.jxta.peergroup.*; -import net.jxta.resolver.*; -import net.jxta.impl.resolver.*; -import net.jxta.impl.meter.*; -import net.jxta.protocol.*; -import net.jxta.meter.*; -import net.jxta.util.*; - -import net.jxta.endpoint.*; -import net.jxta.exception.*; - -import java.net.*; -import java.util.*; - - -public class QueryHandlerMeter { - private static final int QUERY_CULLING_INTERVAL = 5 * 60 * 1000; // Fix-Me: Five minutes hardcoded for now... - - private ResolverServiceMonitor resolverServiceMonitor; - private String handlerName; - - private QueryHandlerMetric cumulativeMetrics; - private QueryHandlerMetric deltaMetrics; - - private Hashtable queryDestinationMeters = new Hashtable(); - - private Hashtable queryMetricsTable = null; - - private class QueryMetricsTable extends Hashtable { - - void deReference() { - queryMetricsTable = null; - } - - @Override - public String toString() { - return handlerName; - } - } - - - private class QueryMetric { - int queryId; - long querySentTime = System.currentTimeMillis(); - int numResponsesReceived = 0; - long lastResponseTime = 0; - - QueryMetric(int queryId) { - this.queryId = queryId; - } - } - - private static LinkedList queryMetricsTables = new LinkedList(); - - static { - Thread cullQueries = new Thread(new Runnable() { - public void run() { - for (;;) { - try { - Thread.sleep(QUERY_CULLING_INTERVAL); - } catch (Exception e) {} - - long dormantTime = System.currentTimeMillis() - QUERY_CULLING_INTERVAL; - - synchronized (queryMetricsTables) { - LinkedList keysToRemove = new LinkedList(); - - for (Iterator i = queryMetricsTables.iterator(); i.hasNext();) { - QueryMetricsTable queryMetricsTable = (QueryMetricsTable) i.next(); - - keysToRemove.clear(); - - synchronized (queryMetricsTable) { - for (Enumeration e = queryMetricsTable.keys(); e.hasMoreElements();) { - Integer key = (Integer) e.nextElement(); - QueryMetric queryMetric = (QueryMetric) queryMetricsTable.get(key); - - if (queryMetric.lastResponseTime < dormantTime) { - keysToRemove.add(key); - } - } - - for (Iterator k = keysToRemove.iterator(); k.hasNext();) { - Integer key = (Integer) k.next(); - - queryMetricsTable.deReference(); - queryMetricsTable.remove(key); - } - - if (queryMetricsTable.size() == 0) { - i.remove(); - } - } - } - } - } - } - }, "Resolver Query Metrics Culling Thread"); - - cullQueries.setDaemon(true); - cullQueries.start(); - } - - public QueryHandlerMeter(String handlerName, ResolverServiceMonitor resolverServiceMonitor) { - this.handlerName = handlerName; - cumulativeMetrics = new QueryHandlerMetric(handlerName); - this.resolverServiceMonitor = resolverServiceMonitor; - } - - public QueryHandlerMetric getCumulativeMetrics() { - return cumulativeMetrics; - } - - public String getHandlerName() { - return handlerName; - } - - public synchronized QueryHandlerMetric collectMetrics() { - QueryHandlerMetric prevDelta = deltaMetrics; - - for (Enumeration e = queryDestinationMeters.elements(); e.hasMoreElements();) { - QueryDestinationMeter queryDestinationMeter = (QueryDestinationMeter) e.nextElement(); - - QueryDestinationMetric queryDestinationMetric = queryDestinationMeter.collectMetrics(); - - if (queryDestinationMetric != null) { - - /* Fix-me: while fixing an exception thrown by SrdiHandlerMeter, I noticed that - a similar problem might occur here if there can be a case where a destinationMtric - is available even though nothing has happened to create the delta. - If that is not possible (we need to do a code review!) remove the check for - a null delta here. - */ - if (prevDelta == null) { - createDeltaMetric(); - prevDelta = deltaMetrics; - } - prevDelta.addQueryDestinationMetric(queryDestinationMetric); - } - } - deltaMetrics = null; - return prevDelta; - } - - public synchronized QueryDestinationMeter getQueryDestinationMeter(EndpointAddress endpointAddress) { - PeerID peerID = MetricUtilities.getPeerIdFromEndpointAddress(endpointAddress); - - return getQueryDestinationMeter(peerID); - } - - public synchronized QueryDestinationMeter getQueryDestinationMeter(String peerIdString) { - PeerID peerID = MetricUtilities.getPeerIdFromString(peerIdString); - - return getQueryDestinationMeter(peerID); - } - - public synchronized QueryDestinationMeter getQueryDestinationMeter(PeerID peerID) { - QueryDestinationMeter queryDestinationMeter = (QueryDestinationMeter) queryDestinationMeters.get(peerID); - - if (queryDestinationMeter == null) { - queryDestinationMeter = new QueryDestinationMeter(peerID); - - queryDestinationMeters.put(peerID, queryDestinationMeter); - cumulativeMetrics.addQueryDestinationMetric(queryDestinationMeter.getCumulativeMetrics()); - } - - return queryDestinationMeter; - } - - private void createDeltaMetric() { - deltaMetrics = new QueryHandlerMetric(handlerName); - } - - @Override - public String toString() { - return "ResolverHandlerMeter(" + handlerName + ")"; - } - - public void setRegistered(boolean registered) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.setRegistered(registered); - cumulativeMetrics.setRegistered(registered); - } - - private QueryMetric getQueryMetric(int queryId) { - Integer key = new Integer(queryId); - - synchronized (queryMetricsTables) { - if (queryMetricsTable == null) { - queryMetricsTable = new QueryMetricsTable(); - - queryMetricsTables.add(queryMetricsTable); - } - - QueryMetric queryMetric = (QueryMetric) queryMetricsTable.get(key); - - if (queryMetric == null) { - queryMetric = new QueryMetric(queryId); - - queryMetricsTable.put(key, queryMetric); - } - - return queryMetric; - } - } - - // Sent Queries - - - public void querySentInGroup(ResolverQueryMsg query) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - getQueryMetric(query.getQueryId()); // register the query - - deltaMetrics.querySentInGroup(); - cumulativeMetrics.querySentInGroup(); - } - - public void querySentViaWalker(ResolverQueryMsg query) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - getQueryMetric(query.getQueryId()); // register the query - - deltaMetrics.querySentViaWalker(); - cumulativeMetrics.querySentViaWalker(); - } - - public void querySentViaUnicast(String peer, ResolverQueryMsg query) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - getQueryMetric(query.getQueryId()); // register the query - - deltaMetrics.querySentViaUnicast(peer); - cumulativeMetrics.querySentViaUnicast(peer); - - QueryDestinationMeter destinationMeter = getQueryDestinationMeter(peer); - - destinationMeter.querySentViaUnicast(); - } - - public void querySendError() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.querySendError(); - cumulativeMetrics.querySendError(); - } - - public void queryPropagateError() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.queryPropagateError(); - cumulativeMetrics.queryPropagateError(); - } - - public void queryHopCountDropped() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.queryHopCountDropped(); - cumulativeMetrics.queryHopCountDropped(); - } - - public void unableToPropagate() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.unableToPropagate(); - cumulativeMetrics.unableToPropagate(); - } - - // Propagate Query - - public void queryPropagatedInGroup() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.queryPropagatedInGroup(); - cumulativeMetrics.queryPropagatedInGroup(); - } - - public void queryPropagatedViaWalker() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.queryPropagatedViaWalker(); - cumulativeMetrics.queryPropagatedViaWalker(); - } - - public void propagationQueryDropped() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.propagationQueryDropped(); - cumulativeMetrics.propagationQueryDropped(); - } - - // Sent Responses - - public void responseSentViaUnicast(String peer, ResolverResponseMsg response) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.responseSentViaUnicast(); - cumulativeMetrics.responseSentViaUnicast(); - - QueryDestinationMeter destinationMeter = getQueryDestinationMeter(peer); - - destinationMeter.responseSentViaUnicast(); - } - - public void responseSentViaWalker(ResolverResponseMsg response) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.responseSentViaWalker(); - cumulativeMetrics.responseSentViaWalker(); - } - - public void responseSentInGroup(ResolverResponseMsg response) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.responseSentInGroup(); - cumulativeMetrics.responseSentInGroup(); - } - - public void responseSendError() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.responseSendError(); - cumulativeMetrics.responseSendError(); - } - - public void responsePropagateError() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.responsePropagateError(); - cumulativeMetrics.responsePropagateError(); - } - - // Received Responses - - public void responseProcessed(ResolverResponseMsg response, long processTime, EndpointAddress srcAddr) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - QueryMetric queryMetric = getQueryMetric(response.getQueryId()); - long now = System.currentTimeMillis(); - long responseTime = now - queryMetric.querySentTime; - - queryMetric.lastResponseTime = now; - queryMetric.numResponsesReceived++; - - deltaMetrics.responseProcessed(responseTime, processTime); - cumulativeMetrics.responseProcessed(responseTime, processTime); - - QueryDestinationMeter destinationMeter = getQueryDestinationMeter(srcAddr); - - destinationMeter.responseProcessed(); - } - - public void responseToUnregisteredHandler(EndpointAddress src) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.responseToUnregisteredHandler(); - cumulativeMetrics.responseToUnregisteredHandler(); - - QueryDestinationMeter destinationMeter = getQueryDestinationMeter(src); - - destinationMeter.responseToUnregisteredHandler(); - } - - public void errorWhileProcessingResponse(EndpointAddress srcAddr) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.errorWhileProcessingResponse(); - cumulativeMetrics.errorWhileProcessingResponse(); - - QueryDestinationMeter destinationMeter = getQueryDestinationMeter(srcAddr); - - destinationMeter.errorWhileProcessingResponse(); - } - - // Received Queries - - public void queryProcessed(ResolverQueryMsg query, int result, long processTime) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.queryProcessed(result, processTime); - cumulativeMetrics.queryProcessed(result, processTime); - - QueryDestinationMeter destinationMeter = getQueryDestinationMeter(query.getSrc()); - - destinationMeter.queryProcessed(); - } - - public void queryToUnregisteredHandler(ResolverQueryMsg query) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.queryToUnregisteredHandler(); - cumulativeMetrics.queryToUnregisteredHandler(); - - QueryDestinationMeter destinationMeter = getQueryDestinationMeter(query.getSrc()); - - destinationMeter.queryToUnregisteredHandler(); - } - - public void errorWhileProcessingQuery(ResolverQueryMsg query) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.errorWhileProcessingQuery(); - cumulativeMetrics.errorWhileProcessingQuery(); - - QueryDestinationMeter destinationMeter = getQueryDestinationMeter(query.getSrc()); - - destinationMeter.errorWhileProcessingQuery(); - } - - public Enumeration getQueryDestinationMeters() { - return queryDestinationMeters.elements(); - } - - public int getQueryDestinationCount() { - return queryDestinationMeters.size(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryHandlerMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryHandlerMetric.java deleted file mode 100644 index e9eac4bf..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/QueryHandlerMetric.java +++ /dev/null @@ -1,582 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.resolver.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.endpoint.*; -import net.jxta.exception.*; -import net.jxta.peer.*; -import net.jxta.util.*; -import java.util.*; - - -/** - * Metrics for a Registered handler Name - **/ -public class QueryHandlerMetric implements DocumentSerializable { - public static final String REGISTERED = "registered"; - public static final String UNREGISTERED = "unregistered"; - - private String handlerName; - private String registered; - - private int numResponses = 0; - private long responseProcessingTime = 0; - private long responseTime = 0; - private int numResponseErrors = 0; - - private int numQueries = 0; - private int numQueriesRepropagated = 0; - private long queryProcessingTime = 0; - private int numQueryErrors = 0; - - private int numQueriesSentInGroup = 0; - private int numQueriesSentViaWalker = 0; - private int numQueriesSentViaUnicast = 0; - private int numErrorsSendingQueries = 0; - private int numErrorsPropagatingQueries = 0; - private int numQueriesHopCountDropped = 0; - - private int numPropagationQueriesDropped = 0; - private int numPropagatedInGroup = 0; - private int numPropagatedViaWalker = 0; - private int numUnableToPropagate = 0; - - private int numResponsesToUnregisteredHandler = 0; - private int numQueriesToUnregisteredHandler = 0; - - private int numResponsesSentInGroup = 0; - private int numResponsesSentViaWalker = 0; - private int numResponsesSentViaUnicast = 0; - private int numErrorsSendingResponses = 0; - private int numErrorsPropagatingResponses = 0; - - private HashMap destinationMetrics = new HashMap(); - - public QueryHandlerMetric(String handlerName) { - this.handlerName = handlerName; - } - - public QueryHandlerMetric() {} - - public QueryHandlerMetric(QueryHandlerMetric prototype) { - this.handlerName = prototype.handlerName; - } - - void responseProcessed(long responseTime, long processingTime) { - numResponses++; - responseTime += responseTime; - responseProcessingTime += processingTime; - } - - void responseToUnregisteredHandler() { - numResponsesToUnregisteredHandler++; - } - - void errorWhileProcessingResponse() { - numResponseErrors++; - } - - void queryProcessed(int result, long processingTime) { - numQueries++; - - if (result == ResolverService.Repropagate) { - numQueriesRepropagated++; - } - - queryProcessingTime += processingTime; - } - - void queryToUnregisteredHandler() { - numQueriesToUnregisteredHandler++; - } - - void errorWhileProcessingQuery() { - numQueryErrors++; - } - - void querySentInGroup() { - numQueriesSentInGroup++; - } - - void querySentViaWalker() { - numQueriesSentViaWalker++; - } - - void querySentViaUnicast(String peer) { - numQueriesSentViaUnicast++; - } - - void querySendError() { - numErrorsSendingQueries++; - } - - void queryPropagateError() { - numErrorsPropagatingQueries++; - } - - void queryHopCountDropped() { - numQueriesHopCountDropped++; - } - - void responseSentInGroup() { - numResponsesSentInGroup++; - } - - void responseSentViaWalker() { - numResponsesSentViaWalker++; - } - - void responseSentViaUnicast() { - numResponsesSentViaUnicast++; - } - - void responseSendError() { - numErrorsSendingResponses++; - } - - void responsePropagateError() { - numErrorsPropagatingResponses++; - } - - void propagationQueryDropped() { - numPropagationQueriesDropped++; - } - - void queryPropagatedInGroup() { - numPropagatedInGroup++; - } - - void queryPropagatedViaWalker() { - numPropagatedViaWalker++; - } - - void unableToPropagate() { - numUnableToPropagate++; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof QueryHandlerMetric) { - QueryHandlerMetric otherQueryHandlerMetric = (QueryHandlerMetric) obj; - - return handlerName.equals((otherQueryHandlerMetric.handlerName)); - } else { - return false; - } - } - - @Override - public int hashCode() { - return handlerName.hashCode(); - } - - void setRegistered(boolean isRegistered) { - this.registered = isRegistered ? REGISTERED : UNREGISTERED; - } - - /** Get Handler Name for this Metric **/ - public String getHandlerName() { - return handlerName; - } - - /** Get State of Handler currently - * @return REGISTERED or UNREGISTERED - **/ - public String getRegistered() { - return (registered != null) ? registered : UNREGISTERED; - } - - /** The number of responses received by this Handler **/ - public int getNumResponses() { - return numResponses; - } - - /** The total clock time to process all responses received by this Handler **/ - public long getResponseProcessingTime() { - return responseProcessingTime; - } - - /** The average clock time to process responses received by this Handler **/ - public long getAverageResponseProcessingTime() { - return (numResponses == 0) ? 0 : (responseProcessingTime / numResponses); - } - - /** The total time to receive all responses to queries sent by this Handler **/ - public long getResponseTime() { - return responseTime; - } - - /** The average time to receive responses to queries sent by this Handler **/ - public long getAverageResponseTime() { - return (numResponses == 0) ? 0 : (responseTime / numResponses); - } - - /** Number of local errors while processing received responses **/ - public int getNumResponseErrors() { - return numResponseErrors; - } - - /** The number of queries received by this Handler **/ - public int getNumQueries() { - return numQueries; - } - - /** The number of queries received and repropagated by this Handler **/ - public int getNumQueriesRepropagated() { - return numQueriesRepropagated; - } - - /** The total clock time to process all Queries received by this Handler **/ - public long getQueryProcessingTime() { - return queryProcessingTime; - } - - /** The average clock time to process Queries received by this Handler **/ - public long getAverageQueryProcessingTime() { - return (numQueries == 0) ? 0 : (queryProcessingTime / numQueries); - } - - /** Number of local errors while processing received Queries **/ - public int getNumQueryErrors() { - return numQueryErrors; - } - - /** Number of Queries sent in Group ***/ - public int getNumQueriesSentInGroup() { - return numQueriesSentInGroup; - } - - /** Number of Queries sent via Walker ***/ - public int getNumQueriesSentViaWalker() { - return numQueriesSentViaWalker; - } - - /** Number of Queries sent via Unicast ***/ - public int getNumQueriesSentViaUnicast() { - return numQueriesSentViaUnicast; - } - - /** Number of Errors while sending Queries ***/ - public int getNumErrorsSendingQueries() { - return numErrorsSendingQueries; - } - - /** Number of Errors while propagating Queries ***/ - public int getNumErrorsPropagatingQueries() { - return numErrorsPropagatingQueries; - } - - /** Number of Responses sent in Group ***/ - public int getNumResponsesSentInGroup() { - return numResponsesSentInGroup; - } - - /** Number of Responses sent via Walker ***/ - public int getNumResponsesSentViaWalker() { - return numResponsesSentViaWalker; - } - - /** Number of Responses sent via Unicast ***/ - public int getNumResponsesSentViaUnicast() { - return numResponsesSentViaUnicast; - } - - /** Number of Errors while sending Responses ***/ - public int getNumErrorsSendingResponses() { - return numErrorsSendingResponses; - } - - /** Number of Errors while propagating Responses ***/ - public int getNumErrorsPropagatingResponses() { - return numErrorsPropagatingResponses; - } - - public int getNumQueriesSent() { - return (numQueriesSentInGroup + numQueriesSentViaWalker + numQueriesSentViaUnicast); - } - - public int getNumQuerySendErrors() { - return (numErrorsSendingQueries + numErrorsPropagatingQueries); - } - - public int getNumResponsesSent() { - return (numResponsesSentInGroup + numResponsesSentViaWalker + numResponsesSentViaUnicast); - } - - public int getNumResponseSendErrors() { - return (numErrorsSendingResponses + numErrorsPropagatingResponses); - } - - public void addQueryDestinationMetric(QueryDestinationMetric queryDestinationMetric) { - destinationMetrics.put(queryDestinationMetric.getPeerID(), queryDestinationMetric); - } - - public QueryDestinationMetric getQueryDestinationMetric(PeerID peerID) { - QueryDestinationMetric destinationMetric = (QueryDestinationMetric) destinationMetrics.get(peerID); - - if (destinationMetric == null) { - destinationMetric = new QueryDestinationMetric(peerID); - destinationMetrics.put(peerID, destinationMetric); - } - return destinationMetric; - } - - public Iterator getDestinationMetrics() { - - return destinationMetrics.values().iterator(); - } - - public void serializeTo(Element element) throws DocumentSerializationException { - if (handlerName != null) { - DocumentSerializableUtilities.addString(element, "handlerName", handlerName); - } - if (registered != null) { - DocumentSerializableUtilities.addString(element, "registered", registered); - } - if (numResponses != 0) { - DocumentSerializableUtilities.addInt(element, "numResponses", numResponses); - } - if (responseProcessingTime != 0) { - DocumentSerializableUtilities.addLong(element, "responseProcessingTime", responseProcessingTime); - } - if (responseTime != 0) { - DocumentSerializableUtilities.addLong(element, "responseTime", responseTime); - } - if (numResponseErrors != 0) { - DocumentSerializableUtilities.addInt(element, "numResponseErrors", numResponseErrors); - } - if (numQueries != 0) { - DocumentSerializableUtilities.addInt(element, "numQueries", numQueries); - } - if (numQueriesRepropagated != 0) { - DocumentSerializableUtilities.addInt(element, "numQueriesRepropagated", numQueriesRepropagated); - } - if (queryProcessingTime != 0) { - DocumentSerializableUtilities.addLong(element, "queryProcessingTime", queryProcessingTime); - } - if (numQueryErrors != 0) { - DocumentSerializableUtilities.addInt(element, "numQueryErrors", numQueryErrors); - } - if (numQueriesSentInGroup != 0) { - DocumentSerializableUtilities.addInt(element, "numQueriesSentInGroup", numQueriesSentInGroup); - } - if (numQueriesSentViaWalker != 0) { - DocumentSerializableUtilities.addInt(element, "numQueriesSentViaWalker", numQueriesSentViaWalker); - } - if (numQueriesSentViaUnicast != 0) { - DocumentSerializableUtilities.addInt(element, "numQueriesSentViaUnicast", numQueriesSentViaUnicast); - } - if (numErrorsSendingQueries != 0) { - DocumentSerializableUtilities.addInt(element, "numErrorsSendingQueries", numErrorsSendingQueries); - } - if (numErrorsPropagatingQueries != 0) { - DocumentSerializableUtilities.addInt(element, "numErrorsPropagatingQueries", numErrorsPropagatingQueries); - } - if (numQueriesHopCountDropped != 0) { - DocumentSerializableUtilities.addInt(element, "numQueriesHopCountDropped", numQueriesHopCountDropped); - } - if (numPropagationQueriesDropped != 0) { - DocumentSerializableUtilities.addInt(element, "numPropagationQueriesDropped", numPropagationQueriesDropped); - } - if (numPropagatedInGroup != 0) { - DocumentSerializableUtilities.addInt(element, "numPropagatedInGroup", numPropagatedInGroup); - } - if (numPropagatedViaWalker != 0) { - DocumentSerializableUtilities.addInt(element, "numPropagatedViaWalker", numPropagatedViaWalker); - } - if (numUnableToPropagate != 0) { - DocumentSerializableUtilities.addInt(element, "numUnableToPropagate", numUnableToPropagate); - } - if (numResponsesToUnregisteredHandler != 0) { - DocumentSerializableUtilities.addInt(element, "numResponsesToUnregisteredHandler", numResponsesToUnregisteredHandler); - } - if (numQueriesToUnregisteredHandler != 0) { - DocumentSerializableUtilities.addInt(element, "numQueriesToUnregisteredHandler", numQueriesToUnregisteredHandler); - } - if (numResponsesSentInGroup != 0) { - DocumentSerializableUtilities.addInt(element, "numResponsesSentInGroup", numResponsesSentInGroup); - } - if (numResponsesSentViaWalker != 0) { - DocumentSerializableUtilities.addInt(element, "numResponsesSentViaWalker", numResponsesSentViaWalker); - } - if (numResponsesSentViaUnicast != 0) { - DocumentSerializableUtilities.addInt(element, "numResponsesSentViaUnicast", numResponsesSentViaUnicast); - } - if (numErrorsSendingResponses != 0) { - DocumentSerializableUtilities.addInt(element, "numErrorsSendingResponses", numErrorsSendingResponses); - } - if (numErrorsPropagatingResponses != 0) { - DocumentSerializableUtilities.addInt(element, "numErrorsPropagatingResponses", numErrorsPropagatingResponses); - } - - for (Iterator i = destinationMetrics.values().iterator(); i.hasNext();) { - Element queryDestinationElement = DocumentSerializableUtilities.createChildElement(element, "destination"); - QueryDestinationMetric queryDestinationMetric = (QueryDestinationMetric) i.next(); - - queryDestinationMetric.serializeTo(queryDestinationElement); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("handlerName")) { - handlerName = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("registered")) { - registered = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("numResponses")) { - numResponses = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("responseProcessingTime")) { - responseProcessingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("responseTime")) { - responseTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numResponseErrors")) { - numResponseErrors = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numQueries")) { - numQueries = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numQueriesRepropagated")) { - numQueriesRepropagated = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("queryProcessingTime")) { - queryProcessingTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numQueryErrors")) { - numQueryErrors = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numQueriesSentInGroup")) { - numQueriesSentInGroup = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numQueriesSentViaWalker")) { - numQueriesSentViaWalker = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numQueriesSentViaUnicast")) { - numQueriesSentViaUnicast = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numErrorsSendingQueries")) { - numErrorsSendingQueries = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numErrorsPropagatingQueries")) { - numErrorsPropagatingQueries = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numQueriesHopCountDropped")) { - numQueriesHopCountDropped = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPropagationQueriesDropped")) { - numPropagationQueriesDropped = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPropagatedInGroup")) { - numPropagatedInGroup = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numPropagatedViaWalker")) { - numPropagatedViaWalker = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numUnableToPropagate")) { - numUnableToPropagate = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numResponsesToUnregisteredHandler")) { - numResponsesToUnregisteredHandler = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numQueriesToUnregisteredHandler")) { - numQueriesToUnregisteredHandler = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numResponsesSentInGroup")) { - numResponsesSentInGroup = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numResponsesSentViaWalker")) { - numResponsesSentViaWalker = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numResponsesSentViaUnicast")) { - numResponsesSentViaUnicast = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numErrorsSendingResponses")) { - numErrorsSendingResponses = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numErrorsPropagatingResponses")) { - numErrorsPropagatingResponses = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("destination")) { - QueryDestinationMetric queryDestinationMetric = new QueryDestinationMetric(); - - queryDestinationMetric.initializeFrom(childElement); - addQueryDestinationMetric(queryDestinationMetric); - } - } - } - - public void mergeMetrics(QueryHandlerMetric otherQueryHandlerMetric) { - this.numResponses += otherQueryHandlerMetric.numResponses; - this.responseProcessingTime += otherQueryHandlerMetric.responseProcessingTime; - this.responseTime += otherQueryHandlerMetric.responseTime; - this.numResponseErrors += otherQueryHandlerMetric.numResponseErrors; - - this.numQueries += otherQueryHandlerMetric.numQueries; - this.numQueriesRepropagated += otherQueryHandlerMetric.numQueriesRepropagated; - this.queryProcessingTime += otherQueryHandlerMetric.queryProcessingTime; - this.numQueryErrors += otherQueryHandlerMetric.numQueryErrors; - - this.numQueriesSentInGroup += otherQueryHandlerMetric.numQueriesSentInGroup; - this.numQueriesSentViaWalker += otherQueryHandlerMetric.numQueriesSentViaWalker; - this.numQueriesSentViaUnicast += otherQueryHandlerMetric.numQueriesSentViaUnicast; - this.numErrorsSendingQueries += otherQueryHandlerMetric.numErrorsSendingQueries; - this.numErrorsPropagatingQueries += otherQueryHandlerMetric.numErrorsPropagatingQueries; - this.numQueriesHopCountDropped += otherQueryHandlerMetric.numQueriesHopCountDropped; - - this.numResponsesSentInGroup += otherQueryHandlerMetric.numResponsesSentInGroup; - this.numResponsesSentViaWalker += otherQueryHandlerMetric.numResponsesSentViaWalker; - this.numResponsesSentViaUnicast += otherQueryHandlerMetric.numResponsesSentViaUnicast; - this.numErrorsSendingResponses += otherQueryHandlerMetric.numErrorsSendingResponses; - this.numErrorsPropagatingResponses += otherQueryHandlerMetric.numErrorsPropagatingResponses; - - for (Iterator i = otherQueryHandlerMetric.getDestinationMetrics(); i.hasNext();) { - QueryDestinationMetric otherQueryDestinationMetric = (QueryDestinationMetric) i.next(); - QueryDestinationMetric ourQueryDestinationMetric = getQueryDestinationMetric(otherQueryDestinationMetric.getPeerID()); - - if (ourQueryDestinationMetric == null) { - ourQueryDestinationMetric = new QueryDestinationMetric(otherQueryDestinationMetric); - addQueryDestinationMetric(ourQueryDestinationMetric); - } - - ourQueryDestinationMetric.mergeMetrics(otherQueryDestinationMetric); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverMeter.java deleted file mode 100644 index a5288552..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverMeter.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.peer.*; -import net.jxta.peergroup.*; -import net.jxta.resolver.*; -import net.jxta.impl.resolver.*; -import net.jxta.protocol.*; -import net.jxta.endpoint.*; - -import java.net.*; -import java.util.*; - - -public class ResolverMeter { - private ResolverServiceMonitor resolverServiceMonitor; - private ResolverMetric cumulativeMetrics; - private ResolverMetric deltaMetrics; - - public ResolverMeter(ResolverServiceMonitor resolverServiceMonitor) { - this.resolverServiceMonitor = resolverServiceMonitor; - cumulativeMetrics = new ResolverMetric(); - } - - public ResolverMetric getCumulativeMetrics() { - return cumulativeMetrics; - } - - public synchronized ResolverMetric collectMetrics() { - ResolverMetric prevDelta = deltaMetrics; - - deltaMetrics = null; - return prevDelta; - } - - private void createDeltaMetric() { - deltaMetrics = new ResolverMetric(); - } - - @Override - public String toString() { - return "ResolverMeter"; - } - - public void invalidSrdiMessageDiscarded(EndpointAddress src) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.invalidSrdiMessageDiscarded(); - cumulativeMetrics.invalidSrdiMessageDiscarded(); - } - - public void unknownHandlerForSrdiMessage(EndpointAddress src, String handlerName) { - if (handlerName != null) { - SrdiHandlerMeter srdiHandlerMeter = resolverServiceMonitor.getSrdiHandlerMeter(handlerName); - - srdiHandlerMeter.srdiToUnregisteredHandler(src); - } else { - invalidSrdiDiscarded(); - } - } - - public void invalidSrdiDiscarded() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.invalidResponseDiscarded(); - cumulativeMetrics.invalidResponseDiscarded(); - } - - public void invalidResponseDiscarded(EndpointAddress src) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.invalidResponseDiscarded(); - cumulativeMetrics.invalidResponseDiscarded(); - } - - public void unknownHandlerForResponse(EndpointAddress src, ResolverResponseMsg resp) { - String handlerName = resp.getHandlerName(); - - if (handlerName != null) { - QueryHandlerMeter queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(handlerName); - - queryHandlerMeter.responseToUnregisteredHandler(src); - } else { - invalidResponseDiscarded(src); - } - } - - public void invalidQueryDiscarded(EndpointAddress src) { - invalidQueryDiscarded(); // We aren't tracking on source at this point (or ever?) - } - - public void invalidQueryDiscarded() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.invalidQueryDiscarded(); - cumulativeMetrics.invalidQueryDiscarded(); - } - - public void unknownHandlerForQuery(ResolverQueryMsg query) { - String handlerName = query.getHandlerName(); - - if (handlerName != null) { - QueryHandlerMeter queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(handlerName); - - queryHandlerMeter.queryToUnregisteredHandler(query); - } else { - invalidQueryDiscarded(); - } - } - - public void queryPropagatedInGroup(ResolverQueryMsg query) { - String handlerName = query.getHandlerName(); - - if (handlerName != null) { - QueryHandlerMeter queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(handlerName); - - queryHandlerMeter.queryPropagatedInGroup(); - } else { - invalidQueryDiscarded(); - } - } - - public void queryPropagatedViaWalker(ResolverQueryMsg query) { - String handlerName = query.getHandlerName(); - - if (handlerName != null) { - QueryHandlerMeter queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(handlerName); - - queryHandlerMeter.queryPropagatedViaWalker(); - } else { - invalidQueryDiscarded(); - } - } - - public void propagationQueryDropped(ResolverQueryMsg query) { - String handlerName = query.getHandlerName(); - - if (handlerName != null) { - QueryHandlerMeter queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(handlerName); - - queryHandlerMeter.propagationQueryDropped(); - } else { - invalidQueryDiscarded(); - } - } - - public void queryPropagationError(ResolverQueryMsg query) { - String handlerName = query.getHandlerName(); - - if (handlerName != null) { - QueryHandlerMeter queryHandlerMeter = resolverServiceMonitor.getQueryHandlerMeter(handlerName); - - queryHandlerMeter.unableToPropagate(); - } else { - invalidQueryDiscarded(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverMeterBuildSettings.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverMeterBuildSettings.java deleted file mode 100644 index a6d7b125..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverMeterBuildSettings.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * The Sun Project JXTA(TM) Software License - * - * Copyright (c) 2001-2006 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: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at https://jxta.dev.java.net. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * https://jxta.dev.java.net/ - * - * This license is based on the BSD license adopted by the Apache Foundation. - * - */ - - -/* **** THIS IS A GENERATED FILE. DO NOT EDIT. **** */ - -package net.jxta.impl.resolver.resolverMeter; - -import net.jxta.impl.meter.*; - -public interface ResolverMeterBuildSettings extends MeterBuildSettings { - public static final boolean RESOLVER_METERING = ConditionalResolverMeterBuildSettings.isRuntimeMetering(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverMetric.java deleted file mode 100644 index ae75b1de..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverMetric.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.resolver.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; - -import java.util.*; - - -/** - * The general Metric for this resolver - **/ -public class ResolverMetric implements DocumentSerializable { - private int numInvalidSrdiMessages = 0; - private int numSrdiMessagesToUnknownHandler = 0; - - private int numInvalidResponses = 0; - private int numResponsesToUnknownHandler = 0; - - private int numInvalidQueries = 0; - private int numQueriesToUnknownHandler = 0; - - public ResolverMetric() {} - - public ResolverMetric(ResolverMetric prototype) {} - - /** Number of invalid Srdi Messages received */ - public int getNumInvalidSrdiMessages() { - return numInvalidSrdiMessages; - } - - /** Number of Srdi Messages received for unknown handlers */ - public int getNumSrdiMessagesToUnknownHandler() { - return numSrdiMessagesToUnknownHandler; - } - - /** Number of invalid Query Response Messages received */ - public int getNumInvalidResponses() { - return numInvalidResponses; - } - - /** Number of Response Messages to unknown handlers received */ - public int getNumResponsesToUnknownHandler() { - return numResponsesToUnknownHandler; - } - - /** Number of invalid Query Messages received */ - public int getNumInvalidQueries() { - return numInvalidQueries; - } - - /** Number of Query Messages to unknown handlers received */ - public int getNumQueriesToUnknownHandler() { - return numQueriesToUnknownHandler; - } - - void invalidSrdiMessageDiscarded() { - numInvalidSrdiMessages++; - } - - void unknownHandlerForSrdiMessage() { - numSrdiMessagesToUnknownHandler++; - } - - void invalidResponseDiscarded() { - numInvalidResponses++; - } - - void unknownHandlerForResponse() { - numResponsesToUnknownHandler++; - } - - void invalidQueryDiscarded() { - numInvalidQueries++; - } - - void unknownHandlerForQuery() { - numQueriesToUnknownHandler++; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - if (numInvalidSrdiMessages != 0) { - DocumentSerializableUtilities.addInt(element, "numInvalidSrdiMessages", numInvalidSrdiMessages); - } - if (numSrdiMessagesToUnknownHandler != 0) { - DocumentSerializableUtilities.addInt(element, "numSrdiMessagesToUnknownHandler", numSrdiMessagesToUnknownHandler); - } - if (numInvalidResponses != 0) { - DocumentSerializableUtilities.addInt(element, "numInvalidResponses", numInvalidResponses); - } - if (numResponsesToUnknownHandler != 0) { - DocumentSerializableUtilities.addInt(element, "numResponsesToUnknownHandler", numResponsesToUnknownHandler); - } - if (numInvalidQueries != 0) { - DocumentSerializableUtilities.addInt(element, "numInvalidQueries", numInvalidQueries); - } - if (numQueriesToUnknownHandler != 0) { - DocumentSerializableUtilities.addInt(element, "numQueriesToUnknownHandler", numQueriesToUnknownHandler); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("numInvalidSrdiMessages")) { - numInvalidSrdiMessages = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numSrdiMessagesToUnknownHandler")) { - numSrdiMessagesToUnknownHandler = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numInvalidResponses")) { - numInvalidResponses = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numResponsesToUnknownHandler")) { - numResponsesToUnknownHandler = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numInvalidQueries")) { - numInvalidQueries = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numQueriesToUnknownHandler")) { - numQueriesToUnknownHandler = DocumentSerializableUtilities.getInt(childElement); - } - } - } - - public void mergeMetrics(ResolverMetric otherResolverMetric) { - if (otherResolverMetric == null) { - return; - } - this.numInvalidSrdiMessages += otherResolverMetric.numInvalidSrdiMessages; - this.numSrdiMessagesToUnknownHandler += otherResolverMetric.numSrdiMessagesToUnknownHandler; - - this.numInvalidResponses += otherResolverMetric.numInvalidResponses; - this.numResponsesToUnknownHandler += otherResolverMetric.numResponsesToUnknownHandler; - - this.numInvalidQueries += otherResolverMetric.numInvalidQueries; - this.numQueriesToUnknownHandler += otherResolverMetric.numQueriesToUnknownHandler; - - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverServiceMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverServiceMetric.java deleted file mode 100644 index f455fc8e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverServiceMetric.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.meter.*; - -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.platform.*; -import net.jxta.id.*; -import java.util.*; -import net.jxta.util.*; -import net.jxta.exception.*; -import java.net.*; - - -/** - * The Service Monitor Metric for the standard Resolver Service - **/ -public class ResolverServiceMetric implements ServiceMetric { - private ResolverMetric resolverMetric; - private LinkedList queryHandlerMetrics = new LinkedList(); - private LinkedList srdiHandlerMetrics = new LinkedList(); - private ModuleClassID moduleClassID = MonitorResources.resolverServiceMonitorClassID; - - public ResolverServiceMetric() {} - - public ResolverServiceMetric(ModuleClassID moduleClassID) { - init(moduleClassID); - } - - public void init(ModuleClassID moduleClassID) { - this.moduleClassID = moduleClassID; - } - - public ModuleClassID getModuleClassID() { - return moduleClassID; - } - - /** - * Get the General Resolver Metric - **/ - public ResolverMetric getResolverMetric() { - return resolverMetric; - } - - void setResolverMetric(ResolverMetric resolverMetric) { - this.resolverMetric = resolverMetric; - } - - /** - * Add a Query Handler Metric - **/ - public void addQueryHandlerMetric(QueryHandlerMetric queryHandlerMetric) { - queryHandlerMetrics.add(queryHandlerMetric); - } - - /** - * Get All Query Handler Metrics as an iterator - **/ - public Iterator getQueryHandlerMetrics() { - return queryHandlerMetrics.iterator(); - } - - /** - * Get Query Handler Metrics for the corresponding handler - * @return Handler or null if not found - **/ - public QueryHandlerMetric getQueryHandlerMetric(String handlerName) { - for (Iterator i = queryHandlerMetrics.iterator(); i.hasNext();) { - QueryHandlerMetric queryHandlerMetric = (QueryHandlerMetric) i.next(); - - if (handlerName.equals(queryHandlerMetric.getHandlerName())) { - return queryHandlerMetric; - } - } - - return null; - } - - /** - * Add a Srdi Handler Metric - **/ - public void addSrdiHandlerMetric(SrdiHandlerMetric srdiHandlerMetric) { - srdiHandlerMetrics.add(srdiHandlerMetric); - } - - /** - * Get All Srdi Handler Metrics as an iterator - **/ - public Iterator getSrdiHandlerMetrics() { - return srdiHandlerMetrics.iterator(); - } - - /** - * Get Srdi Handler Metrics for the corresponding handler - * @return Handler or null if not found - **/ - public SrdiHandlerMetric getSrdiHandlerMetric(String handlerName) { - for (Iterator i = srdiHandlerMetrics.iterator(); i.hasNext();) { - SrdiHandlerMetric srdiHandlerMetric = (SrdiHandlerMetric) i.next(); - - if (handlerName.equals(srdiHandlerMetric.getHandlerName())) { - return srdiHandlerMetric; - } - } - - return null; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - - for (Iterator i = queryHandlerMetrics.iterator(); i.hasNext();) { - QueryHandlerMetric queryHandlerMetric = (QueryHandlerMetric) i.next(); - - DocumentSerializableUtilities.addDocumentSerializable(element, "queryHandlerMetric", queryHandlerMetric); - } - - for (Iterator i = srdiHandlerMetrics.iterator(); i.hasNext();) { - SrdiHandlerMetric srdiHandlerMetric = (SrdiHandlerMetric) i.next(); - - DocumentSerializableUtilities.addDocumentSerializable(element, "srdiHandlerMetric", srdiHandlerMetric); - } - - if (resolverMetric != null) { - DocumentSerializableUtilities.addDocumentSerializable(element, "resolverMetric", resolverMetric); - } - - if (moduleClassID != null) { - DocumentSerializableUtilities.addString(element, "moduleClassID", moduleClassID.toString()); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("queryHandlerMetric")) { - QueryHandlerMetric queryHandlerMetric = (QueryHandlerMetric) DocumentSerializableUtilities.getDocumentSerializable( - childElement, QueryHandlerMetric.class); - - queryHandlerMetrics.add(queryHandlerMetric); - } - - if (tagName.equals("srdiHandlerMetric")) { - SrdiHandlerMetric srdiHandlerMetric = (SrdiHandlerMetric) DocumentSerializableUtilities.getDocumentSerializable( - childElement, SrdiHandlerMetric.class); - - srdiHandlerMetrics.add(srdiHandlerMetric); - } - - if (tagName.equals("resolverMetric")) { - resolverMetric = (ResolverMetric) DocumentSerializableUtilities.getDocumentSerializable(childElement - , - ResolverMetric.class); - } - if (tagName.equals("moduleClassID")) { - try { - moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI(DocumentSerializableUtilities.getString(childElement))); - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Can't read moduleClassID", jex); - } - } - } - } - - public void mergeMetrics(ServiceMetric otherOne) { - mergeMetrics(otherOne, true, true, true); - } - - /** - * Make a deep copy of this metric only including the portions designated in the Filter - * The resulting metric is Safe to modify without danger to the underlying Monitor Metrics - * @param resolverServiceMonitorFilter Filter designates constituant parts to be included - * @return a copy of this metric with references to the designated parts - **/ - public ResolverServiceMetric deepCopy(ResolverServiceMonitorFilter resolverServiceMonitorFilter) { - ResolverServiceMetric serviceMetric = new ResolverServiceMetric(); - - serviceMetric.moduleClassID = moduleClassID; - - serviceMetric.mergeMetrics(this, true, resolverServiceMonitorFilter.isIncludeQueryHandlerMetrics() - , - resolverServiceMonitorFilter.isIncludeSrdiHandlerMetrics()); - return serviceMetric; - } - - public void mergeMetrics(ServiceMetric otherOne, boolean includeResolverMetric, boolean includeQueryHandlerMetrics, boolean includeSrdiHandlerMetrics) { - ResolverServiceMetric otherResolverServiceMetric = (ResolverServiceMetric) otherOne; - - if (includeResolverMetric) { - ResolverMetric otherResolverMetric = otherResolverServiceMetric.getResolverMetric(); - - if ((resolverMetric == null) && (otherResolverMetric != null)) { - resolverMetric = new ResolverMetric(otherResolverMetric); - } - - if (otherResolverMetric != null) { - resolverMetric.mergeMetrics(otherResolverMetric); - } - } - - if (includeQueryHandlerMetrics) { - for (Iterator i = otherResolverServiceMetric.getQueryHandlerMetrics(); i.hasNext();) { - QueryHandlerMetric otherQueryHandlerMetric = (QueryHandlerMetric) i.next(); - QueryHandlerMetric queryHandlerMetric = getQueryHandlerMetric(otherQueryHandlerMetric.getHandlerName()); - - if (queryHandlerMetric == null) { - queryHandlerMetric = new QueryHandlerMetric(otherQueryHandlerMetric); - addQueryHandlerMetric(queryHandlerMetric); - } - - queryHandlerMetric.mergeMetrics(otherQueryHandlerMetric); - } - } - - if (includeSrdiHandlerMetrics) { - for (Iterator i = otherResolverServiceMetric.getSrdiHandlerMetrics(); i.hasNext();) { - SrdiHandlerMetric otherSrdiHandlerMetric = (SrdiHandlerMetric) i.next(); - SrdiHandlerMetric srdiHandlerMetric = getSrdiHandlerMetric(otherSrdiHandlerMetric.getHandlerName()); - - if (srdiHandlerMetric == null) { - srdiHandlerMetric = new SrdiHandlerMetric(otherSrdiHandlerMetric); - addSrdiHandlerMetric(srdiHandlerMetric); - } - - srdiHandlerMetric.mergeMetrics(otherSrdiHandlerMetric); - } - } - } - - /** - * Make a shallow copy of this metric only including the portions designated in the Filter - *

            Note: since this is a shallow copy it is dangerous to modify the submetrics - * @param resolverServiceMonitorFilter Filter designates constituant parts to be included - * @return a copy of this metric with references to the designated parts - **/ - public ResolverServiceMetric shallowCopy(ResolverServiceMonitorFilter resolverServiceMonitorFilter) { - ResolverServiceMetric resolverServiceMetric = new ResolverServiceMetric(moduleClassID); - - resolverServiceMetric.resolverMetric = resolverMetric; - - if (resolverServiceMonitorFilter.isIncludeQueryHandlerMetrics()) { - for (Iterator i = getQueryHandlerMetrics(); i.hasNext();) { - QueryHandlerMetric queryHandlerMetric = (QueryHandlerMetric) i.next(); - - resolverServiceMetric.addQueryHandlerMetric(queryHandlerMetric); - } - } - - if (resolverServiceMonitorFilter.isIncludeSrdiHandlerMetrics()) { - for (Iterator i = getSrdiHandlerMetrics(); i.hasNext();) { - SrdiHandlerMetric srdiHandlerMetric = (SrdiHandlerMetric) i.next(); - - resolverServiceMetric.addSrdiHandlerMetric(srdiHandlerMetric); - } - } - - return resolverServiceMetric; - } - - public void diffMetrics(ServiceMetric otherOne) { - throw new RuntimeException("Not Supported"); - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverServiceMonitor.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverServiceMonitor.java deleted file mode 100644 index 19530b3b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverServiceMonitor.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.meter.*; -import net.jxta.impl.meter.*; -import java.util.*; - - -/** - * The Service Monitor Metric for the standard Resolver Service - **/ -public class ResolverServiceMonitor extends GenericServiceMonitor { - public static final String UNKNOWN_HANDLER = "--UNKNOWN-HANDLER--"; - - private Hashtable queryHandlerMeters = new Hashtable(); - private Hashtable srdiHandlerMeters = new Hashtable(); - private Hashtable destinationMeters = new Hashtable(); - private Hashtable sourceMeters = new Hashtable(); - - private ResolverMeter resolverMeter = new ResolverMeter(this); - - private ResolverServiceMetric cumulativeResolverServiceMetric; - - @Override - protected void init() { - cumulativeResolverServiceMetric = (ResolverServiceMetric) getCumulativeServiceMetric(); - cumulativeResolverServiceMetric.setResolverMetric(resolverMeter.getCumulativeMetrics()); - } - - public ResolverMeter getResolverMeter() { - return resolverMeter; - } - - public synchronized QueryHandlerMeter registerQueryHandlerMeter(String handlerName) { - QueryHandlerMeter queryHandlerMeter = (QueryHandlerMeter) queryHandlerMeters.get(handlerName); - - if (queryHandlerMeter == null) { - queryHandlerMeter = addQueryHandlerMeter(handlerName, true); - } - - queryHandlerMeter.setRegistered(true); - - return queryHandlerMeter; - } - - public synchronized QueryHandlerMeter addQueryHandlerMeter(String handlerName, boolean registered) { - QueryHandlerMeter queryHandlerMeter = new QueryHandlerMeter(handlerName, this); - - queryHandlerMeters.put(handlerName, queryHandlerMeter); - cumulativeResolverServiceMetric.addQueryHandlerMetric(queryHandlerMeter.getCumulativeMetrics()); - queryHandlerMeter.setRegistered(registered); - - return queryHandlerMeter; - } - - public synchronized QueryHandlerMeter unregisterQueryHandlerMeter(String handlerName) { - QueryHandlerMeter queryHandlerMeter = getQueryHandlerMeter(handlerName); - - queryHandlerMeter.setRegistered(false); - - return queryHandlerMeter; - } - - public QueryHandlerMeter getQueryHandlerMeter(String handlerName) { - QueryHandlerMeter queryHandlerMeter = (QueryHandlerMeter) queryHandlerMeters.get(handlerName); - - if (queryHandlerMeter == null) { - queryHandlerMeter = addQueryHandlerMeter(handlerName, false); - } - - return queryHandlerMeter; - } - - public synchronized SrdiHandlerMeter registerSrdiHandlerMeter(String handlerName) { - SrdiHandlerMeter srdiHandlerMeter = (SrdiHandlerMeter) srdiHandlerMeters.get(handlerName); - - if (srdiHandlerMeter == null) { - srdiHandlerMeter = addSrdiHandlerMeter(handlerName, true); - } - - srdiHandlerMeter.setRegistered(true); - - return srdiHandlerMeter; - } - - public synchronized SrdiHandlerMeter addSrdiHandlerMeter(String handlerName, boolean registered) { - SrdiHandlerMeter srdiHandlerMeter = new SrdiHandlerMeter(handlerName); - - srdiHandlerMeters.put(handlerName, srdiHandlerMeter); - cumulativeResolverServiceMetric.addSrdiHandlerMetric(srdiHandlerMeter.getCumulativeMetrics()); - srdiHandlerMeter.setRegistered(registered); - - return srdiHandlerMeter; - } - - public synchronized SrdiHandlerMeter unregisterSrdiHandlerMeter(String handlerName) { - SrdiHandlerMeter srdiHandlerMeter = getSrdiHandlerMeter(handlerName); - - srdiHandlerMeter.setRegistered(false); - - return srdiHandlerMeter; - } - - public SrdiHandlerMeter getSrdiHandlerMeter(String handlerName) { - SrdiHandlerMeter srdiHandlerMeter = (SrdiHandlerMeter) srdiHandlerMeters.get(handlerName); - - if (srdiHandlerMeter == null) { - srdiHandlerMeter = addSrdiHandlerMeter(handlerName, false); - } - - return srdiHandlerMeter; - } - - @Override - protected ServiceMetric collectServiceMetrics() { - ResolverServiceMetric resolverServiceMetric = (ResolverServiceMetric) createServiceMetric(); - - boolean anyData = false; - - for (Enumeration e = queryHandlerMeters.elements(); e.hasMoreElements();) { - QueryHandlerMeter queryHandlerMeter = (QueryHandlerMeter) e.nextElement(); - QueryHandlerMetric queryHandlerMetric = queryHandlerMeter.collectMetrics(); // clears delta from meter - - if (queryHandlerMetric != null) { - resolverServiceMetric.addQueryHandlerMetric(queryHandlerMetric); - anyData = true; - } - } - - for (Enumeration e = srdiHandlerMeters.elements(); e.hasMoreElements();) { - SrdiHandlerMeter srdiHandlerMeter = (SrdiHandlerMeter) e.nextElement(); - SrdiHandlerMetric srdiHandlerMetric = srdiHandlerMeter.collectMetrics(); // clears delta from meter - - if (srdiHandlerMetric != null) { - resolverServiceMetric.addSrdiHandlerMetric(srdiHandlerMetric); - anyData = true; - } - } - - ResolverMetric resolverMetric = resolverMeter.collectMetrics(); - - if (resolverMetric != null) { - resolverServiceMetric.setResolverMetric(resolverMetric); - anyData = true; - } - - if (anyData) { - return resolverServiceMetric; - } else { - return null; - } - } - - @Override - public ServiceMetric getServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime, int pulseIndex, long reportRate) { - int deltaReportRateIndex = monitorManager.getReportRateIndex(reportRate); - ResolverServiceMetric origMetric = (ResolverServiceMetric) deltaServiceMetrics[deltaReportRateIndex]; - - if (origMetric == null) { - return null; - } - - ResolverServiceMonitorFilter resolverServiceMonitorFilter = (ResolverServiceMonitorFilter) serviceMonitorFilter; - - return origMetric.shallowCopy(resolverServiceMonitorFilter); - } - - @Override - public ServiceMetric getCumulativeServiceMetric(ServiceMonitorFilter serviceMonitorFilter, long fromTime, long toTime) { - ResolverServiceMonitorFilter resolverServiceMonitorFilter = (ResolverServiceMonitorFilter) serviceMonitorFilter; - ResolverServiceMetric origMetric = (ResolverServiceMetric) cumulativeServiceMetric; - - return origMetric.deepCopy(resolverServiceMonitorFilter); - } - - /* - private ResolverServiceMetric copy(ResolverServiceMetric origMetric) { - ResolverServiceMetric resolverServiceMetric = new ResolverServiceMetric(); - - for (Iterator i = origMetric.getQueryHandlerMetrics(); i.hasNext(); ) { - QueryHandlerMetric queryHandlerMetric = (QueryHandlerMetric)i.next(); - resolverServiceMetric.addQueryHandlerMetric(queryHandlerMetric); - } - - for (Iterator i = origMetric.getSrdiHandlerMetrics(); i.hasNext(); ) { - SrdiHandlerMetric srdiHandlerMetric = (SrdiHandlerMetric)i.next(); - resolverServiceMetric.addSrdiHandlerMetric(srdiHandlerMetric); - } - - return resolverServiceMetric; - } - */ -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverServiceMonitorFilter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverServiceMonitorFilter.java deleted file mode 100644 index de4b98a1..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/ResolverServiceMonitorFilter.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.meter.*; -import net.jxta.platform.*; -import net.jxta.document.*; -import net.jxta.util.documentSerializable.*; -import java.util.*; -import net.jxta.util.*; -import net.jxta.exception.*; -import java.net.*; -import net.jxta.id.*; - - -public class ResolverServiceMonitorFilter implements ServiceMonitorFilter { - private boolean includeQueryHandlerMetrics = true; - private boolean includeSrdiHandlerMetrics = true; - private ModuleClassID moduleClassID = MonitorResources.resolverServiceMonitorClassID; - - public ModuleClassID getModuleClassID() { - return moduleClassID; - } - - public ResolverServiceMonitorFilter() {} - - public void init(ModuleClassID moduleClassID) { - this.moduleClassID = moduleClassID; - } - - public boolean isIncludeQueryHandlerMetrics() { - return includeQueryHandlerMetrics; - } - - public boolean isIncludeSrdiHandlerMetrics() { - return includeSrdiHandlerMetrics; - } - - public void setIncludeQueryHandlerMetrics(boolean includeQueryHandlerMetrics) { - this.includeQueryHandlerMetrics = includeQueryHandlerMetrics; - } - - public void setIncludeSrdiHandlerMetrics(boolean includeSrdiHandlerMetrics) { - this.includeSrdiHandlerMetrics = includeSrdiHandlerMetrics; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - DocumentSerializableUtilities.addBoolean(element, "includeQueryHandlerMetrics", includeQueryHandlerMetrics); - DocumentSerializableUtilities.addBoolean(element, "includeSrdiHandlerMetrics", includeSrdiHandlerMetrics); - if (moduleClassID != null) { - DocumentSerializableUtilities.addString(element, "moduleClassID", moduleClassID.toString()); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("includeQueryHandlerMetrics")) { - includeQueryHandlerMetrics = DocumentSerializableUtilities.getBoolean(childElement); - } - if (tagName.equals("includeSrdiHandlerMetrics")) { - includeSrdiHandlerMetrics = DocumentSerializableUtilities.getBoolean(childElement); - } - if (tagName.equals("moduleClassID")) { - try { - moduleClassID = (ModuleClassID) IDFactory.fromURI( - new URI(DocumentSerializableUtilities.getString(childElement))); - } catch (URISyntaxException jex) { - throw new DocumentSerializationException("Can't read moduleClassID", jex); - } - } - } - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiDestinationMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiDestinationMeter.java deleted file mode 100644 index fb705e57..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiDestinationMeter.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.peer.*; -import net.jxta.endpoint.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.util.*; -import java.util.*; - - -public class SrdiDestinationMeter { - private PeerID peerID; - - private SrdiDestinationMetric cumulativeMetrics; - private SrdiDestinationMetric deltaMetrics; - - public SrdiDestinationMeter(PeerID peerID) { - this.peerID = peerID; - cumulativeMetrics = new SrdiDestinationMetric(peerID); - } - - /* - public SrdiDestinationMeter(EndpointAddress addr) { - super(addr); - cumulativeMetrics = new SrdiDestinationMetric(addr); - } - */ - public synchronized SrdiDestinationMetric collectMetrics() { - SrdiDestinationMetric prevDelta = deltaMetrics; - - deltaMetrics = null; - return prevDelta; - } - - public SrdiDestinationMetric getCumulativeMetrics() { - return cumulativeMetrics; - } - - private void createDeltaMetric() { - deltaMetrics = new SrdiDestinationMetric(peerID); - } - - public PeerID getPeerID() { - return peerID; - } - - protected void messageProcessed() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.messageProcessed(); - cumulativeMetrics.messageProcessed(); - } - - protected void srdiToUnregisteredHandler() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.srdiToUnregisteredHandler(); - cumulativeMetrics.srdiToUnregisteredHandler(); - } - - protected void errorWhileProcessing() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.errorWhileProcessing(); - cumulativeMetrics.errorWhileProcessing(); - } - - protected void messageSentViaUnicast() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.messageSentViaUnicast(); - cumulativeMetrics.messageSentViaUnicast(); - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiDestinationMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiDestinationMetric.java deleted file mode 100644 index 0bb9a5dd..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiDestinationMetric.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.peer.*; -import net.jxta.endpoint.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import java.util.*; -import net.jxta.impl.meter.*; - -import net.jxta.util.*; - - -/** - * Metrics for a specific Srdi Destination for a specific handler - **/ -public class SrdiDestinationMetric implements DocumentSerializable { - private PeerID peerID; - private int messageProcessed; - private int errorWhileProcessing; - private int srdiToUnregisteredHandler = 0; - - private int messageSentViaUnicast; - - public SrdiDestinationMetric(PeerID peerID) { - this.peerID = peerID; - } - - public SrdiDestinationMetric(SrdiDestinationMetric prototype) { - this.peerID = prototype.peerID; - } - - public SrdiDestinationMetric() {} - - public PeerID getPeerID() { - return peerID; - } - - void messageProcessed() { - messageProcessed++; - } - - /** Messages Received and Processed from this destinations **/ - public int getMessagesProcessed() { - return messageProcessed; - } - - void errorWhileProcessing() { - errorWhileProcessing++; - } - - /** Messages Received, but generating errors when processing **/ - public int getErrorsWhileProcessing() { - return errorWhileProcessing; - } - - void messageSentViaUnicast() { - messageSentViaUnicast++; - } - - /** Get Messages Sent via Unicast to this destinations **/ - public int getMessagesSentViaUnicast() { - return messageSentViaUnicast; - } - - public void srdiToUnregisteredHandler() { - srdiToUnregisteredHandler++; - } - - /** Messages Received, to this when it was not registered **/ - public int getSrdiToUnregisteredHandler() { - return srdiToUnregisteredHandler; - } - - public void serializeTo(Element element) throws DocumentSerializationException { - if (peerID != null) { - DocumentSerializableUtilities.addString(element, "peerID", peerID.toString()); - } - if (messageProcessed != 0) { - DocumentSerializableUtilities.addInt(element, "messageProcessed", messageProcessed); - } - if (errorWhileProcessing != 0) { - DocumentSerializableUtilities.addInt(element, "errorWhileProcessing", errorWhileProcessing); - } - if (srdiToUnregisteredHandler != 0) { - DocumentSerializableUtilities.addInt(element, "srdiToUnregisteredHandler", srdiToUnregisteredHandler); - } - if (messageSentViaUnicast != 0) { - DocumentSerializableUtilities.addInt(element, "messageSentViaUnicast", messageSentViaUnicast); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("peerID")) { - String peerIDText = DocumentSerializableUtilities.getString(childElement); - - peerID = MetricUtilities.getPeerIdFromString(peerIDText); - } else if (tagName.equals("messageProcessed")) { - messageProcessed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("errorWhileProcessing")) { - errorWhileProcessing = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("srdiToUnregisteredHandler")) { - srdiToUnregisteredHandler = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("messageSentViaUnicast")) { - messageSentViaUnicast = DocumentSerializableUtilities.getInt(childElement); - } - } - } - - public void mergeMetrics(SrdiDestinationMetric otherSrdiDestinationMetric) { - this.errorWhileProcessing += otherSrdiDestinationMetric.errorWhileProcessing; - this.messageProcessed += otherSrdiDestinationMetric.messageProcessed; - this.messageSentViaUnicast += otherSrdiDestinationMetric.messageSentViaUnicast; - } - - @Override - public int hashCode() { - return peerID.hashCode(); - } - - @Override - public boolean equals(Object other) { - if (other instanceof SrdiDestinationMetric) { - SrdiDestinationMetric otherSrdiDestinationMetric = (SrdiDestinationMetric) other; - - return peerID.equals(otherSrdiDestinationMetric.peerID); - } else { - return false; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiHandlerMeter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiHandlerMeter.java deleted file mode 100644 index bdc6a90e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiHandlerMeter.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.protocol.ResolverSrdiMsg; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.peer.*; -import net.jxta.util.*; -import net.jxta.impl.meter.*; -import net.jxta.exception.*; -import java.util.*; - - -public class SrdiHandlerMeter { - private String handlerName; - - private SrdiHandlerMetric cumulativeMetrics; - private SrdiHandlerMetric deltaMetrics; - private Hashtable srdiDestinationMeters = new Hashtable(); - - public SrdiHandlerMeter(String handlerName) { - this.handlerName = handlerName; - cumulativeMetrics = new SrdiHandlerMetric(handlerName); - } - - public SrdiHandlerMetric getCumulativeMetrics() { - return cumulativeMetrics; - } - - public String getHandlerName() { - return handlerName; - } - - public synchronized SrdiHandlerMetric collectMetrics() { - SrdiHandlerMetric prevDelta = deltaMetrics; - - for (Enumeration e = srdiDestinationMeters.elements(); e.hasMoreElements();) { - SrdiDestinationMeter srdiDestinationMeter = (SrdiDestinationMeter) e.nextElement(); - - SrdiDestinationMetric srdiDestinationMetric = srdiDestinationMeter.collectMetrics(); - - if (srdiDestinationMetric != null) { - - /* Fix-me: Apparantly, we can have a case where NO Srdi mteric is tickled, but a - destination metric is available. This may be a bug. For now, we'll create the - delta in that case. - */ - if (prevDelta == null) { - createDeltaMetric(); - prevDelta = deltaMetrics; - } - prevDelta.addSrdiDestinationMetric(srdiDestinationMetric); - } - } - deltaMetrics = null; - return prevDelta; - } - - public synchronized SrdiDestinationMeter getSrdiDestinationMeter(EndpointAddress endpointAddress) { - PeerID peerID = MetricUtilities.getPeerIdFromEndpointAddress(endpointAddress); - - return getSrdiDestinationMeter(peerID); - } - - public synchronized SrdiDestinationMeter getSrdiDestinationMeter(String peer) { - PeerID peerID = MetricUtilities.getPeerIdFromString(peer); - - return getSrdiDestinationMeter(peerID); - } - - public synchronized SrdiDestinationMeter getSrdiDestinationMeter(PeerID peerID) { - - SrdiDestinationMeter srdiDestinationMeter = (SrdiDestinationMeter) srdiDestinationMeters.get(peerID); - - if (srdiDestinationMeter == null) { - srdiDestinationMeter = new SrdiDestinationMeter(peerID); - srdiDestinationMeters.put(peerID, srdiDestinationMeter); - cumulativeMetrics.addSrdiDestinationMetric(srdiDestinationMeter.getCumulativeMetrics()); - } - - return srdiDestinationMeter; - } - - private void createDeltaMetric() { - deltaMetrics = new SrdiHandlerMetric(handlerName); - } - - @Override - public String toString() { - return "SrdiHandlerMeter(" + handlerName + ")"; - } - - public void setRegistered(boolean registered) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.setRegistered(registered); - cumulativeMetrics.setRegistered(registered); - } - - // received - - public void messageProcessed(ResolverSrdiMsg srdi, long processTime, EndpointAddress srcAddr) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.messageProcessed(processTime); - cumulativeMetrics.messageProcessed(processTime); - - SrdiDestinationMeter destinationMeter = getSrdiDestinationMeter(srcAddr); - - destinationMeter.messageProcessed(); - } - - public void errorWhileProcessing(EndpointAddress srcAddr) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - deltaMetrics.errorWhileProcessing(); - cumulativeMetrics.errorWhileProcessing(); - - SrdiDestinationMeter destinationMeter = getSrdiDestinationMeter(srcAddr); - - destinationMeter.errorWhileProcessing(); - } - - public void srdiToUnregisteredHandler(EndpointAddress srcAddr) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.srdiToUnregisteredHandler(); - cumulativeMetrics.srdiToUnregisteredHandler(); - - SrdiDestinationMeter destinationMeter = getSrdiDestinationMeter(srcAddr); - - destinationMeter.srdiToUnregisteredHandler(); - } - - // send - - - public void messageSentViaUnicast(String peer, ResolverSrdiMsg srdi) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.messageSentViaUnicast(); - cumulativeMetrics.messageSentViaUnicast(); - - SrdiDestinationMeter destinationMeter = getSrdiDestinationMeter(peer); - - destinationMeter.messageSentViaUnicast(); - } - - public void messageSentViaWalker(ResolverSrdiMsg srdi) { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.messageSentViaWalker(); - cumulativeMetrics.messageSentViaWalker(); - } - - public void errorSendingMessage() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.errorSendingMessage(); - cumulativeMetrics.errorSendingMessage(); - } - - public void errorPropagatingMessage() { - if (deltaMetrics == null) { - createDeltaMetric(); - } - - deltaMetrics.errorPropagatingMessage(); - cumulativeMetrics.errorPropagatingMessage(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiHandlerMetric.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiHandlerMetric.java deleted file mode 100644 index 45815f43..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/resolver/resolverMeter/SrdiHandlerMetric.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Micro//Systems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.resolver.resolverMeter; - - -import net.jxta.resolver.*; -import net.jxta.util.documentSerializable.*; -import net.jxta.document.*; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.peer.*; -import net.jxta.impl.meter.*; - -import java.util.*; - - -public class SrdiHandlerMetric implements DocumentSerializable { - private String handlerName; - private boolean registered = true; - private int numProcessed = 0; - private int numErrorsWhileProcessing = 0; - private int numToUnregisteredHandler = 0; - - private long totalProcessTime = 0; - - private int numMessagesSentViaWalker = 0; - private int numMessagesSentViaUnicast = 0; - private int numErrorsSendingMessages = 0; - private int numErrorsPropagatingMessages = 0; - - private HashMap destinationMetrics = new HashMap(); - - public SrdiHandlerMetric(String handlerName) { - this.handlerName = handlerName; - } - - public SrdiHandlerMetric() {} - - public SrdiHandlerMetric(SrdiHandlerMetric prototype) { - this.handlerName = prototype.handlerName; - } - - public void setRegistered(boolean registered) { - this.registered = registered; - } - - public String getHandlerName() { - return handlerName; - } - - public boolean getRegistered() { - return registered; - } - - public int getNumProcessed() { - return numProcessed; - } - - public int getNumErrorsWhileProcessing() { - return numErrorsWhileProcessing; - } - - public long getTotalProcessTime() { - return totalProcessTime; - } - - public int getNumMessagesSentViaWalker() { - return numMessagesSentViaWalker; - } - - public int getNumMessagesSentViaUnicast() { - return numMessagesSentViaUnicast; - } - - public int getNumErrorsSendingMessages() { - return numErrorsSendingMessages; - } - - public int getNumErrorsPropagatingMessages() { - return numErrorsPropagatingMessages; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof SrdiHandlerMetric) { - SrdiHandlerMetric otherSrdiHandlerMetric = (SrdiHandlerMetric) obj; - - return handlerName.equals((otherSrdiHandlerMetric.handlerName)); - } else { - return false; - } - } - - @Override - public int hashCode() { - return handlerName.hashCode(); - } - - public void messageProcessed(long processTime) { - numProcessed++; - totalProcessTime += processTime; - } - - public void errorWhileProcessing() { - numErrorsWhileProcessing++; - } - - public void srdiToUnregisteredHandler() { - numToUnregisteredHandler++; - } - - public void messageSentViaWalker() { - numMessagesSentViaWalker++; - } - - public void messageSentViaUnicast() { - numMessagesSentViaUnicast++; - } - - public void errorSendingMessage() { - numErrorsSendingMessages++; - } - - public void errorPropagatingMessage() { - numErrorsPropagatingMessages++; - } - - SrdiDestinationMetric getSrdiDestinationMetric(EndpointAddress endpointAddress) { - PeerID peerID = MetricUtilities.getPeerIdFromEndpointAddress(endpointAddress); - - return getSrdiDestinationMetric(peerID); - } - - SrdiDestinationMetric getSrdiDestinationMetric(PeerID peerID) { - - SrdiDestinationMetric destinationMetric = (SrdiDestinationMetric) destinationMetrics.get(peerID); - - if (destinationMetric == null) { - destinationMetric = new SrdiDestinationMetric(peerID); - destinationMetrics.put(peerID, destinationMetric); - } - return destinationMetric; - } - - public Iterator getDestinationMetrics() { - - return destinationMetrics.values().iterator(); - } - - public void addSrdiDestinationMetric(SrdiDestinationMetric srdiDestinationMetric) { - destinationMetrics.put(srdiDestinationMetric.getPeerID(), srdiDestinationMetric); - } - - public void serializeTo(Element element) throws DocumentSerializationException { - if (handlerName != null) { - DocumentSerializableUtilities.addString(element, "handlerName", handlerName); - } - DocumentSerializableUtilities.addBoolean(element, "registered", registered); - if (numProcessed != 0) { - DocumentSerializableUtilities.addInt(element, "numProcessed", numProcessed); - } - if (numErrorsWhileProcessing != 0) { - DocumentSerializableUtilities.addInt(element, "numErrorsWhileProcessing", numErrorsWhileProcessing); - } - if (numToUnregisteredHandler != 0) { - DocumentSerializableUtilities.addInt(element, "numToUnregisteredHandler", numToUnregisteredHandler); - } - if (totalProcessTime != 0) { - DocumentSerializableUtilities.addLong(element, "totalProcessTime", totalProcessTime); - } - if (numMessagesSentViaWalker != 0) { - DocumentSerializableUtilities.addInt(element, "numMessagesSentViaWalker", numMessagesSentViaWalker); - } - if (numMessagesSentViaUnicast != 0) { - DocumentSerializableUtilities.addInt(element, "numMessagesSentViaUnicast", numMessagesSentViaUnicast); - } - if (numErrorsSendingMessages != 0) { - DocumentSerializableUtilities.addInt(element, "numErrorsSendingMessages", numErrorsSendingMessages); - } - if (numErrorsPropagatingMessages != 0) { - DocumentSerializableUtilities.addInt(element, "numErrorsPropagatingMessages", numErrorsPropagatingMessages); - } - - for (Iterator i = destinationMetrics.values().iterator(); i.hasNext();) { - Element srdiDestinationElement = DocumentSerializableUtilities.createChildElement(element, "destination"); - SrdiDestinationMetric srdiDestinationMetric = (SrdiDestinationMetric) i.next(); - - srdiDestinationMetric.serializeTo(srdiDestinationElement); - } - } - - public void initializeFrom(Element element) throws DocumentSerializationException { - for (Enumeration e = element.getChildren(); e.hasMoreElements();) { - Element childElement = (TextElement) e.nextElement(); - String tagName = (String) childElement.getKey(); - - if (tagName.equals("handlerName")) { - handlerName = DocumentSerializableUtilities.getString(childElement); - } else if (tagName.equals("registered")) { - registered = DocumentSerializableUtilities.getBoolean(childElement); - } else if (tagName.equals("numProcessed")) { - numProcessed = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numErrorsWhileProcessing")) { - numErrorsWhileProcessing = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numToUnregisteredHandler")) { - numToUnregisteredHandler = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("totalProcessTime")) { - totalProcessTime = DocumentSerializableUtilities.getLong(childElement); - } else if (tagName.equals("numMessagesSentViaWalker")) { - numMessagesSentViaWalker = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numMessagesSentViaUnicast")) { - numMessagesSentViaUnicast = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numErrorsSendingMessages")) { - numErrorsSendingMessages = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("numErrorsPropagatingMessages")) { - numErrorsPropagatingMessages = DocumentSerializableUtilities.getInt(childElement); - } else if (tagName.equals("destination")) { - SrdiDestinationMetric srdiDestinationMetric = new SrdiDestinationMetric(); - - srdiDestinationMetric.initializeFrom(childElement); - addSrdiDestinationMetric(srdiDestinationMetric); - } - } - } - - public void mergeMetrics(SrdiHandlerMetric otherSrdiHandlerMetric) { - numProcessed += otherSrdiHandlerMetric.numProcessed; - numErrorsWhileProcessing += otherSrdiHandlerMetric.numErrorsWhileProcessing; - totalProcessTime += otherSrdiHandlerMetric.totalProcessTime; - numMessagesSentViaWalker += otherSrdiHandlerMetric.numMessagesSentViaWalker; - numMessagesSentViaUnicast += otherSrdiHandlerMetric.numMessagesSentViaUnicast; - numErrorsSendingMessages += otherSrdiHandlerMetric.numErrorsSendingMessages; - numErrorsPropagatingMessages += otherSrdiHandlerMetric.numErrorsPropagatingMessages; - for (Iterator i = otherSrdiHandlerMetric.getDestinationMetrics(); i.hasNext();) { - SrdiDestinationMetric otherSrdiDestinationMetric = (SrdiDestinationMetric) i.next(); - SrdiDestinationMetric ourSrdiDestinationMetric = getSrdiDestinationMetric(otherSrdiDestinationMetric.getPeerID()); - - if (ourSrdiDestinationMetric == null) { - ourSrdiDestinationMetric = new SrdiDestinationMetric(otherSrdiDestinationMetric); - addSrdiDestinationMetric(ourSrdiDestinationMetric); - } - - ourSrdiDestinationMetric.mergeMetrics(otherSrdiDestinationMetric); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ACLSeedingManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ACLSeedingManager.java deleted file mode 100644 index 97e93588..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ACLSeedingManager.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (c) 2002-2004 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.net.URLConnection; - -import java.io.IOException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -import net.jxta.impl.access.AccessList; -import net.jxta.impl.endpoint.EndpointUtils; - - -/** - * Provides support for the optional access control list which determines which - * peers may be used. - */ -public abstract class ACLSeedingManager implements SeedingManager { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(ACLSeedingManager.class.getName()); - - /** - * The interval in milliseconds at which the ACL be refreshed from the - * source. - */ - private static final long ACL_REFRESH_INTERVAL = 30 * TimeUtils.AMINUTE; - - /** - * The access control list which controls which hosts are allowed. - */ - private final URI aclLocation; - - /** - * The last known modification time of the ACL. - */ - private long aclLastModified = 0; - - /** - * Manages access to the seeds. - */ - protected final AccessList acl = new AccessList(); - - /** - * The absolute time in milliseconds after which we will attempt to refresh - * the access control list from the acl URI. - */ - private long nextACLrefreshTime = 0; - - /** - * Constructs a new ACL seeding manager. - * - * @param aclLocation The location of the ACL file or {@code null} if no - * ACL file should be used. - */ - public ACLSeedingManager(URI aclLocation) { - this.aclLocation = aclLocation; - - // Default to allowing all peers. - acl.setGrantAll(true); - if (null == aclLocation) { - // forever. - nextACLrefreshTime = Long.MAX_VALUE; - } - } - - /** - * {@inheritDoc} - * - *

            Performs it's determination based solely on the list of peers in - * the access list. - */ - public boolean isAcceptablePeer(PeerAdvertisement peeradv) { - RouteAdvertisement route = EndpointUtils.extractRouteAdv(peeradv); - - if (null != route) { - return isAcceptablePeer(route); - } else { - // No route? It's only OK if we are approving everyone. - return acl.getGrantAll(); - } - } - - /** - * {@inheritDoc} - * - *

            Performs it's determination based solely on the list of peers in - * the access list. - */ - public synchronized boolean isAcceptablePeer(RouteAdvertisement radv) { - - // Refresh the ACL? - - if (TimeUtils.timeNow() > nextACLrefreshTime) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Updating ACL"); - } - - try { - URL asURL = aclLocation.toURL(); - URLConnection connection = asURL.openConnection(); - - connection.setDoInput(true); - InputStream is = connection.getInputStream(); - - long last_mod = connection.getLastModified(); - - if ((last_mod == 0) || (last_mod > aclLastModified)) { - acl.setGrantAll(false); - acl.refresh(is); - } - - nextACLrefreshTime = TimeUtils.toAbsoluteTimeMillis(ACL_REFRESH_INTERVAL); - } catch (IOException failed) { - // be lenient in response to failures. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "ACL update failed. GRANTING ALL PERMISSIONS.", failed); - } - - acl.setGrantAll(true); - - nextACLrefreshTime = TimeUtils.toAbsoluteTimeMillis(ACL_REFRESH_INTERVAL / 2); - } - } - - return acl.isAllowed(radv.getDestPeerID()); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/AdvCooker.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/AdvCooker.java deleted file mode 100644 index b9bbe67b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/AdvCooker.java +++ /dev/null @@ -1,513 +0,0 @@ - - -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredTextDocument; -import net.jxta.document.TextElement; -import net.jxta.document.XMLDocument; -import net.jxta.id.IDFactory; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleClassAdvertisement; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.ModuleSpecAdvertisement; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.PipeAdvertisement; - -import net.jxta.impl.peergroup.StdPeerGroup; -import net.jxta.impl.peergroup.StdPeerGroupParamAdv; - - -/** - * Advertisements and ID's "cooked" according to recipes lifted - * from J-C and Frog. Static methods meant for convenience in developing - * experimental propagation modules (pipe or rendezvous services, - * rendezvous managers) but maybe generally useful. - * - * @author vasha - */ -public class AdvCooker { - - /** - * Reconstructs a ModuleClassID from its String representation - * as printed by the foregoing recipes. - * - * @param url -- the module class id in String form, "urn:jxta:uuid-[the big hex string]" - * @throws URISyntaxException -- if url is messed up - * @return -- module class id reconstructed from String - */ - private static ModuleClassID buildModuleClassID(String uri) throws URISyntaxException { - return (ModuleClassID) IDFactory.fromURI(new URI(uri)); - } - - /** Reconstructs a ModuleSpecID from its String representation - * as printed by the foregoing recipes. - * - * @param url -- the module spec id in String form, "urn:jxta:uuid-[the big hex string]" - * @throws URISyntaxException -- if url is messed up - * @return -- module spec id reconstructed from String - */ - private static ModuleSpecID buildModuleSpecID(String uri) throws URISyntaxException { - return (ModuleSpecID) IDFactory.fromURI(new URI(uri)); - } - - /** - * The module class advertisement is to simply advertise the - * existence of a module. - * - * @param mcid -- the module class id - * @param serviceName -- something like "JXTAMOD:JXTA-WIRE-MyNewThing" - * @param serviceDescription -- something like "JXTA-WIRE MyNewThing Module" - * @return an appropriate ModuleClassAdvertisement - */ - public static ModuleClassAdvertisement buildModuleClassAdvertisement(ModuleClassID mcid, String serviceName, String serviceDescription) { - ModuleClassAdvertisement mcadv = (ModuleClassAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleClassAdvertisement.getAdvertisementType()); - - mcadv.setName(serviceName); - mcadv.setDescription(serviceDescription); - mcadv.setModuleClassID(mcid); - return mcadv; - } - - /** - * The ModuleSpecAdvertisement has two purposes, to publish - * the uri of its formal specs for developers and to publish the - * means of remote access to the module's services if that - * is appropriate. (See {@link ModuleSpecAdvertisement} ) - * Use this form for a minimal advertisement, suitable - * for development. - * - * @param msid -- the module spec id, "urn:jxta:uuid-[the big hex string]" - * @param moduleSpecName -- something like "JXTASPEC:JXTA-WIRE-MyNewThing-SPEC" - * @param moduleSpecDescription -- something like "JXTA-WIRE MyNewThing Specification" - * @return -- a boilerplate suitable for development. - */ - public static ModuleSpecAdvertisement buildModuleSpecAdvertisement(ModuleSpecID msid, String moduleSpecName, String moduleSpecDescription) { - return buildModuleSpecAdvertisement(msid, moduleSpecName, moduleSpecDescription, null, null, null, null, null, null, null); - } - - /** - * Use this form for production provided remote access is not required. - * - * @param msid -- the module spec id, "urn:jxta:uuid-[the big hex string]" - * @param moduleSpecName -- something like "JXTASPEC:JXTA-WIRE-MyNewThing-SPEC" - * @param moduleSpecDescription -- something like "JXTA-WIRE MyNewThing Specification" - * @param creator -- something like "jxta.org" - * @param version -- something like "Version 1.0" - * @param specURI -- where to locate the formal specs, e.g. "http://www.jxta.org/MyNewThing" - * @return -- a fully populated advert suitable if remote access is not required. - */ - public static ModuleSpecAdvertisement buildModuleSpecAdvertisement(ModuleSpecID msid, String moduleSpecName, String moduleSpecDescription, String creator, String version, String specURI) { - return buildModuleSpecAdvertisement(msid, moduleSpecName, moduleSpecDescription, creator, version, specURI, null, null - , - null, null); - } - - /** - * Use this form for a fully populated advert. - * - * @param msid -- the module spec id, "urn:jxta:uuid-[the big hex string]" - * @param moduleSpecName -- something like "JXTASPEC:JXTA-WIRE-MyNewThing-SPEC" - * @param moduleSpecDescription -- something like "JXTA-WIRE MyNewThing Specification" - * @param creator -- something like "jxta.org" - * @param version -- something like "Version 2.0" - * @param specURI -- where to locate the formal specs, e.g. "http://www.jxta.org/MyNewThing" - * @param pipeAdv -- to make the module useable remotely (see {@link ModuleSpecAdvertisement}) - * @param proxySpecID -- sometimes required for remote use (see {@link ModuleSpecAdvertisement}) - * @param authorizationSpecID -- sometimes required for remote use (see {@link ModuleSpecAdvertisement}) - * @param param -- anything else - * @return -- a fully populated advert specifying remote access to module services. - */ - public static ModuleSpecAdvertisement buildModuleSpecAdvertisement(ModuleSpecID msid, String moduleSpecName, String moduleSpecDescription, String creator, String version, String specURI, PipeAdvertisement pipeAdv, ModuleSpecID proxySpecID, ModuleSpecID authorizationSpecID, StructuredDocument param) { - ModuleSpecAdvertisement msadv = (ModuleSpecAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleSpecAdvertisement.getAdvertisementType()); - - msadv.setModuleSpecID(msid); - msadv.setName(moduleSpecName); - msadv.setDescription(moduleSpecDescription); - msadv.setCreator(creator == null ? "jxta.org" : creator); - msadv.setVersion(version == null ? "Version 2.0" : version); - msadv.setSpecURI(specURI == null ? "http://www.jxta.org/" + moduleSpecName : specURI); - if (pipeAdv != null) { - msadv.setPipeAdvertisement(pipeAdv); - } - if (proxySpecID != null) { - msadv.setProxySpecID(proxySpecID); - } - if (authorizationSpecID != null) { - msadv.setAuthSpecID(authorizationSpecID); - } - if (param != null) { - msadv.setParam(param); - } - return msadv; - } - - /** - * Compat's (compatibility statements) serve to narrow the search - * for a ModuleImplAdvertisement. Basically you want something - * compatible with your group's implementation. Use this form for - * compatibilty with the current StdPeerGroup. - * - * @return -- boilerplate compat for StdPeerGroup - */ - public static XMLDocument buildCompat() { - - try { - PeerGroup wpg = PeerGroup.globalRegistry.lookupInstance(PeerGroupID.worldPeerGroupID); - - ModuleImplAdvertisement implAdv = wpg.getAllPurposePeerGroupImplAdvertisement(); - - wpg.unref(); - - XMLDocument compat = (XMLDocument) implAdv.getCompat(); - - return compat; - } catch (Exception e) { - // but if it doesn't work default to what was current on Feb 22 2006. - return buildCompat("JDK1.4.1", "V2.0 Ref Impl"); - } - } - - /** - * Use this form for customized compatibility statements. - * Alternatively a group's compat is accessible via - * group.getCompat() - * - * @param efmt -- something like "JDK1.4" - * @param bind -- something like "V1.0 Ref Impl" - * @return -- custom compatibility tag - */ - public static XMLDocument buildCompat(String efmt, String bind) { - XMLDocument doc = (XMLDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Comp"); - - Element e = doc.createElement("Efmt", efmt); - - doc.appendChild(e); - e = doc.createElement("Bind", bind); - doc.appendChild(e); - - return doc; - } - - /** - * A ModuleImplAdvertisement represents one of any number of - * published implementations of a given specification. Use this form - * with for a development boilerplate. Use buildCompat() for a compat - * boilerplate. - * (See {@link ModuleImplAdvertisement}.) - * - * @param msid -- the module spec id - * @param code -- the module's fully qualified classname, "net.jxta.impl.wire.MyNewThing" - * @param compat -- a compatibility statement. Use buildCompat() for a boilerplate. - * @return -- a development boilerplate with custom compatibility. - */ - public static ModuleImplAdvertisement buildModuleImplAdvertisement(ModuleSpecID msid, String code, Element compat) { - ModuleImplAdvertisement miadv = (ModuleImplAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleImplAdvertisement.getAdvertisementType()); - - miadv.setCompat(compat); - miadv.setModuleSpecID(msid); - miadv.setCode(code); - miadv.setDescription(code + " Module, J2SE Implementation"); - miadv.setProvider("jxta.org"); - miadv.setUri("http://download.jxta.org"); - return miadv; - } - - /** Use this form to fully populate a ModuleImplAdvertisement. - * A ModuleImplAdvertisement has an optional field, "param" which is - * neglected here. If needed it should be set with advert's setParam method. - * (See {@link ModuleImplAdvertisement}.) - * - * @param msid -- the module spec id - * @param code -- the module's fully qualified classname, "net.jxta.impl.wire.MyNewThing" - * @param compat -- a compatibility statement - * @param description -- something like "MyNewThing Module, J2SE Implementation" - * @param provider -- something like "jxta.org" - * @param uri -- currently ornamental, eventually where to find binaries. - * @return -- a custom advert, fully populated except for "param" field. - */ - public static ModuleImplAdvertisement buildModuleImplAdvertisement(ModuleSpecID msid, String code, Element compat, String description, String provider, String uri) { - ModuleImplAdvertisement miadv = buildModuleImplAdvertisement(msid, code, compat); - - miadv.setDescription(description); - miadv.setProvider(provider); - miadv.setUri(uri); - return miadv; - } - - /** - * Modifies a copy of the parent's implementation - * advertisement to reflect the addition or replacement of - * services. The newServices Hashtable must have ModuleClassID - * keys and ModuleImplAdvertisement values. I've deferred adding - * applications or protocols for the moment --vasha@jxta.org Dec 3 2001. - * - * @return -- advert for the new peergroup which the StdPeerGroup module will implement. - * @param parent -- a running instance of the new group's parent - * @param newGroupModuleSpecID -- since new or replacement services are involved - * @param newDescription -- the new group's reason to be - * @param newServices -- advert's for the new services - * @throws IllegalArgumentException -- for a bad key or value type - * @throws Exception --- if the parent can't produce a copy of its own impl advert - */ - public static ModuleImplAdvertisement buildPeerGroupImplAdvertisement(StdPeerGroup parent, ModuleSpecID newGroupModuleSpecID, String newDescription, Map newServices) throws Exception { - Map newApps = null, newProtos = null; - - // illegal types will cause an IllegalArgumentException - typeCheckKeys(newServices); - typeCheckValues(newServices); - // get a copy of parent's general purpose advert as a template - ModuleImplAdvertisement implAdv = parent.getAllPurposePeerGroupImplAdvertisement(); - - implAdv.setDescription(newDescription); - implAdv.setModuleSpecID(newGroupModuleSpecID); - // extract embedded ad for standard modules - TextElement paramElement = (TextElement) implAdv.getParam(); - StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv(paramElement); - // alter services - Map services = paramAdv.getServices(); - - typeCheckKeys(services); - // mergeTables will override old services with new if base classes are the same - services = mergeTables(services, newServices); - paramAdv.setServices(services); - paramElement = (TextElement) paramAdv.getDocument(MimeMediaType.XMLUTF8); - implAdv.setParam(paramElement); - return implAdv; - } - - public static ModuleImplAdvertisement buildPeerGroupImplAdvertisement(PeerGroup parent, ModuleSpecID newGroupModuleSpecID, String newDescription, Map newServices, Map newApps) throws Exception { - Map newProtos = null; - - // illegal types will cause an IllegalArgumentException - typeCheckKeys(newServices); - typeCheckValues(newServices); - typeCheckKeys(newApps); - typeCheckValues(newApps); - - // get a copy of parent's general purpose advert as a template - ModuleImplAdvertisement implAdv = parent.getAllPurposePeerGroupImplAdvertisement(); - - implAdv.setDescription(newDescription); - implAdv.setModuleSpecID(newGroupModuleSpecID); - // extract embedded ad for standard modules - TextElement paramElement = (TextElement) implAdv.getParam(); - StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv(paramElement); - - // alter services - Map services = paramAdv.getServices(); - - typeCheckKeys(services); - // mergeTables will override old services with new if base classes are the same - services = mergeTables(services, newServices); - paramAdv.setServices(services); - - // alter apps - Map apps = paramAdv.getApps(); - - typeCheckKeys(apps); - apps = mergeTables(apps, newApps); - paramAdv.setApps(apps); - - paramElement = (TextElement) paramAdv.getDocument(MimeMediaType.XMLUTF8); - implAdv.setParam(paramElement); - - return implAdv; - } - - public static ModuleImplAdvertisement buildPeerGroupImplAdvertisement(PeerGroup parent, ModuleSpecID newGroupModuleSpecID, String newDescription, Map newServices, Map newApps, Map newProtos) throws Exception { - - // illegal types will cause an IllegalArgumentException - typeCheckKeys(newServices); - typeCheckValues(newServices); - typeCheckKeys(newApps); - typeCheckValues(newApps); - typeCheckKeys(newProtos); - typeCheckValues(newProtos); - - // get a copy of parent's general purpose advert as a template - ModuleImplAdvertisement implAdv = parent.getAllPurposePeerGroupImplAdvertisement(); - - implAdv.setDescription(newDescription); - implAdv.setModuleSpecID(newGroupModuleSpecID); - // extract embedded ad for standard modules - TextElement paramElement = (TextElement) implAdv.getParam(); - StdPeerGroupParamAdv paramAdv = new StdPeerGroupParamAdv(paramElement); - - // alter services - Map services = paramAdv.getServices(); - - typeCheckKeys(services); - // mergeTables will override old services with new if base classes are the same - services = mergeTables(services, newServices); - paramAdv.setServices(services); - - // alter apps - Map apps = paramAdv.getApps(); - - typeCheckKeys(apps); - apps = mergeTables(apps, newApps); - paramAdv.setApps(newApps); - - // alter protos - Map protos = paramAdv.getProtos(); - - typeCheckKeys(protos); - apps = mergeTables(protos, newProtos); - paramAdv.setProtos(newProtos); - - paramElement = (TextElement) paramAdv.getDocument(MimeMediaType.XMLUTF8); - implAdv.setParam(paramElement); - - return implAdv; - } - - /** - * Module table vaules must be ModuleImplAdvertisements here. - * Though StdPeerGroup allows for values of type ModuleSpecID, - * the context in which they seem to apply is not our context of adding - * or replacing modules, so I've prohibited them. --vasha@jxta.org dec 3 2001. - * - * @param moduleTable -- a Hashtable of services, applications or protocols. - * @throws IllegalArgumentException -- for an invalid key or value type - */ - public static void typeCheckValues(Map moduleTable) { - String badVal = "Module table value not a ModuleImplAdvertisement "; - Iterator keys = moduleTable.keySet().iterator(); - - while (keys.hasNext()) { - // Tables allow for ModuleSpecID values when, as I understand it, - // they can load the module from the parent. I'm insisting that - // NEW or ALTERNATIVE modules supply a ModuleImplAdvertisement. - Object value = moduleTable.get(keys.next()); - boolean legalValue = value instanceof ModuleImplAdvertisement; - - if (!legalValue) { - throw(new IllegalArgumentException(badVal + value)); - } - } - } - - /** - * Module table keys must be ModuleClassID's. - * - * @param moduleTable -- a Hashtable of services, applications or protocols. - * @throws IllegalArgumentException -- for an invalid key or value type - */ - public static void typeCheckKeys(Map moduleTable) { - String badKey = "Module table key not a ModuleClassID "; - Iterator keys = moduleTable.keySet().iterator(); - - while (keys.hasNext()) { - Object key = keys.next(); - boolean legalKey = key instanceof ModuleClassID; - - if (!legalKey) { - throw(new IllegalArgumentException(badKey + key)); - } - } - } - - /** - * Merge two hashtables of servcices, overwriting old with new if - * they have the same base class id. - * - * @oldServices --service table of a parent group - * @newServices --services to be added or substituted - * @return --merged table - */ - private static Map mergeTables(Map oldServices, Map newServices) { - // just use brute force; we won't be doing it that often - Map mergedServices = new HashMap(oldServices); - Iterator newKeys = newServices.keySet().iterator(); - - while (newKeys.hasNext()) { - ModuleClassID key = (ModuleClassID) newKeys.next(); - Iterator oldKeys = oldServices.keySet().iterator(); - - while (oldKeys.hasNext()) { - ModuleClassID oldkey = (ModuleClassID) oldKeys.next(); - - if (oldkey.isOfSameBaseClass(key)) { - mergedServices.remove(oldkey); - } - } - mergedServices.put(key, newServices.get(key)); - } - return mergedServices; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/BASE64InputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/BASE64InputStream.java deleted file mode 100644 index 656a3464..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/BASE64InputStream.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.io.InputStream; -import java.io.Reader; - -import java.io.IOException; - -/** - * An InputStream implementation which decodes BASE64 encoded - * data from a text Reader. - * - *

            This implementation is not thread safe. - * - * @see net.jxta.impl.util.BASE64OutputStream - * @see IETF RFC 2045 MIME : Format of Internet Message Bodies - **/ -public class BASE64InputStream extends InputStream { - - /** - * The input source of BASE64 text data. - **/ - private Reader source; - - /** - * If true then the stream has been closed. - **/ - private boolean closed = false; - - /** - * If true then the source reader has reached EOF. - **/ - private boolean atEOF = false; - - /** - * Buffer for unread but decoded bytes. - **/ - private byte buffer[] = new byte[3]; - - /** - * Position of current available character in buffer. - **/ - private byte inBuffer = 3; - - /** - * Construct InputStream given a source of BASE64 encoded text. - **/ - public BASE64InputStream(Reader source) { - this.source = source; - } - - /** - * {@inheritDoc} - **/ - @Override - public int available() throws IOException { - if (closed) { - throw new IOException("InputStream closed."); - } - - int bufferAvail = buffer.length - inBuffer; - - return (bufferAvail > 0) ? bufferAvail : (source.ready() ? 1 : 0); - } - - /** - * {@inheritDoc} - **/ - @Override - public void close() throws IOException { - closed = true; - - source.close(); - source = null; - } - - /** - * {@inheritDoc} - **/ - @Override - public void mark(int readLimit) { - throw new IllegalStateException("Mark not supported."); - } - - /** - * {@inheritDoc} - **/ - @Override - public boolean markSupported() { - return false; - } - - /** - * {@inheritDoc} - **/ - @Override - public int read() throws IOException { - if (closed) { - throw new IOException("InputStream closed."); - } - - while (!atEOF) { - if (inBuffer < buffer.length) { - return buffer[inBuffer++] & 0x00FF; - } - - inBuffer = 0; - - int s0; - - do { - s0 = source.read(); - } while ((-1 != s0) && Character.isWhitespace((char) s0)); - - if (-1 == s0) { - atEOF = true; - break; - } - - int s1 = source.read(); - int s2 = source.read(); - int s3 = source.read(); - - if ((-1 == s1) || (-1 == s2) || (-1 == s3)) { - throw new IOException("Unexpected EOF"); - } - - int c0 = decodeSixBits((char) s0); - int c1 = decodeSixBits((char) s1); - int c2 = decodeSixBits((char) s2); - int c3 = decodeSixBits((char) s3); - - if ((-1 == c0) || (-1 == c1) || (-1 == c2) || (-1 == c3)) { - throw new IOException("Bad character in BASE64 data"); - } - - if (Integer.MAX_VALUE == c0) { - throw new IOException("'=' found in first position of BASE64 data"); - } - - if (Integer.MAX_VALUE == c1) { - throw new IOException("'=' found in second position of BASE64 data"); - } - - if (Integer.MAX_VALUE == c3) { - c3 = 0; - inBuffer++; - } - - if (Integer.MAX_VALUE == c2) { - c2 = 0; - inBuffer++; - } - - int val = (c0 << 18) + (c1 << 12) + (c2 << 6) + c3; - - buffer[ inBuffer ] = (byte) (val >> 16); - - if ((inBuffer + 1) < buffer.length) { - buffer[ inBuffer + 1 ] = (byte) (val >> 8); - } - - if ((inBuffer + 2) < buffer.length) { - buffer[ inBuffer + 2 ] = (byte) val; - } - } - - return -1; - } - - /** - * - * XXX bondolo this would be faster as a table. - **/ - private static int decodeSixBits(char c) { - int v; - - if ('A' <= c && c <= 'Z') { - v = (c - 'A'); - } else if ('a' <= c && c <= 'z') { - v = (c - 'a') + 26; - } else if ('0' <= c && c <= '9') { - v = (c - '0') + 52; - } else if (c == '+') { - v = 62; - } else if (c == '/') { - v = 63; - } else if (c == '=') { - v = Integer.MAX_VALUE; - } else { - v = -1; - } - - return v; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/BASE64OutputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/BASE64OutputStream.java deleted file mode 100644 index f2bf45f4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/BASE64OutputStream.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.io.OutputStream; -import java.io.Writer; - -import java.io.IOException; -import java.io.StringReader; -import java.io.ByteArrayOutputStream; -import java.io.StringWriter; - - -/** - * An OutputStream implementation which encodes the written bytes into BASE64 - * encoded character data and writes the output to an associated text Writer. - * - *

            This implementation is not thread safe. - * - * @see net.jxta.impl.util.BASE64InputStream - * @see IETF RFC 2045 MIME : Format of Internet Message Bodies - **/ -public class BASE64OutputStream extends OutputStream { - - /** - * If true then the output stream has been closed. - **/ - private boolean closed = false; - - /** - * The output writer. - **/ - private Writer sendTo = null; - - /** - * Column width to breakup out. - **/ - private final int columnWidth; - - /** - * Current output column. - **/ - private int column = 0; - - /** - * Buffer for incomplete characters. - **/ - private byte[] buffer = new byte[] { 0, 0, 0 }; - - /** - * The number of characters currently in the buffer. - **/ - private byte inBuffer = 0; - - /** - * Construct a BASE64 Output Stream. - * - * @param sendTo The text Writer to which the BASE64 output will be - * written. - **/ - public BASE64OutputStream(Writer sendTo) { - this(sendTo, -1); - } - - /** - * Construct a BASE64 Output Stream. The output will be broken into lines - * columnWidth long. - * - * @param sendTo The text Writer to which the BASE64 output will be - * written. - * @param columnWidth The width of lines to break output into. - **/ - public BASE64OutputStream(Writer sendTo, int columnWidth) { - this.sendTo = sendTo; - this.columnWidth = columnWidth; - } - - /** - * {@inheritDoc} - **/ - @Override - public void write(int b) throws IOException { - if (closed) { - throw new IOException("OutputStream closed."); - } - - buffer[ inBuffer++ ] = (byte) b; - - if (buffer.length == inBuffer) { - writeBuffer(); - } - } - - /** - * {@inheritDoc} - * - *

            The output writer is NOT closed. - **/ - @Override - public void close() throws IOException { - flush(); - - closed = true; - sendTo = null; - } - - /** - * {@inheritDoc} - **/ - @Override - public void flush() throws IOException { - writeBuffer(); - } - - /** - * Write a full or partial buffer to the output writer. - **/ - private void writeBuffer() throws IOException { - if (0 == inBuffer) { - return; - } - - int val = ((buffer[0] & 0x00FF) << 16) + ((buffer[1] & 0x00FF) << 8) + (buffer[2] & 0x00FF); - - int c0 = (val >> 18) & 0x003F; - int c1 = (val >> 12) & 0x003F; - int c2 = (val >> 6) & 0x003F; - int c3 = val & 0x003F; - - if ((columnWidth > 0) && (column > columnWidth)) { - sendTo.write('\n'); - column = 0; - } - - sendTo.write(encodeSixBits(c0)); - sendTo.write(encodeSixBits(c1)); - - if (inBuffer > 1) { - sendTo.write(encodeSixBits(c2)); - } else { - sendTo.write('='); - } - - if (inBuffer > 2) { - sendTo.write(encodeSixBits(c3)); - } else { - sendTo.write('='); - } - - buffer[0] = 0; - buffer[1] = 0; - buffer[2] = 0; - - inBuffer = 0; - column += 4; - } - - /** - * BASE64 Encoding Table - **/ - static final char encode[] = { - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X' - , - 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v' - , - 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' - }; - - /** - * Encode six bits into a character using the standard BASE64 table. - * - * @param b the bits to encode. b must be >=0 and <= 63 - * @return the appropriate character for the input value. - **/ - private static char encodeSixBits(int b) { - char c; - - if ((b < 0) || (b > 63)) { - throw new IllegalArgumentException("bad encode value"); - } else { - c = encode[b]; - } - - return c; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Base64.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Base64.java deleted file mode 100644 index cea4bf09..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Base64.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.io.IOException; -import java.io.StringReader; -import java.io.ByteArrayOutputStream; -import java.io.StringWriter; - - -/** - * @deprecated Planned for removal. This implementation has been replaced by - * {@link net.jxta.impl.util.BASE64InputStream} and - * {@link net.jxta.impl.util.BASE64OutputStream}. - * - **/ -@Deprecated -public final class Base64 { - - private Base64() {} - - // Base64 encoding. See Rfc1341 - - static public byte[] decodeBase64(String text) throws IOException { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - StringReader r = new StringReader(text); - - for (;;) { - char c0 = getBase64Char(r); - - if (c0 == '\0') { - break; - } - char c1 = getBase64Char(r); - - if (c1 == '\0') { - throw new IOException("binary data not a multiple of four bytes"); - } - char c2 = getBase64Char(r); - - if (c2 == '\0') { - throw new IOException("binary data not a multiple of four bytes"); - } - char c3 = getBase64Char(r); - - if (c3 == '\0') { - throw new IOException("binary data not a multiple of four bytes"); - } - - if (c0 == '=') { - throw new IOException("'=' found in first position of base64 data"); - } - if (c1 == '=') { - throw new IOException("'=' found in second position of base64 data"); - } - int n = 3; - - if (c2 == '=') { - n = 1; - c2 = c3 = 'A'; // So we get a value of 0. - } else if (c3 == '=') { - n = 2; - c3 = 'A'; // So we get a value of 0. - } - - int v = (decodeSixBits(c0) << 18) + (decodeSixBits(c1) << 12) + (decodeSixBits(c2) << 6) + decodeSixBits(c3); - - int b0 = (v >> 16) & 0xff; - int b1 = (v >> 8) & 0xff; - int b2 = (v) & 0xff; - - os.write(b0); - if (n >= 2) { - os.write(b1); - } - if (n == 3) { - os.write(b2); - } - } - - return os.toByteArray(); - } - - /** - * '\0' represents end of file. - */ - static private char getBase64Char(StringReader r) throws IOException { - for (;;) { - int i = r.read(); - - if (i == -1) { - return '\0'; - } - - char c = (char) i; - - if ('A' <= c && c <= 'Z') { - return c; - } else if ('a' <= c && c <= 'z') { - return c; - } else if ('0' <= c && c <= '9') { - return c; - } else if (c == '+') { - return c; - } else if (c == '/') { - return c; - } else if (c == '=') { - return c; - } - - // Not a base64 char, loop around and try again. - - } - } - - static public String encodeBase64(byte[] bytes) { - int n = 0; - StringWriter w = new StringWriter(); - int v; - int h; // Six bits. Six, thus h for hex. - - int len = bytes.length / 3 * 3; - - for (int i = 0; i < len; i += 3) { - v = (bytes[i] << 16) + ((bytes[i + 1] & 0xff) << 8) + (bytes[i + 2] & 0xff); - - h = (v >> 18) & 0x3f; - w.write(encodeSixBits(h)); - - h = ((v >> 12) & 0x3f); - w.write(encodeSixBits(h)); - - h = ((v >> 6) & 0x3f); - w.write(encodeSixBits(h)); - - h = ((v >> 0) & 0x3f); - w.write(encodeSixBits(h)); - - n += 4; - if (n >= 76) { - w.write("\r\n"); - n = 0; - } - - } - - switch (bytes.length - len) { - case 0: - break; - - case 1: - v = (bytes[len] << 16); - - h = (v >> 18) & 0x3f; - w.write(encodeSixBits(h)); - - h = (v >> 12) & 0x3f; - w.write(encodeSixBits(h)); - - w.write('='); - w.write('='); - break; - - case 2: - v = (bytes[len] << 16) + ((bytes[len + 1] & 0xff) << 8); - - h = (v >> 18) & 0x3f; - w.write(encodeSixBits(h)); - - h = ((v >> 12) & 0x3f); - w.write(encodeSixBits(h)); - - h = ((v >> 6) & 0x3f); - w.write(encodeSixBits(h)); - - w.write('='); - break; - } - w.write("\r\n"); - return w.toString(); - } - - static private char encodeSixBits(int b) { - char c; - - if (b <= 25) { - c = (char) ('A' + b); - } else if (b <= 51) { - c = (char) ('a' + b - 26); - } else if (b <= 61) { - c = (char) ('0' + b - 52); - } else if (b == 62) { - c = '+'; - } else { - // if (b == 63) - c = '/'; - } - return c; - } - - static private int decodeSixBits(char c) { - int v; - - if ('A' <= c && c <= 'Z') { - v = (c - 'A'); - } else if ('a' <= c && c <= 'z') { - v = (c - 'a') + 26; - } else if ('0' <= c && c <= '9') { - v = (c - '0') + 52; - } else if (c == '+') { - v = 62; - } else { - // if (c == '/') - v = 63; - } - - return v; - } - - public static void main(String args[]) { - byte bytes[] = new byte[200]; - - for (int i = 0; i < bytes.length; ++i) { - bytes[i] = (byte) i; - } - - System.out.println(encodeBase64(bytes)); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Cache.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Cache.java deleted file mode 100644 index b7399dee..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Cache.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.util.HashMap; -import java.util.Map; - - -/** - * A Cache which is similar to {@link java.util.LinkedHashMap} - * - *

            LinkedList cannot be used efficiently because it - * cannot remove an element efficiently from the middle. For that, we need - * the externally referenced element (the thing to be removed) to - * be the list entry itself, rather than referenced by an invisible - * list entry. That is why we use the DLink/Dlist family. - */ -public class Cache { - - /** - * CacheEntryImpl objects are both part of a doubly linked list and - * inserted in a HashMap. They refer to the thing mapped which is what - * users of this class want to get, and to the key. The reason is - * that we need the key to remove from the map - * an entry that we found in list. The otherway around is made easy by - * the nature of the dlinked structure. - **/ - - class CacheEntryImpl extends Dlink implements CacheEntry { - - private final Object value; - private final Object key; - - // The application interface. - public CacheEntryImpl(Object k, Object v) { - key = k; - value = v; - } - - /** - * {@inheritDoc} - **/ - public Object getKey() { - return key; - } - - /** - * {@inheritDoc} - **/ - public Object getValue() { - return value; - } - } - - private final long maxSize; - private long size; - private final Map map = new HashMap(); - private final Dlist lru = new Dlist(); - - private final CacheEntryListener listener; - - /** - * Creates a cache whih will keep at most maxSize purgeable entries. - * Every new entry is purgeable by default. - * - *

            Entries that are not purgeable are not counted and are never removed - * unless clear() or remove() is called. Purgeable entries are removed - * silently as needed to make room for new entries so that the number - * of purgeable entries remains < maxSize. - * - *

            Entries prugeability is controlled by invoking the sticky() method - * or the stickyCacheEntry() method. - * - *

            For now, purged entries are abandonned to the GC which is probably not - * so bad. To permit acceleration of the collection of resources, a - * purge listener will be added soon. - */ - public Cache(long maxSize, CacheEntryListener listener) { - this.maxSize = maxSize; - this.size = 0; - this.listener = listener; - } - - /** - * Empties the cache completely. - * The entries are abandonned to the GC. - */ - public void clear() { - lru.clear(); - map.clear(); - } - - /** - * Purges some of the cache. - * The entries are cleaned-up properly. - */ - public void purge(int fraction) { - if (size == 0) { - return; - } - - if (fraction == 0) { - fraction = 1; - } - long nbToPurge = size / fraction; - - if (nbToPurge == 0) { - nbToPurge = 1; - } - - while (nbToPurge-- > 0) { - CacheEntryImpl toRm = (CacheEntryImpl) lru.next(); - - map.remove(toRm.getKey()); - toRm.unlink(); - --size; - if (listener != null) { - listener.purged(toRm); - } - } - } - - /** - * Inserts the given cache entry directly. - * Returns the previous cache entry associated with the given key, if any. - * Not exposed yet. Should not be a problem to expose it, but it is not - * needed yet. - */ - protected CacheEntry putCacheEntry(Object key, CacheEntry value) { - if (size == maxSize) { - CacheEntryImpl toRm = (CacheEntryImpl) lru.next(); - - map.remove(toRm.getKey()); - toRm.unlink(); - --size; - if (listener != null) { - listener.purged(toRm); - } - } - - lru.putLast((CacheEntryImpl) value); - ++size; - - CacheEntryImpl oldEntry = (CacheEntryImpl) map.put(key, value); - - if (oldEntry == null) { - return null; - } - - if (oldEntry.isLinked()) { - oldEntry.unlink(); - --size; - } - return oldEntry; - } - - /** - * Create a cache entry to hold the given value, and insert it. - * Returns the previous value associated with the given key, if any. - */ - public Object put(Object key, Object value) { - CacheEntry oldEntry = putCacheEntry(key, new CacheEntryImpl(key, value)); - - if (oldEntry == null) { - return null; - } - - return oldEntry.getValue(); - } - - /** - * Remove the value, if any, and cacheEntry associated with the given key. - * return the cacheEntry that has been removed. - * Not exposed yet. Should not be a problem to expose it, but it is not - * needed yet. - */ - protected CacheEntry removeCacheEntry(Object key) { - CacheEntryImpl oldEntry = (CacheEntryImpl) map.remove(key); - - if (oldEntry == null) { - return null; - } - if (oldEntry.isLinked()) { - oldEntry.unlink(); - --size; - } - return oldEntry; - } - - /** - * Remove the value, if any, and cacheEntry associated with the given key. - * returns the value that has been removed. - */ - public Object remove(Object key) { - CacheEntry oldEntry = removeCacheEntry(key); - - if (oldEntry == null) { - return null; - } - return oldEntry.getValue(); - } - - /** - * Return the cache entry, if any, associated with the given key. - * This is public; it improves performance by letting the application - * do a single lookup instead of two when it needs to find an object in - * the cache and then change its purgeability. - */ - public CacheEntry getCacheEntry(Object key) { - CacheEntryImpl foundEntry = (CacheEntryImpl) map.get(key); - - if (foundEntry == null) { - return null; - } - - // Leave the purgeability status alone but manage lru position if - // purgeable. - if (foundEntry.isLinked()) { - lru.putLast(foundEntry); - } - return foundEntry; - } - - /** - * Return the value, if any associated with the given key. - */ - public Object get(Object key) { - CacheEntry foundEntry = getCacheEntry(key); - - if (foundEntry == null) { - return null; - } - return foundEntry.getValue(); - } - - /** - * Change the purgeability of the given cacheEntry. - * If sticky is true, the entry cannot be purged. - * Note: if the CacheEntry is known, it is more efficient to use this - * method than sticky(), since sticky will preform a hashmap lookup - * to locate the cache entry. - */ - public void stickyCacheEntry(CacheEntry ce, boolean sticky) { - CacheEntryImpl target = (CacheEntryImpl) ce; - - if (sticky) { - - // Stiky => not purgeable. - - if (!target.isLinked()) { - return; - } - target.unlink(); - --size; - - } else { - - // ! Sticky => purgeable. - - if (target.isLinked()) { - return; - } - if (size == maxSize) { - CacheEntryImpl toRm = (CacheEntryImpl) lru.next(); - - map.remove(toRm.getKey()); - toRm.unlink(); - if (listener != null) { - listener.purged(toRm); - } - --size; - } - - lru.putLast(target); - ++size; - - } - } - - /** - * Force the value associated with the given key to be purgeable or - * non-purgeable from the cache (non-sticky vs. sticky). - * Note: Most often, a call to the get() method will be performed - * before it can be decided to invoke sticky(). Whenever this is the case - * it is better to invoke getCacheEntry() + getValue() and then - * stickyCacheEntry() since that eliminates one hashmap lookup. - */ - public void sticky(Object key, boolean sticky) { - CacheEntry foundEntry = (CacheEntry) map.get(key); - - if (foundEntry == null) { - return; - } - stickyCacheEntry(foundEntry, sticky); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/CacheEntry.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/CacheEntry.java deleted file mode 100644 index ab25ff80..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/CacheEntry.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -/** - * Part of a pre jdk1.4 replacement for LinkedHashMap which is basically a - * cache. The following is the definition of an entry in the cache. - * The implementation is the business of the Cache class. As far as the - * application is concerned, it is a handle that can return a key and - * a value. It is constructed and managed by the Cache class. - */ - -public interface CacheEntry { - public Object getKey(); - public Object getValue(); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/CacheEntryListener.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/CacheEntryListener.java deleted file mode 100644 index 40fa9bbb..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/CacheEntryListener.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -/** - * Part of a pre jdk1.4 replacement for LinkedHashMap which is basically a - * cache. The following is the definition of an entry in the cache. - * The implementation is the business of the Cache user. - * This listener is used to alerts the cache owner of events that affect - * cache entries. Currently purge() is the only method. It is called when a - * cache entry is purged from the cache. - */ - -public interface CacheEntryListener { - public void purged(CacheEntry c); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ConsumerBiasedQueue.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ConsumerBiasedQueue.java deleted file mode 100644 index e5b29e55..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ConsumerBiasedQueue.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import java.util.List; -import java.util.ArrayList; - -import net.jxta.impl.util.TimeUtils; - - -/** - * A queue who's implementation is biased towards effciency in removing - elements from the queue. - * - * FIXME 20020511 bondolo@jxta.org This could be more efficient with a - * circular queue implementation, but its a pain to write since we allow the - * queue to be resizable. - * - * FIXME 20020511 bondolo@jxta.org Exercise for the reader: Extend this - * class so that it does both LIFO and FIFO. - * - * @deprecated Please convert all code to use the java.util.concurrent BlockingQueue instead. - * - **/ -@Deprecated -public class ConsumerBiasedQueue extends UnbiasedQueue { - - /** - * Log4J - **/ - private static final Logger LOG = Logger.getLogger(ConsumerBiasedQueue.class.getName()); - - /** - * Default constructor. 100 element FIFO queue which drops oldest element - * when full. - */ - public ConsumerBiasedQueue() { - this(DEFAULT_MAX_OBJECTS, DROP_OLDEST_OBJECT); - } - - /** - * Full featured constructor for creating a new ConsumerBiasedQueue. - * - * @param size Queue will be not grow larger than this size. Use - * Integer.MAX_VALUE for "unbounded" queue size. - * @param dropOldest Controls behaviour of element insertion when the queue is - * full. If "true" and the queue is full upon a push operation then the - * oldest element will be dropped to be replaced with the element currently - * being pushed. If "false" then then newest item will be dropped. - */ - public ConsumerBiasedQueue(int size, boolean dropOldest) { - super(size, dropOldest, new ArrayList()); - } - - /** - * Flush the queue of all pending objects. - **/ - @Override - public void clear() { - synchronized (queue) { - super.clear(); - } - } - - @Override - public synchronized boolean push(Object obj) { - synchronized (queue) { - boolean pushed = super.push(obj); - - queue.notify(); // inform someone who is waiting. we dont have to tell everyone though - return pushed; - } - } - - /** - * Push an object onto the queue. If the queue is full then the push will - * wait for up to "timeout" milliseconds to push the object. At the end of - * "timeout" milliseconds, the push will either return false or remove the - * oldest item from the queue and insert "obj". This behaviour is contolled - * by the constructor parameter "dropOldest". - * - * This method, unlike all others is synchronized. This creates a - * bottleneck for producers seperate from the primary lock on the "queue" - * member. This reduces contention on the primary lock which benefits users - * who are popping items from the queue (Consumers). - * - * @param obj Object to be pushed onto the queue - * @param timeout Time in milliseconds to try to insert the item into a full - * queue. Per Java standards, a timeout of "0" (zero) will wait indefinitly. - * Negative values force no wait period at all. - * @return true if the object was intersted into the queue, otherwise false. - * @throws InterruptedException if the operation is interrupted before - * the timeout interval is completed. - **/ - @Override - public synchronized boolean push(Object obj, long timeout) throws InterruptedException { - return super.push(obj, timeout); - } - - /** - * Return next obj in the queue if there is one. - * - * @return Object, null if the queue is empty - **/ - @Override - public Object pop() { - synchronized (queue) { - return super.pop(); - } - } - - /** - * Returns an array of objects, possibly empty, from the queue. - * - * @param maxObjs the maximum number of items to return. - * @return an array of objects, possibly empty containing the returned - * queue elements. - **/ - @Override - public Object[] popMulti(int maxObjs) { - synchronized (queue) { - return super.popMulti(maxObjs); - } - } - - /** - * Set how many objects this queue may store. Note that if there are more - * objects already in the queue than the specified amount then the queue - * will retain its current capacity. - * - * @param maxObjs The number of objects which the queue must be able to - * store. - **/ - @Override - public void setMaxQueueSize(int maxObjs) { - synchronized (queue) { - super.setMaxQueueSize(maxObjs); - } - } - - /** - * Return the number of elements currently in the queue. This method is - * useful for statistical sampling, but should not be used to determine - * program logic due to the multi-threaded behaviour of these queues. You - * should use the return values and timeout behaviour of the push() and - * pop() methods to regulate how you use the queue. - * - * @return the number of elements currently in the queue. Be warned that - * even two sequential calls to this method may return different answers - * due to activity on other threads. - * - **/ - @Override - public int getCurrentInQueue() { - synchronized (queue) { - return super.getCurrentInQueue(); - } - } - - /** - * Return the average number of elements in the queue at Enqueue time. - * - * @return average number of elements which were in the queue at during all - * of the "push" operations which returned a "true" result. Does not - * include the item being pushed. If no elements have ever been enqueued - * then "NaN" will be returned. - **/ - @Override - public double getAvgInQueueAtEnqueue() { - synchronized (queue) { - return super.getAvgInQueueAtEnqueue(); - } - } - - /** - * Return the average number of elements in the queue at dequeue time. - * - * @return average number of elements which were in the queue at during all - * of the "pop" operations which returned a non-null result. Includes the - * item being "pop"ed in the average. If no elements have ever been dequeued - * then "NaN" will be returned. - **/ - @Override - public double getAvgInQueueAtDequeue() { - synchronized (queue) { - return super.getAvgInQueueAtDequeue(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Dlink.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Dlink.java deleted file mode 100644 index ea9eaff4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Dlink.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -/** - * A dlinkable base class. - * It is far less general than java's LinkedList but permits much better - * removal performance from the middle of the list because a contained - * element and the corresponding chaining object are one and the same. - * - * The major inconvenient of this class is that it is...a class, not an - * interface. Making it an interface does not make sense since one would have - * to re-implement it entirely. There is almost no value added in a List class - * in addition to a Link class. A list of these Dlink is just a stand-alone - * Dlink with just a couple of additional convenience methods. - */ - -public class Dlink { - - /** - * Previous element in list. - */ - private Dlink prev; - - /** - * Next element in list. - */ - private Dlink next; - - private void setNext(Dlink n) { - next = n; - } - - private void setPrev(Dlink p) { - prev = p; - } - - public Dlink next() { - return next; - } - - public Dlink prev() { - return prev; - } - - public void unlink() { - next.setPrev(prev); - prev.setNext(next); - next = prev = this; - } - - public boolean isLinked() { - return next != this; - } - - public void linkNewNext(Dlink ne) { - ne.unlink(); - ne.setPrev(this); - ne.setNext(next); - next.setPrev(ne); - next = ne; - } - - public void linkNewPrev(Dlink ne) { - ne.unlink(); - ne.setNext(this); - ne.setPrev(prev); - prev.setNext(ne); - prev = ne; - } - - public Dlink() { - next = prev = this; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Dlist.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Dlist.java deleted file mode 100644 index f2f357a6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/Dlist.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -/** - * A cheap doubly linked list. - * It is far less general than java's LinkedList but permits much better - * removal performance from the middle of the list because a contained - * element and the corresponding chaining object are one and the same. - * - * The major inconvenient of Dlink is that it is a class, not an - * interface. Making it an interface does not make sense since one would have - * to re-implement it entirely. A DList is just a stand-alone - * Dlink with just a couple of additional convenience methods. - * - * Note this class does not keep an element count. The way element removal - * works makes it impossible. Do it from the outside. - */ - -public class Dlist extends Dlink { - - public void putLast(Dlink ne) { - linkNewPrev(ne); - } - - public void putFirst(Dlink ne) { - linkNewNext(ne); - } - - public Dlink last() { - return prev(); - } - - public Dlink first() { - return next(); - } - - public void addLast(Dlink ne) { - linkNewPrev(ne); - } - - public void addFirst(Dlink ne) { - linkNewNext(ne); - } - - public Dlink getLast() { - return prev(); - } - - public Dlink getFirst() { - return next(); - } - - public Dlink removeLast() { - Dlink p = prev(); - - p.unlink(); - return p; - } - - public Dlink removeFirst() { - Dlink n = next(); - - n.unlink(); - return n; - } - - public void clear() { - unlink(); - } - - public boolean isEmpty() { - return !isLinked(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/DynamicEnumeration.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/DynamicEnumeration.java deleted file mode 100644 index 4df5507f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/DynamicEnumeration.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; - -import java.util.NoSuchElementException; - - -/** - * A dynamic {@link java.util.Enumeration} which allows items to added to the - * enumeration while it is in use. This is mostly intended for use with - * {@link java.io.SequenceInputStream}. When used with {@code SequenceInputStream} - * it is important to call {@code close()} on the enumeration before calling - * {@code close()} on the stream. Failing to do so will cause the stream to - * block as it tries to "drain" the enumeration. - * - *

            This class is entirely thread safe. Attempting to use the enumeration - * and to add objects from a single thread is not recommended, as it may - * deadlock the thread. - * - **/ -public class DynamicEnumeration implements Enumeration { - private List sequence = new ArrayList(); - - private volatile boolean closed = false; - - /** - * Creates a new instance of DynamicEnumeration - **/ - public DynamicEnumeration() {} - - /** - * Creates a new instance of DynamicEnumeration - **/ - public DynamicEnumeration(List initial) { - sequence.addAll(initial); - } - - /** - * {@inheritDoc} - * - *

            If the Enumeration has not been closed we may have to block until we - * have a stream to return. - **/ - public boolean hasMoreElements() { - while (!closed) { - synchronized (sequence) { - if (!sequence.isEmpty()) { - return true; - } - - try { - sequence.wait(); - } catch (InterruptedException woken) { - Thread.interrupted(); - } - } - } - - return false; - } - - /** - * {@inheritDoc} - * - *

            If the Enumeration has not been closed we may have to block until we - * have a stream to return. - **/ - public synchronized Object nextElement() { - while (!closed) { - synchronized (sequence) { - if (sequence.isEmpty()) { - try { - sequence.wait(); - } catch (InterruptedException woken) { - Thread.interrupted(); - } - continue; - } - - Object result = sequence.remove(0); - - return result; - } - } - - throw new NoSuchElementException("No more elements"); - } - - /** - * Add another object to the enumeration. - **/ - public void add(Object add) { - if (closed) { - throw new IllegalStateException("Enumeration was closed"); - } - - synchronized (sequence) { - sequence.add(add); - sequence.notify(); - } - } - - /** - * There will be no more objects added. - **/ - public void close() { - closed = true; - synchronized (sequence) { - sequence.notify(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/EndpointServiceStatsFilter.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/EndpointServiceStatsFilter.java deleted file mode 100644 index c58fdf18..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/EndpointServiceStatsFilter.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.MessageFilterListener; - -import java.util.Enumeration; -import java.util.Hashtable; - - -/** - * Instances of this clas can be registered with an EndpointService - * to gather statistics about what kind of messages pass through it. - *

            - * This class is not MT-safe, so make sure you plug it only - * into one endpoint service. - * - * @see net.jxta.endpoint.EndpointService#addIncomingMessageFilterListener - */ - -public class EndpointServiceStatsFilter implements MessageFilterListener { - - long lastMessageTime; - Hashtable channelTrafficTable; - Hashtable sourceCountTable; - Hashtable destCountTable; - - public EndpointServiceStatsFilter() { - - channelTrafficTable = new Hashtable(); - sourceCountTable = new Hashtable(); - destCountTable = new Hashtable(); - } - - /** - * This method is called by the EndpointService to give us a chance - * to look at the message before it is dispatched to any listeners. - */ - public Message filterMessage(Message msg, EndpointAddress source, EndpointAddress dest) { - Message.ElementIterator e = msg.getMessageElements(); - MessageElement el; - String namespace; - String name; - - while (e.hasNext()) { - el = e.next(); - - namespace = e.getNamespace(); - name = el.getElementName(); - - incrementCount(channelTrafficTable, source.getProtocolName() + "://" + source.getProtocolAddress() + "/" + namespace - , - (int) el.getByteLength()); - incrementCount(channelTrafficTable, source.getProtocolName() + "://" + source.getProtocolAddress() + "/" + name - , - (int) el.getByteLength()); - } - - if (source != null) { - incrementCount(sourceCountTable, source, 1); - } - - if (dest != null) { - incrementCount(destCountTable, dest, 1); - } - - lastMessageTime = System.currentTimeMillis(); - - return msg; - } - - /** - * Get the time we last saw a message. - * - * @return time last message was received, in milliseconds, - * since Jan. 1, 1970. - */ - - public long getLastMessageTime() { - return lastMessageTime; - } - - /** - * Get the number of messages seen with a given message element - * namespace or full message element name. (Both are referred - * to as "channel" here because filters and listeners are - * dispatched by the EndpointService based on message element - * namespaces or fully name.) - */ - public long getTrafficOnChannel(String channel) { - - return getCount(channelTrafficTable, channel); - } - - public Enumeration getChannelNames() { - return channelTrafficTable.keys(); - } - - /** - * Get the number of messages received from a given address. - */ - public long getMessageCountFrom(EndpointAddress addr) { - return getCount(sourceCountTable, addr); - } - - /** - * Get the number of messages we've seen that were adderssed - * to a given address. - */ - public long getMessageCountTo(EndpointAddress addr) { - return getCount(destCountTable, addr); - } - - private long getCount(Hashtable table, Object key) { - Counter counter = (Counter) table.get(key); - - return counter == null ? -1 : counter.value; - } - - private void incrementCount(Hashtable table, Object key, int incr) { - Counter counter = (Counter) table.get(key); - - if (counter == null) { - counter = new Counter(); - - table.put(key, counter); - } - - counter.value += incr; - } - - private static final class Counter { - long value; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/GenerateID.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/GenerateID.java deleted file mode 100644 index 10cf02c7..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/GenerateID.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.util; - - -import net.jxta.id.*; -import net.jxta.platform.*; -import net.jxta.peergroup.*; -import net.jxta.peer.*; -import net.jxta.pipe.*; -import net.jxta.codat.*; - - -/** - * @deprecated This would be much better as a JXTA shell command. Will be removed soon. - * - * Generate a new JXTA IDs from the command line. - * - * @author Kevin A. Burton - */ -@Deprecated -public class GenerateID { - - /** - * main() - * - */ - public static void main(String[] args) { - - try { - - ModuleClassID classID = IDFactory.newModuleClassID(); - - ModuleSpecID specID = IDFactory.newModuleSpecID(classID); - - PeerGroupID groupID = IDFactory.newPeerGroupID(); - - PeerID peerID = IDFactory.newPeerID(groupID); - - PipeID pipeID = IDFactory.newPipeID(groupID); - - CodatID codatID = IDFactory.newCodatID(groupID); - - ModuleSpecID groupSpecID = IDFactory.newModuleSpecID(PeerGroup.allPurposePeerGroupSpecID.getBaseClass()); - - System.out.println("Module Class ID - " + classID.toString()); - System.out.println("Module Spec ID - " + specID.toString()); - System.out.println("Peer Group ID - " + groupID.toString()); - System.out.println("Peer ID - " + peerID.toString()); - System.out.println("Pipe ID - " + pipeID.toString()); - System.out.println("Codat ID - " + codatID.toString()); - System.out.println("Peer Group Module Spec ID - " + groupSpecID.toString()); - - } catch (Throwable t) { - - t.printStackTrace(); - - } - - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/JxtaHash.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/JxtaHash.java deleted file mode 100644 index 1d10121b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/JxtaHash.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.util; - - -import java.util.*; -import java.io.File; -import java.math.BigInteger; -import java.io.InputStream; -import java.io.IOException; -import java.io.ByteArrayInputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - - -/** - * A message digest wrapper to provide hashing using java.security.MesssageDigest - */ -public class JxtaHash { - private final static Logger LOG = Logger.getLogger(JxtaHash.class.getName()); - public final static String SHA = "SHA"; - public final static String SHA1 = "SHA1"; - public final static String MD2 = "MD2"; - public final static String MD5 = "MD5"; - public final static String DSA = "DSA"; - public final static String RSA = "RSA"; - public final static String SHA1withDSA = "SHA1WITHDSA"; - private MessageDigest dig = null; - - /** - * Default JxtaHash constructor, with the default algorithm SHA1 - * - */ - public JxtaHash() { - try { - dig = MessageDigest.getInstance(SHA1); - } catch (NoSuchAlgorithmException ex) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(ex.toString()); - } - } - } - - /** - * Default JxtaHash constructor, with the default algorithm SHA1 - * - * @param expression message to hash - */ - public JxtaHash(String expression) { - this(SHA1, expression); - } - - /** - * Constructor for the JxtaHash object - * - * @deprecated This implementation may produce inconsistent results - * based upon varience of the locale. (The locale of getBytes() is - * not defined). - * - * @param algorithm algorithm - the name of the algorithm requested - * @param expression expression to digest - */ - @Deprecated - public JxtaHash(String algorithm, String expression) { - - this(algorithm, expression.getBytes()); - } - - /** - * Constructor for the JxtaHash object - * - * @param algorithm algorithm - the name of the algorithm requested - * @param expression expression to digest - */ - public JxtaHash(String algorithm, byte[] expression) { - try { - dig = MessageDigest.getInstance(algorithm); - if (expression != null) { - dig.update(expression); - } - } catch (NoSuchAlgorithmException ex) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(ex.toString()); - } - } - } - - /** - * Constructor for the JxtaHash object - * - * @param expression expression to digest - */ - public void update(String expression) { - if (expression != null) { - dig.update(expression.getBytes()); - } - } - - /** - * Gets the digest as digestInteger - * - * @return The digestInteger value - */ - public BigInteger getDigestInteger() { - - return new BigInteger(dig.digest()); - } - - /** - * Gets the digest as digestInteger - * - * @param expression expression to digest - * @return The digestInteger value - */ - public BigInteger getDigestInteger(byte[] expression) { - dig.reset(); - dig.update(expression); - return new BigInteger(dig.digest()); - } - - /** - * Gets the digest as digestInteger - * - * @param expression expression to digest - * @return The digestInteger value - */ - public BigInteger getDigestInteger(String expression) { - - return getDigestInteger(expression.getBytes()); - } - - /** - * Returns a int whose value is (getDigestInteger mod m). - * - * @param m the modulus. - * @return (getDigestInteger mod m). - */ - public int mod(long m) { - BigInteger bi = getDigestInteger(); - BigInteger mod = new BigInteger(longToBytes(m)); - BigInteger result = bi.mod(mod); - - return result.intValue(); - } - - /** - * convert a long into the byte array - * - * @param value long value to convert - * @return byte array - */ - private byte[] longToBytes(long value) { - byte[] bytes = new byte[8]; - - for (int eachByte = 0; eachByte < 8; eachByte++) { - bytes[eachByte] = (byte) (value >> ((7 - eachByte) * 8L)); - } - return bytes; - } - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/LRUCache.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/LRUCache.java deleted file mode 100644 index e48ee64e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/LRUCache.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright 1999-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package net.jxta.impl.util; - -import java.util.Iterator; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * This class implements a Generic LRU Cache. The cache is not thread-safe. - * - * @author Ignacio J. Ortega - * @author Mohamed Abdelaziz - */ - -public class LRUCache { - - private final transient int cacheSize; - private transient int currentSize; - private transient CacheNode first; - private transient CacheNode last; - private final transient Map> nodes; - - /** - * Constructor for the LRUCache object - * - * @param size Description of the Parameter - */ - public LRUCache(int size) { - currentSize = 0; - cacheSize = size; - nodes = new HashMap>(size); - } - - /** - * clear the cache - */ - public void clear() { - first = null; - last = null; - nodes.clear(); - currentSize = 0; - } - - /** - * returns the number of elements currently in cache - * - * @return the number of elements in cache - */ - public int size() { - return currentSize; - } - - /** - * retrieve an object from cache - * - * @param key key - * @return object - */ - public V get(K key) { - CacheNode node = nodes.get(key); - - if (node != null) { - moveToHead(node); - return node.value; - } - return null; - } - - public boolean contains(K key) { - return nodes.keySet().contains(key); - } - - protected Iterator iterator(int size) { - List list = new ArrayList(); - - for (CacheNode node : nodes.values()) { - list.add(node.value); - if (list.size() >= size) { - break; - } - } - return list.iterator(); - } - - private void moveToHead(CacheNode node) { - if (node == first) { - return; - } - if (node.prev != null) { - node.prev.next = node.next; - } - if (node.next != null) { - node.next.prev = node.prev; - } - if (last == node) { - last = node.prev; - } - if (first != null) { - node.next = first; - first.prev = node; - } - first = node; - node.prev = null; - if (last == null) { - last = first; - } - } - - /** - * puts an object into cache - * - * @param key key to store value by - * @param value object to insert - */ - public void put(K key, V value) { - CacheNode node = nodes.get(key); - - if (node == null) { - if (currentSize >= cacheSize) { - if (last != null) { - nodes.remove(last.key); - } - removeLast(); - } else { - currentSize++; - } - node = new CacheNode(key, value); - } - node.value = value; - moveToHead(node); - nodes.put(key, node); - } - - /** - * remove an object from cache - * - * @param key key - * @return Object removed - */ - public V remove(K key) { - CacheNode node = nodes.get(key); - - if (node != null) { - if (node.prev != null) { - node.prev.next = node.next; - } - if (node.next != null) { - node.next.prev = node.prev; - } - if (last == node) { - last = node.prev; - } - if (first == node) { - first = node.next; - } - } - if (node != null) { - return node.value; - } else { - return null; - } - } - - /** - * removes the last entry from cache - */ - private void removeLast() { - if (last != null) { - if (last.prev != null) { - last.prev.next = null; - } else { - first = null; - } - last = last.prev; - } - } - - /** - * cache node object wrapper - */ - protected class CacheNode { - final K key; - CacheNode next; - - CacheNode prev; - V value; - - /** - * Constructor for the CacheNode object - * - * @param key key - * @param value value - */ - CacheNode(K key, V value) { - this.key = key; - this.value = value; - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ModuleManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ModuleManager.java deleted file mode 100644 index 81fb365b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ModuleManager.java +++ /dev/null @@ -1,655 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.util.Enumeration; -import java.util.Hashtable; -import java.io.IOException; - -import net.jxta.platform.Module; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Element; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.StructuredDocumentUtils; -import net.jxta.document.TextElement; -import net.jxta.protocol.ModuleClassAdvertisement; -import net.jxta.protocol.ModuleImplAdvertisement; -import net.jxta.protocol.ModuleSpecAdvertisement; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.id.IDFactory; - - -/** - * Module Manager. - * - * This class allows to manage modules to be loaded, started and stopped - * within a PeerGroup. Modules that are loaded using the ModuleManager do not need - * to be listed within the PeerGroup advertisement, nor do they have to have - * published their ModuleSpec and ModuleImpl advertisements: the ModuleManager - * takes care of this task. However, other peers which may want to load the Module - * will also have to use its own loader (or the ModuleManager itself, of course): - * the ModuleManager only manages Modules on the local peer. - * - * The Module Manager allows, as an option, to use an application provided class loader. - * The default class loader is the PeerGroup class loader. - * - * The following example shows how to use the ModuleManager: - * - * - *

            - *      // Get the peergroup
            - *      PeerGroup group = getMyPeerGroup();
            - *      // Get the ModuleManager
            - *      ModuleManager moduleManager = ModuleManager.getModuleManager (group);
            - *
            - *      // Is the Module already loaded ?
            - *      Module module = moduleManager.lookupModule ("SampleModule");
            - *      if (module == null) {
            - *          // SampleModue is not loaded yet. Load it now.
            - *          module = moduleManager.loadModule ( "SampleModule", "net.jxta.app.SampleModule.SampleModule");
            - *      }
            - *
            - *      // Start SampleModule
            - *      moduleManager.startModule ("SampleModule", moduleArgs);
            - * 
            - */ - -public class ModuleManager { - - private static Hashtable managers = null; - private static long LOCAL_ADV_TTL = 5 * 60 * 1000; - // 5 minutes is more than sufficient - private static long REMOTE_ADV_TTL = 0; - // We do not allow remote access of the advertisements. - - private final Hashtable modules = new Hashtable(); - private final PeerGroup group; - - /** - * Private constructor that allows to create an instance of the Module Manager for each - * PeerGroup. - * - * @param group the PeerGroup for which the ModuleManager needs to allocated a new instance - * of itself. - */ - private ModuleManager(PeerGroup group) { - this.group = group; - } - - /** - * startModule - * - * This method is invoked by the application to start a previously loaded - * module. - * - * @param moduleName is the symbolic name of the module. - * @param args is an array of String containing optional arguments for the module. This - * array is passed directly to the startApp (String[] ) method of the Module. - */ - public void startModule(String moduleName, String[] args) { - - ModuleDesc moduleDesc = modules.get(moduleName); - - if (moduleDesc == null) { - // Cannot find such a module - return; - } - moduleDesc.startApp(args); - } - - /** - * stopModule - * - * This method is invoked by the application to stop a running module. - * - * @param moduleName is the symbolic name of the module. - */ - public void stopModule(String moduleName) { - - ModuleDesc moduleDesc = modules.get(moduleName); - - if (moduleDesc == null) { - // Cannot find such a module - return; - } - moduleDesc.stopApp(); - } - - /** - * getModuleManager - * - * This method is used in order to get the instance of the ModuleManager for a given - * PeerGroup. getModuleManager will create a new instance automatically if there is no - * instance for the given PeerGroup. - * - * @param group the PeerGroup for which the ModuleManager is asked. - * @return the ModuleManager instance for the given PeerGroup. - */ - public static ModuleManager getModuleManager(PeerGroup group) { - - if (managers == null) { - // This is the first time the ModuleManager is invoked. Create - // the Hashtable - managers = new Hashtable(); - } - ModuleManager manager; - - manager = managers.get(group.getPeerGroupID()); - - if (manager == null) { - manager = new ModuleManager(group); - managers.put(group.getPeerGroupID(), manager); - } - return manager; - } - - /** - * Description of the Method - * - * @param moduleName Description of the Parameter - * @param module Description of the Parameter - * @return Description of the Return Value - */ - private synchronized boolean registerModule(String moduleName, Module module) { - - ModuleDesc moduleDesc = modules.get(moduleName); - - if (moduleDesc != null) { - // There is already a module registered to that name. - return false; - } - moduleDesc = new ModuleDesc(module); - modules.put(moduleName, moduleDesc); - return true; - } - - /** - * lookupModule - * - * Get the Module from its symbolic name. - * - * @param moduleName symbolic name of the Module - * @return the Module for the given name. null is returned if there is no module - * of the given name. - */ - public synchronized Module lookupModule(String moduleName) { - - ModuleDesc moduleDesc = modules.get(moduleName); - - if (moduleDesc == null) { - // There is not any module registered to that name. - return null; - } - return moduleDesc.module; - } - - /** - * loadModule - * - * Loads a Module. A class loaded is provided by the application. - * If the module has already been loaded, the existing Module is returned. - * - * @param moduleName symbolic name of the Module - * @param loader application provided class loader - * @return the Module for the given name. null is returned if the module could not be - * loaded - */ - - public synchronized Module loadModule(String moduleName, ModuleManagerLoader loader) { - - // First check if the module is already loaded and registered - Module module = lookupModule(moduleName); - - if (module != null) { - return module; - } - module = loader.loadModule(moduleName); - if (module != null) { - // Since this module is not started by the standard - // JXTA PeerGroup, we need to initialize ourself. - // Note that the ID and the ModuleImplAdvertisement is - // then set to null, which is fine, since that has been - // the decision from the application to actually not use - // the standard PeerGroup Module loading scheme. - try { - module.init(group, null, null); - } catch (Exception e) { - // Init failed, the module cannot be initialized - return null; - } - registerModule(moduleName, module); - } - return module; - } - - /** - * loadModule - * - * Loads a Module. The default PeerGroup class loader will be used. The class - * must be within the CLASSPATH of the platform. - * If the module has already been loaded, the existing Module is returned. - * - * @param moduleName symbolic name of the Module - * @param moduleCode the name of the class to be loaded. - * @return the Module for the given name. null is returned if the module could not be - * loaded - */ - public synchronized Module loadModule(String moduleName, String moduleCode) { - - // First check if the module is already loaded and registered - Module module = lookupModule(moduleName); - - if (module != null) { - return module; - } - - if (!createModuleAdvs(moduleName, null, moduleCode, null, LOCAL_ADV_TTL, REMOTE_ADV_TTL)) { - - // Creation of the module advertisement has failed. - return null; - } - // Get the module. This should always work since the advertisements have - // just been created. - module = loadModule(moduleName); - if (module == null) { - // There is really nothing more we can do here. - return null; - } - return module; - } - - /** - * Description of the Method - * - * @param moduleName Description of the Parameter - * @return Description of the Return Value - */ - private synchronized Module loadModule(String moduleName) { - - // First check if the module is already loaded and registered - Module module = lookupModule(moduleName); - - if (module != null) { - return module; - } - - try { - // Recover the ModuleClassAdvertisement - Enumeration each = group.getDiscoveryService().getLocalAdvertisements(DiscoveryService.ADV, "Name", moduleName); - - if (!each.hasMoreElements()) { - // No advertisement. - return null; - } - - ModuleClassAdvertisement mcAdv = null; - - while (each.hasMoreElements()) { - try { - mcAdv = (ModuleClassAdvertisement) each.nextElement(); - break; - } catch (Exception ez1) {// ignored - } - } - - // Revover the Module Specification Advertisement - each = group.getDiscoveryService().getLocalAdvertisements(DiscoveryService.ADV, "Name", moduleName); - if (!each.hasMoreElements()) { - return null; - } - - ModuleSpecAdvertisement mSpecAdv = null; - - while (each.hasMoreElements()) { - try { - mSpecAdv = (ModuleSpecAdvertisement) each.nextElement(); - break; - } catch (Exception ez1) {// ignored - } - } - - module = group.loadModule(mcAdv.getModuleClassID(), mSpecAdv.getModuleSpecID(), PeerGroup.Here); - - if (module != null) { - registerModule(moduleName, module); - } - return module; - } catch (Exception ez2) { - return null; - } - } - - /** - * Description of the Method - * - * @param moduleName Description of the Parameter - * @param moduleSpecURI Description of the Parameter - * @param moduleCode Description of the Parameter - * @param moduleCodeURI Description of the Parameter - * @param localTTL Description of the Parameter - * @param remoteTTL Description of the Parameter - * @return Description of the Return Value - */ - private boolean createModuleAdvs(String moduleName, String moduleSpecURI, String moduleCode, String moduleCodeURI, long localTTL, long remoteTTL) { - - DiscoveryService disco = group.getDiscoveryService(); - - try { - // First create the Module class advertisement associated with the module - // We build the module class advertisement using the advertisement - // Factory class by passing it the type of the advertisement we - // want to construct. The Module class advertisement is to be used - // to simply advertise the existence of the module. This is a - // a very small advertisement that only advertise the existence - // of module. In order to access the module, a peer will - // have to discover the associated module spec advertisement. - - ModuleClassAdvertisement mcadv = (ModuleClassAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleClassAdvertisement.getAdvertisementType()); - - mcadv.setName(moduleName); - mcadv.setDescription("Created by ModuleManager: " + moduleName); - - ModuleClassID mcID = IDFactory.newModuleClassID(); - - mcadv.setModuleClassID(mcID); - - // Ok the Module Class advertisement was created, just publish - // it in my local cache and to my peergroup. This - // is the NetPeerGroup - disco.publish(mcadv, localTTL, remoteTTL); - - // Create the Module Spec advertisement associated with the module - // We build the module Spec Advertisement using the advertisement - // Factory class by passing in the type of the advertisement we - // want to construct. The Module Spec advertisement will contain - // all the information necessary for a client to contact the module - // for instance it will contain a pipe advertisement to - // be used to contact the module - - ModuleSpecAdvertisement mdadv = (ModuleSpecAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleSpecAdvertisement.getAdvertisementType()); - - // ModuleManager does not allow to set up any customized - // information for the Module. - - mdadv.setName(moduleName); - mdadv.setCreator("jxta.org"); - mdadv.setModuleSpecID(IDFactory.newModuleSpecID(mcID)); - - if (moduleSpecURI != null) { - mdadv.setSpecURI(moduleSpecURI); - } - - // Ok the Module advertisement was created, just publish - // it in my local cache and into the NetPeerGroup. - disco.publish(mdadv, localTTL, remoteTTL); - - // Create the Module Implementation advertisement - ModuleImplAdvertisement miadv = (ModuleImplAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleImplAdvertisement.getAdvertisementType()); - - miadv.setModuleSpecID(mdadv.getModuleSpecID()); - if (moduleCode != null) { - miadv.setCode(moduleCode); - } - - if (moduleCodeURI != null) { - miadv.setUri(moduleCodeURI); - } - miadv.setDescription("Created by ModuleManager: " + moduleName); - - // Steal the compat, provider, and uri from the - // group's own impl adv. We DO want them identical in - // this case. - ModuleImplAdvertisement pgImpl = (ModuleImplAdvertisement) group.getImplAdvertisement(); - - miadv.setCompat(pgImpl.getCompat()); - miadv.setUri(pgImpl.getUri()); - - // Ok the Module Class advertisement was created, just publish - // it in my local cache and to my peergroup. This - // is the NetPeerGroup - disco.publish(miadv, localTTL, remoteTTL); - } catch (Exception ex) { - return false; - } - return true; - } - - // FIXME this method should be refactored - /** - * Creates a Module Class, Spec, and Impl advertisements, and adds the service - * Advertisement as part of the Module Impl Advertisement, and publishes the advertisements - * in local cache - * - * @param group group - * @param moduleName module name - * @param description module description - * @param moduleSpecURI module spec uri - * @param moduleCode module code - * @param moduleCodeURI module code uri - * @param mcID module class id - * @param msID module spec id - * @param code module code - * @param serviceAdv service advertisement - * @param localTTL local cache lifetime in ms - * @param remoteTTL remote cache lifetime in ms - * @exception IOException if an io error occurs - */ - public void createServiceAdvertisement(PeerGroup group, String moduleName, String description, String moduleSpecURI, String moduleCode, String moduleCodeURI, ModuleClassID mcID, ModuleSpecID msID, String code, Advertisement serviceAdv, long localTTL, long remoteTTL) throws IOException { - - DiscoveryService discovery = group.getDiscoveryService(); - // Create module class advertisement - ModuleClassAdvertisement mcadv = (ModuleClassAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleClassAdvertisement.getAdvertisementType()); - - mcadv.setModuleClassID(mcID); - mcadv.setName(moduleName); - mcadv.setDescription(description); - - // Module spec advertisement - ModuleSpecAdvertisement mdspec = (ModuleSpecAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleSpecAdvertisement.getAdvertisementType()); - - mdspec.setModuleSpecID(msID); - mdspec.setName(moduleName); - mdspec.setSpecURI(moduleSpecURI); - - // Module implementation advertisement - ModuleImplAdvertisement miadv = (ModuleImplAdvertisement) - AdvertisementFactory.newAdvertisement(ModuleImplAdvertisement.getAdvertisementType()); - - miadv.setModuleSpecID(mdspec.getModuleSpecID()); - miadv.setDescription(description); - if (moduleCodeURI != null) { - miadv.setUri(moduleCodeURI); - } - if (moduleCode != null) { - miadv.setCode(moduleCode); - } - // Steal the compat, provider, and uri from the - // group's own impl adv. We DO want them identical in - // this case. - ModuleImplAdvertisement pgImpl = (ModuleImplAdvertisement) group.getImplAdvertisement(); - - miadv.setCompat(pgImpl.getCompat()); - miadv.setCode(code); - Element pEl = (Element) serviceAdv.getDocument(MimeMediaType.XMLUTF8); - StructuredDocument svcParm = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8, "Parm"); - - StructuredDocumentUtils.copyElements(svcParm, svcParm, pEl); - miadv.setParam(svcParm); - // publish the advertisements - discovery.publish(mcadv, localTTL, remoteTTL); - discovery.publish(mdspec, localTTL, remoteTTL); - discovery.publish(miadv, localTTL, remoteTTL); - } - - /** - * Retreives a Service Advertisement from a module impl advertisement - * @param group peer group - * @param mia ModuleImplAdvertisement - * @param advertismentType service advertisment string Type - * @return The service Advertisement - * @exception IOException if an io error occurs - */ - public Advertisement getServiceAdvertisement(PeerGroup group, ModuleImplAdvertisement mia, String advertismentType) throws IOException { - Element param = mia.getParam(); - Element pel = null; - - if (param != null) { - Enumeration list = param.getChildren(advertismentType); - - if (list.hasMoreElements()) { - pel = (Element) list.nextElement(); - } - } - Advertisement adv = AdvertisementFactory.newAdvertisement((TextElement) pel); - - return adv; - } - - /** - * Description of the Class - */ - private class ModuleDesc { - - /** - * Description of the Field - */ - protected Module module = null; - private boolean started = false; - private boolean stopped = true; - - /** - *Constructor for the ModuleDesc object - * - * @param module Description of the Parameter - */ - public ModuleDesc(Module module) { - this.module = module; - } - - /** - * Description of the Method - * - * @param args Description of the Parameter - */ - public void startApp(String[] args) { - if (module == null) { - return; - } - if (started) { - // Already started - nothing to do - return; - } - module.startApp(args); - started = true; - stopped = false; - } - - /** - * Description of the Method - */ - public void stopApp() { - if (module == null) { - return; - } - if (stopped) { - // Already stopped - nothing to do - return; - } - module.stopApp(); - stopped = true; - started = false; - } - } - - - /** - * ModuleManagerLoader interface. - * This interface is used by the application in order to provide its own - * class loader instead of using the standard PeerGroup loader. - */ - - public interface ModuleManagerLoader { - - /** - * This method is invoked by the ModuleManager when it is time to load - * the class associated to the module. The name of the module is provided, - * which allows the application provided loader to be able to load a variety - * of modules, if that is necessary for the application. Note that the ModuleManager - * assumes that the module which is loaded by the provided loader is not started: - * loading and starting a module are two different operations for the ModuleManager. - * - * @param moduleName is the symbolic name of the Module. - * @return Module the object that has been loaded. - */ - public Module loadModule(String moduleName); - } - -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ProducerBiasedQueue.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ProducerBiasedQueue.java deleted file mode 100644 index 084276d0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ProducerBiasedQueue.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import java.util.List; -import java.util.ArrayList; - -import net.jxta.impl.util.TimeUtils; - - -/** - * A queue who's implementation is biased towards effciency in adding elements - * to the queue. - * - * @deprecated Please convert all code to use the java.util.concurrent BlockingQueue instead. - * - **/ -@Deprecated -public class ProducerBiasedQueue extends UnbiasedQueue { - - /** - * Log4J - **/ - private static final Logger LOG = Logger.getLogger(ProducerBiasedQueue.class.getName()); - - /** - * Default constructor. 100 element FIFO queue which drops oldest element - * when full. - */ - public ProducerBiasedQueue() { - this(DEFAULT_MAX_OBJECTS, DROP_OLDEST_OBJECT); - } - - /** - * Full featured constructor for creating a new ConsumerBiasedQueue. - * - * @param size Queue will be not grow larger than this size. Use - * Integer.MAX_VALUE for "unbounded" queue size. - * @param dropOldest Controls behaviour of element insertion when the queue is - * full. If "true" and the queue is full upon a push operation then the - * oldest element will be dropped to be replaced with the element currently - * being pushed. If "false" then then newest item will be dropped. - */ - public ProducerBiasedQueue(int size, boolean dropOldest) { - super(size, dropOldest, new ArrayList()); - } - - /** - * Flush the queue of all pending objects. - **/ - @Override - public void clear() { - synchronized (queue) { - super.clear(); - } - } - - @Override - public boolean push(Object obj) { - synchronized (queue) { - boolean pushed; - - pushed = super.push(obj); - queue.notify(); // inform someone who is waiting. we dont have to tell everyone though. - return pushed; - } - } - - /* The pop methods of this queue, unlike the "push" method. This creates a - * bottleneck for producers seperate from the primary lock on the "queue" - * member. This reduces contention on the primary lock which benefits users - * who are popping items from the queue (Consumers). - * - */ - - /** - * Return next obj in the queue if there is one. - * - * @return Object, null if the queue is empty - **/ - @Override - public synchronized Object pop() { - synchronized (queue) { - return super.pop(); - } - } - - /** - * Gets a Object from the queue. If no Object is immediately available, - * then wait the specified amount of time. Per Java convention, a timeout - * of zero (0) means wait an infinite amount of time. Negative values mean - * do not wait at all. - * - * @param timeout amount of time to wait in milliseconds for an object to - * be available. Per Java convention, a timeout of zero (0) means wait an - * infinite amount of time. Negative values mean do not wait at all. - * @return The next object in the queue. - * @throws InterruptedException if the operation is interrupted before - * the timeout interval is completed. - */ - @Override - public synchronized Object pop(long timeout) throws InterruptedException { - synchronized (queue) { - return super.pop(timeout); - } - } - - /** - * Returns an array of objects, possibly empty, from the queue. - * - * @param maxObjs the maximum number of items to return. - * @return an array of objects, possibly empty containing the returned - * queue elements. - **/ - @Override - public synchronized Object[] popMulti(int maxObjs) { - synchronized (queue) { - return super.popMulti(maxObjs); - } - } - - /** - * Set how many objects this queue may store. Note that if there are more - * objects already in the queue than the specified amount then the queue - * will retain its current capacity. - * - * @param maxObjs The number of objects which the queue must be able to - * store. - **/ - @Override - public void setMaxQueueSize(int maxObjs) { - synchronized (queue) { - super.setMaxQueueSize(maxObjs); - } - } - - /** - * Return the number of elements currently in the queue. This method is - * useful for statistical sampling, but should not be used to determine - * program logic due to the multi-threaded behaviour of these queues. You - * should use the return values and timeout behaviour of the push() and - * pop() methods to regulate how you use the queue. - * - * @return the number of elements currently in the queue. Be warned that - * even two sequential calls to this method may return different answers - * due to activity on other threads. - * - **/ - @Override - public int getCurrentInQueue() { - synchronized (queue) { - return super.getCurrentInQueue(); - } - } - - /** - * Return the average number of elements in the queue at Enqueue time. - * - * @return average number of elements which were in the queue at during all - * of the "push" operations which returned a "true" result. Does not - * include the item being pushed. If no elements have ever been enqueued - * then "NaN" will be returned. - **/ - @Override - public double getAvgInQueueAtEnqueue() { - synchronized (queue) { - return super.getAvgInQueueAtEnqueue(); - } - } - - /** - * Return the average number of elements in the queue at dequeue time. - * - * @return average number of elements which were in the queue at during all - * of the "pop" operations which returned a non-null result. Includes the - * item being "pop"ed in the average. If no elements have ever been dequeued - * then "NaN" will be returned. - **/ - @Override - public double getAvgInQueueAtDequeue() { - synchronized (queue) { - return super.getAvgInQueueAtDequeue(); - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/RdvAdvSeedingManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/RdvAdvSeedingManager.java deleted file mode 100644 index 7f0cdbdd..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/RdvAdvSeedingManager.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2002-2004 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - -import java.io.IOException; -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.logging.Logging; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - -/** - * Adds the ability to discover RdvAdvs via Discovery. - */ -public class RdvAdvSeedingManager extends ACLSeedingManager { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(URISeedingManager.class.getName()); - - /** - * The minimum frequence at which we will update our seed lists. - */ - final static long MIN_REFRESH_INTERVAL = 30 * TimeUtils.ASECOND; - - /** - * Group who's services we will utilize. - */ - final PeerGroup group; - - /** - * The identifier which we use to distinguish our RdvAdvertisements. - */ - final String serviceName; - - /** - * The absolute time in milliseconds at which we may sen our next remote - * discovery. - */ - long nextRemoteDiscovery = 0; - - /** - * The Route Advertisements we have discovered. - */ - final List discoveredRoutes = new ArrayList(); - - /** - * Creates a new instance of RdvAdvSeedingManager - * - * @param aclLocation The location of the ACL file or {@code null} if no - * ACL file should be used. - */ - public RdvAdvSeedingManager(URI aclLocation, PeerGroup group, String serviceName) { - super(aclLocation); - - this.group = group; - this.serviceName = serviceName; - } - - /** - * Update seeds - */ - private void refreshActiveSeeds() { - DiscoveryService discovery = group.getDiscoveryService(); - - if((null != discovery) && (TimeUtils.timeNow() > nextRemoteDiscovery)) { - // Send a remote search hoping for future responses. - discovery.getRemoteAdvertisements(null, DiscoveryService.ADV, RdvAdvertisement.ServiceNameTag, serviceName, 3); - - Enumeration advs; - try { - advs = discovery.getLocalAdvertisements(DiscoveryService.ADV, RdvAdvertisement.ServiceNameTag, serviceName); - } catch( IOException failed ) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure retrieving advertisements" , failed); - } - - return; - } - - synchronized(this) { - discoveredRoutes.clear(); - - while(advs.hasMoreElements()) { - Advertisement anAdv = advs.nextElement(); - if(!(anAdv instanceof RdvAdvertisement)) { - continue; - } - - RdvAdvertisement rdvAdv = (RdvAdvertisement) anAdv; - RouteAdvertisement routeAdv = rdvAdv.getRouteAdv(); - routeAdv.setDestPeerID(rdvAdv.getPeerID()); - - discoveredRoutes.add(routeAdv); - } - - Collections.shuffle(discoveredRoutes); - - if(discoveredRoutes.isEmpty()) { - // Be extra aggressive if we haven't found anything yet. - nextRemoteDiscovery = TimeUtils.toAbsoluteTimeMillis(MIN_REFRESH_INTERVAL / 2); - } else { - nextRemoteDiscovery = TimeUtils.toAbsoluteTimeMillis(MIN_REFRESH_INTERVAL); - } - } - } - } - - /** - * {@inheritDoc} - */ - public void stop() { - // do nothing. - } - - /** - * {@inheritDoc} - */ - public synchronized URI[] getActiveSeedURIs() { - refreshActiveSeeds(); - - List results = new ArrayList(); - - int eaIndex = 0; - boolean addedEA; - - do { - addedEA = false; - - for (RouteAdvertisement aRA : discoveredRoutes) { - List raEAs = aRA.getDestEndpointAddresses(); - if (eaIndex < raEAs.size()) { - URI seedURI = raEAs.get(eaIndex).toURI(); - if(!results.contains(seedURI)) { - results.add(seedURI); - } - addedEA = true; - } - } - - // Next loop we use the next most preferred address. - eaIndex++; - } while (addedEA); - - return results.toArray(new URI[results.size()]); - } - - /** - * {@inheritDoc} - */ - public synchronized RouteAdvertisement[] getActiveSeedRoutes() { - refreshActiveSeeds(); - - List results = new ArrayList(); - - for( RouteAdvertisement eachRoute : discoveredRoutes ) { - if(!results.contains(eachRoute)) { - results.add(eachRoute); - } - } - - return results.toArray(new RouteAdvertisement[results.size()]); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ResourceAccount.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ResourceAccount.java deleted file mode 100644 index b505ebbe..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ResourceAccount.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -/** - * A descriptor for a resource consumser. The resource consumer's resource - * allocation and dynamic usage is tracked. - */ -public interface ResourceAccount { - - /** - * Tear down this account. - * Releases all reserved resources. - */ - public void close(); - - /** - * Try and grant a new item to this account. If it cannot be done, - * the account may be eligible for the next available extra item. - * The account is automatically set to be in need, as if inNeed(true) - * has been invoked. - * - * @return boolean true if an item was granted, false otherwise. - */ - public boolean obtainItem(); - - /** - * Try and grant a certain quantity. - * - *

            It is useful to manage the allocation of variable sized aggregates - * when what matters is the cummulated quantity rather than an item - * count. Quantity could be a number of bytes needed to store - * something for example. The advantage of using this method rather - * than obtainItem repeatedly is that it is obvisouly faster if - * quantity is more than one or two, and also that it is atomic; - * the entire quantity is either granted or denied. - * Using this routine is by definition incompatible with the round-robin - * mode, which could only re-assign quantities of 1. - * - *

            It is legal to use this routine along with round-robin mode if the - * same dispatcher is used to manage quantities of 1 in this manner, - * but an account that has failed to obtain its desired quantity is - * not queued for later re-assignment. And items released with - * releaseQuantity() are not re-assigned, so overall it is - * probably best to not mix the two. - * - * @param quantity The number of units wanted. The unit is arbitrary - * It is only meaningfull to the code that uses this dispatcher. - * @return boolean whether the requested quantity is authorized. - */ - public boolean obtainQuantity(long quantity); - - /** - * This will release an item and return the most eligible account to - * re-use this item for. The account that is returned has been granted - * the item and thus the invoker is expected to do with this account - * whatever an invoker of obtainItem() would do in case of success. - * If the items that are managed are threads, the invoker is - * likely to be one these threads and it should therefore process - * the returned account as it did the one for which it was calling - * releaseItem, however be very carefull not to process the new account - * in the context of the old one; that would rapidly lead to stack - * overflow. In other words, be carefull of not making a construct - * equivalent to: - * - *

            -     * process() {
            -     *   doStuff();
            -     *   myAccount.releaseItem().getUserObject().process();
            -     * }
            -     * 
            - * - * That won't work. Instead do: - * - *

            -     * work() {
            -     *  while (myAccount != null) {
            -     *   myAccount.getUserObject().doStuff();
            -     *   myAccount = myAccount.releaseItem();
            -     *  }
            -     * }
            -     * 
            - * - *

            Or similar; always go back to base stack level. - * It is mandatory to handle accounts returned by {@code releaseItem()}. - * If handling leads to releaseItem, then it has to be done in a - * forever loop. That is typical if the items are threads. - * That is normally not happening if the items are only memory. - * - * @return ResourceAccount the account to which the released item - * has been re-assigned. null if the released item was not re-assigned. - */ - public ResourceAccount releaseItem(); - - /** - * This will release a number of items at once rather than - * once. To be used in conjunctino with obtainItems(). See that - * method. - * - * @param quantity the number of items to be released. - */ - public void releaseQuantity(long quantity); - - /** - * Call this with true as soon as this account needs a new item. - * Call this with false as soon as this account has all that it needs. - * For proper operation, this must be done. - * - * @param needs Whether the account needs a new item or not. - */ - public void inNeed(boolean needs); - - /** - * @return Object The userObject that was supplied when creating the - * account. - */ - public Object getUserObject(); - - /** - * Set the userObject associated with that account. - */ - public void setUserObject(Object obj); - - /** - * Returns the number of reserved items that can still be obtained by - * this account. - * - *

            If that number is negative or zero, it means that all reserved - * items are currently in use. Still more items might still be obtained - * from the extra items pool. - * - * @return long The number of reserved items. - */ - public long getNbReserved(); - - /** - * Tells if this account is idle (that is, none of the resources - * that it controls are currently in use). This means it can be closed - * safely. - */ - public boolean isIdle(); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ResourceDispatcher.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ResourceDispatcher.java deleted file mode 100644 index 019ce2d0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/ResourceDispatcher.java +++ /dev/null @@ -1,722 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.util.LinkedList; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.impl.util.ResourceAccount; - - -/** - * This class does not in itself allocate anything; it just does accounting. - * Its role is to make sure that resource consumers ("accounts") - * are guaranteed to be able to hold a pre-determined number of items, - * the extra being granted on a first-come-first-serve basis. - * It just replies yes/no to an account that wants to allocate an item. - * Synchronization is external. - * - *

            Note that this is all essentially a limiter device. It assumes - * that the resources that are dispatched in that way are not otherwise - * in short supply. - * - *

            The rules of the game are as follows: - *

            At initialization, an absolute maximum authorized number of items - * is computed. All item reservations and authorizations are done - * within this budget. - *

            At any given point in time, out of this maximum, a number of items are - * permanently reserved for the minimum guaranteed to each current account, - * a number of items are set aside for future accounts guarantee reservation, - * and the rest is open for dynamic attribution on a first come first serve - * basis. - * - *

            The current strategy is as follows: - * - * The initialization parameters are:

              - *
            • minimum number of guaranteed accounts: {@code minAccounts}
            • - *
            • minimum commitment to new accounts up to minAccounts: {@code minReserve}
            • - *
            • maximum commitment to new accounts: {@code maxReserve}
            • - *
            • extra number of dynamically allocatable items: {@code extraItems}
            • - *
            - * - *

            We infer the number of items dedicated to reservation: {@code reservedItems} - * That is {@code minReserve * minAccounts}. - * - *

            Accounts can ask for a commitment in excess of minReserve. Any reservation - * made by an account beyond the minimum is satisfied from extraItems - * limited by what's available and maxReserve. When minAccounts have - * registered, it is possible that reservedItems is exhausted. New accounts - * are then accepted on a best effort basis using extra items exclusively. This - * may cause such new accounts to be given a commitment inferior to minReserve, - * including zero. It is up to the account to reject the offer and give up - * by closing, or to go along with the offer. At this time, we do not try - * to raise the commitment made to an account while it is registered. - * - *

            During the life of the account, items are allocated first from the set - * reserved by this account. If the account is out of reserved items, an attempt - * is made at getting the item from extraItems. - * - *

            For each account we count the number of items reserved from reservedItems, - * reserved from extraItems, allocated from the local reserved items - * and allocated from extraItems separately. When an item is released, it is - * accounted to extraItems if the account had anything allocated from - * extra items, or to the local reserved items. - * When an account goes away, the number of items that were reserved from - * reserveItems go back to reserveItems and likewise for those coming - * from extraItems. This is done rather than giving priority to reserve - * items so that the system does not favor reservation beyond its initial - * parameters when an account goes away under load. - * - *

            When resources are scarce, two modes of operations are available. - *

            - *
            Unfair
            - *
            each account keeps its items as long it has a use for them. If - * the allocation of a new item is denied for an account, the account just has - * to live with it and try again the next time more items are desired. - *
            - *
            RoundRobin
            - *
            Each account releases each item after one use. When allocation - * of a new item is denied for an account by reason of item shortage, the - * account is placed on a list of eligible accounts. Every time an item is - * released, it is re-assigned to the oldest eligible account. - *
            - *
            - *

            From an API point of view the difference is not visible: account users - * are advised to release items after one use. Release returns the account to - * which the item has been re-assigned. If RoundRobin is not used, then - * the item is always re-assigned to the account that releases it unless it - * is not needed, in which case it returns to the available pool. - * So, with round-robin off the following is true: - *

            - * a.releaseItem() == (a.needs ? a : null);
            - * 
            - */ - -public class ResourceDispatcher { - - /** - * Logger - */ - private final static transient Logger LOG = Logger.getLogger(ResourceDispatcher.class.getName()); - - private long extraItems; - private long reservedItems; - private final long maxReservedPerAccount; - private final long minReservedPerAccount; - private final long maxExtraPerAccount; - private final long minExtraPoolSize; - private int nbEligibles; - - private final String myName; - - class ClientAccount extends Dlink implements ResourceAccount { - - /** - * Tells whether this account has any use for extra resources - * or not. This feature is required to support roundRobin mode - * properly when resources are scarce. - */ - private boolean needs; - - /** - * The number of items reserved for this account that may still be - * allocated. This decrements when we grant an item allocation. When - * it is <= 0, new items may be obtained from extraItems. If obtained - * we still decrement. When an item is released, if this counter is - * < 0 we return the item to extra items. This counter gets - * incremented either way. - */ - private long nbReserved; - - /** - * The number out of nbReserved that is due back in reservedItems - * when this account disappears. - * The rest goes back to extraItems. - * NOTE: If we go away with items unaccounted for, we take the option - * of accounting them as allocated. In other words, that amount is - * not returned to its right full item account. That's why we do not - * need to keep track of allocated items. The leak is felt - * by this allocator. Alternatively we could pretend that the - * leaked resources are not ours; but that might break the actual - * allocator of the resource if it relies on our accounting. - */ - private long fromReservedItems; - - /** - * Same idea but they have been reserved by reducing the number - * of extra items available. - */ - private final long fromExtraItems; - - /** - * The limit for extra items allocation. - * When nbReserved is at or below that, extra items cannot be - * granted. - */ - private final long extraLimit; - - /** - * The external object for which this account manages items. - * This is an opaque cookie to us. Whatever code invokes - * releaseItem knows what to do with it and the re-assigned item, but - * it needs to be told which of its own object got an item assigned. - */ - private Object userObject; - - /** - * Creates a client account with this resource manager. - * Not for external use. - * @param fromReservedItems - * @param fromExtraItems - * @param extraLimit - * @param userObject - */ - ClientAccount(long fromReservedItems, long fromExtraItems, long extraLimit, Object userObject) { - - this.nbReserved = fromReservedItems + fromExtraItems; - this.fromReservedItems = fromReservedItems; - this.fromExtraItems = fromExtraItems; - this.extraLimit = -extraLimit; - this.userObject = userObject; - this.needs = false; - } - - /** - * {@inheritDoc} - * - *

            To accelerate return of resources to the global pool, one - * may call close() explicitly. Otherwise it is called by - * {@code finalize}. - * - *

            Calling close() or letting the account be GC'ed while some of the - * resources have not been returned is an error, may create a leak and - * may display a warning message. - */ - public void close() { - notEligible(); - userObject = null; - - if ((nbReserved == 0) && (fromReservedItems == 0) && (fromExtraItems == 0)) { - return; - } - - if (nbReserved < (fromReservedItems + fromExtraItems)) { - // !!! someone just gave up on its resource controller - // without returning the resources ! - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("An account was abandoned with resources still allocated."); - } - - // Release whatever we can. - if (nbReserved >= fromReservedItems) { - releaseExtra(nbReserved - fromReservedItems); - releaseReserved(fromReservedItems); - } else if (nbReserved > 0) { - releaseReserved(nbReserved); - } - - } else { - releaseReserved(fromReservedItems); - releaseExtra(fromExtraItems); - } - - nbReserved = 0; - } - - /** - * {@inheritDoc} - * - *

            Will close the account. (close is idempotent). - */ - @Override - protected void finalize() throws Throwable { - close(); - - super.finalize(); - } - - /** - * {@inheritDoc} - */ - public boolean isIdle() { - return (nbReserved == fromExtraItems + fromReservedItems); - } - - public boolean isEligible() { - return isLinked(); - } - - /** - * Put that account in the queue of accounts eligible to - * receive a resource when one becomes available. - */ - public void beEligible() { - if ((eligibles != null) && !isEligible()) { - newEligible(this); - } - } - - /** - * Remove that account from the queue of accounts eligible to - * receive a resource when one becomes available. - */ - public void notEligible() { - if ((eligibles != null) && isEligible()) { - unEligible(this); - } - } - - // An extra item is being granted to this account (by being reassigned - // from another account upon release). - private void granted() { - - // In theory, there cannot be an account that should NOT be granted - // an item in the eligibles list. For now, check whether the theory - // survives observations. - // It could happen that the need flag was turned off while this - // account was in the eligible list. That's not realy a problem. - // Either it will be released immediately, or we could filter - // it in mostEligible(). - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - if (nbReserved <= extraLimit) { - LOG.warning("An account that should not get an item was found in the eligibles list"); - } - } - - --nbReserved; - - // We've been assigned an item. No-longer eligible. - notEligible(); - } - - /** - * {@inheritDoc} - */ - public boolean obtainQuantity(long quantity) { - - if ((nbReserved - quantity) < extraLimit) { - // That's asking too much. Denied. - return false; - } - - if (quantity > nbReserved) { - // We need to get some or all of it from the extra items. - long toAsk = nbReserved > 0 ? quantity - nbReserved : quantity; - long res = holdExtra(toAsk); - - if (res != toAsk) { - // Could not get enough. We got nothing. - releaseExtra(res); - return false; - } - } - - // Now record it. - nbReserved -= quantity; - - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - if (nbReserved > fromReservedItems + fromExtraItems) { - LOG.severe("Incorrect values after obtaining " + quantity + " : [" + this + "]"); - } - } - - return true; - } - - /** - * {@inheritDoc} - */ - public boolean obtainItem() { - - // Set it for consistency. It will get cleared when - // the item is used to satisfy the need. - needs = true; - - if (nbReserved > 0) { - notEligible(); - --nbReserved; - return true; // Its pre-reserved. - } - - // This account may deliberately limit the number of extra - // items it uses. this translates into a lower limit for - // nbReserved when <= 0. - if (nbReserved <= extraLimit) { - notEligible(); - return false; - } - - if (holdExtra(1) == 1) { // Need authorization. - notEligible(); - --nbReserved; - return true; - } - - // We are out of luck but eligible. - beEligible(); - return false; - } - - /** - * {@inheritDoc} - */ - public void releaseQuantity(long quantity) { - if (nbReserved < 0) { - releaseExtra(quantity < -nbReserved ? quantity : -nbReserved); - } - nbReserved += quantity; - if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { - if (nbReserved > fromReservedItems + fromExtraItems) { - LOG.severe("Incorrect values after releasing " + quantity + " : [" + this + "]"); - } - } - } - - /** - * {@inheritDoc} - */ - public ResourceAccount releaseItem() { - if (nbReserved < 0) { - if (eligibles == null) { - // RoundRobin is OFF either we reuse it or we let - // it go. - if (needs) { - return this; - } - - ++nbReserved; - releaseExtra(1); - return null; - } - - // RoundRobin is ON, we compete with others for this item. - ++nbReserved; - - // Update our eligibility which depends on extraLimit and - // whether we have a use for the item or not. - if ((nbReserved > extraLimit) && needs) { - beEligible(); - } - - ClientAccount next = mostEligible(); - - if (next == null) { - releaseExtra(1); // noone wants it. return to main pool - } else { - next.granted(); - } - return next; - } - - // Since we are (back) in our reserved range, we can't be eligible - // for extra. - notEligible(); - - // In reserved range; we keep using the item if we need it. - if (needs) { - return this; - } - - ++nbReserved; - return null; - } - - /** - * {@inheritDoc} - */ - public void inNeed(boolean needs) { - this.needs = needs; - if ((nbReserved < 0) && (nbReserved > extraLimit) && needs) { - beEligible(); - } else { - notEligible(); - } - } - - /** - * {@inheritDoc} - */ - public Object getUserObject() { - return userObject; - } - - /** - * {@inheritDoc} - */ - public void setUserObject(Object object) { - userObject = object; - } - - /** - * {@inheritDoc} - */ - public long getNbReserved() { - return nbReserved; - } - - /** - * {@inheritDoc} - * - *

            Returns some human-readable status and identity information useful for debugging. - */ - @Override - public String toString() { - return super.toString() + " : needs=" + needs + " nbReserved=" + nbReserved + " fromReservedItems=" - + fromReservedItems + " fromExtraItems=" + fromExtraItems + " extraLimit=" + extraLimit; - } - - } - - /** - * The list of eligible accounts. - */ - private Dlist eligibles; - - /** - * Construct a Fair Resource Allocator with the given parameters: - * @param minAccounts The minimum number of client accounts that we want to - * guarantee we can handle. <0 means 0 - * - * @param minReservedPerAccount The minimum reservation request that we will - * always grant to accounts as long as we have less than minAccounts <0 means - * 0. - * @param maxReservedPerAccount The maximum reservation request that we ever - * will grant to any given account. extraItems means ==extraItems. - * @param minExtraPoolSize The number of extra items that can never be - * taken out of the extra pool to satisfy a reservation request. - * @param roundRobin If true, when there is no items available, all - * eligible accounts are put in a FIFO. Accounts release items often, and the - * oldest account in the FIFO will get it. If false, accounts always keep - * items for as long as they can use them, and there is no FIFO of eligible - * accounts. Accounts can obtain new resources only if available at the time - * they try to aquire it. RoundRobin is more fair but has more overhead. - * Neither mode will cause starvation as long as accounts reserve at least - * one item each. RoundRobin is most useful when allocating threads. - */ - public ResourceDispatcher(long minAccounts, long minReservedPerAccount, long maxReservedPerAccount, long extraItems, long maxExtraPerAccount, long minExtraPoolSize, boolean roundRobin, String dispatcherName) { - if (minAccounts < 0) { - minAccounts = 0; - } - if (minReservedPerAccount < 0) { - minReservedPerAccount = 0; - } - if (maxReservedPerAccount < minReservedPerAccount) { - maxReservedPerAccount = minReservedPerAccount; - } - if (extraItems < 0) { - extraItems = 0; - } - if (minExtraPoolSize < 0) { - minExtraPoolSize = 0; - } - - if ((maxExtraPerAccount < 0) || (maxExtraPerAccount > extraItems)) { - maxExtraPerAccount = extraItems; - } - - this.extraItems = extraItems; - this.minExtraPoolSize = minExtraPoolSize; - this.maxReservedPerAccount = maxReservedPerAccount; - this.minReservedPerAccount = minReservedPerAccount; - this.reservedItems = minAccounts * minReservedPerAccount; - this.maxExtraPerAccount = maxExtraPerAccount; - nbEligibles = 0; - if (roundRobin) { - eligibles = new Dlist(); - } - - this.myName = dispatcherName; - } - - private long holdReserved(long req) { - if (req > reservedItems) { - req = reservedItems; - } - reservedItems -= req; - return req; - } - - private void releaseReserved(long nb) { - reservedItems += nb; - } - - private long holdExtra(long req) { - if (req > extraItems) { - req = extraItems; - } - extraItems -= req; - return req; - } - - // Get items from the extra pool but only if there is at least - // minExtraPoolSize item - // left after that. The goal is to make sure we keep at least one - // un-reserved item when granting reserved items from the extra pool. - // Thanks to that, even accounts that could not get a single reserved - // item still stand a chance to make progress by taking turns using - // the one extra item left. - private long holdExtraKeepSome(long req) { - if (extraItems <= minExtraPoolSize) { - return 0; - } - long allowed = extraItems - minExtraPoolSize; - - if (req > allowed) { - req = allowed; - } - extraItems -= req; - return req; - } - - private void releaseExtra(long nb) { - extraItems += nb; - } - - private void newEligible(ClientAccount account) { - ++nbEligibles; - eligibles.putLast(account); - } - - private ClientAccount mostEligible() { - if (nbEligibles == 0) { - return null; - } - return (ClientAccount) eligibles.getFirst(); - } - - private void unEligible(ClientAccount account) { - --nbEligibles; - account.unlink(); - } - - // Not synch; it's just a snapshot for trace purposes. - public int getNbEligibles() { - return nbEligibles; - } - - /** - * Creates and returns a new client account. - * - * @param nbReq the number of reserved items requested (may not be - * always granted in full). A negative value is taken to mean 0. - * @param maxExtra the number of additional items that this account - * authorizes to be allocated in addition to the reserved ones. This - * is typically useful if the items are threads and if some accounts - * are not re-entrant. Then nbReq would be 1 and maxExtra would be 0. - * It is also permitted to have some accounts receive no items at all - * ever by setting nbReq and maxExtra both to zero. A negative maxExtra - * is taken as meaning no specified limit, in which case an actual limit - * may be set silently. - * @param userObject An opaque cookie that the account object will return - * when requested. This is useful to relate an account returned by - * ClientAccount.releaseItem() to an invoking code relevant object. - * @return ResourceAccount An account with this allocator. - */ - public ResourceAccount newAccount(long nbReq, long maxExtra, Object userObject) { - - long extra = 0; // reserved from extra pool - long reserved = 0; // reserved from reserved pool - - if (nbReq > maxReservedPerAccount) { - nbReq = maxReservedPerAccount; - } - - // Anything beyond the minimum comes from extra items if there's - // enough. - if (nbReq > minReservedPerAccount) { - extra = holdExtraKeepSome(nbReq - minReservedPerAccount); - nbReq = minReservedPerAccount; - } - - // Then the minimum comes from reserved items, if we can. - reserved = holdReserved(nbReq); - nbReq -= reserved; - - // If there's some letf to be had, it means that we're getting - // short on reserved items, we'll try to compensate by getting - // more items from extra, but the app should start getting rid - // of stale accounts if it can. - if (nbReq > 0) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Accepting extra account on a best effort basis."); - } - - extra += holdExtraKeepSome(nbReq); - if (extra + reserved < minReservedPerAccount) { - // Even that was not enough to reach our minimal commitment. - // The app should realy consider some cleanup. - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("[" + myName + "] Accepting extra account with below-minimal commitment:[" + userObject + "]"); - } - } - } - - if ((maxExtra > maxExtraPerAccount) || (maxExtra < 0)) { - maxExtra = maxExtraPerAccount; - } - - return new ClientAccount(reserved, extra, maxExtra, userObject); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/SeedingManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/SeedingManager.java deleted file mode 100644 index e9b20319..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/SeedingManager.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) 2002-2004 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Random; -import java.util.Set; -import java.util.SortedSet; -import java.util.Timer; -import java.util.TimerTask; -import java.util.TreeSet; - -import java.io.IOException; -import java.io.File; -import java.net.URISyntaxException; -import java.util.NoSuchElementException; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Attribute; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.endpoint.EndpointListener; -import net.jxta.endpoint.EndpointService; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.MessageTransport; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.endpoint.TextDocumentMessageElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.PeerGroup; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.PipeID; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.protocol.AccessPointAdvertisement; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.protocol.RdvAdvertisement; -import net.jxta.protocol.RouteAdvertisement; -import net.jxta.rendezvous.RendezvousEvent; -import net.jxta.rendezvous.RendezvousListener; - -import net.jxta.impl.access.AccessList; -import net.jxta.impl.endpoint.relay.RelayClient; -import net.jxta.impl.protocol.RdvConfigAdv; -import net.jxta.impl.rendezvous.RendezVousServiceImpl; -import net.jxta.impl.util.TimeUtils; - - -/** - * Manages the location of seed peers. - */ -public interface SeedingManager { - - /** - * Stop this seeding manager. - */ - public void stop(); - - /** - * Returns the route advertisements of the active seed peers. The route - * advertisements are returned in the order which the consumer should - * attempt to contact the seed peers. In some cases the returned route - * advertisements may omit the destination {@code PeerID} if it is not - * known. - * - * @return The route advertisements of the active seed peers in the order - * in which the seed peers should be contacted. - */ - public RouteAdvertisement[] getActiveSeedRoutes(); - - /** - * Returns the {@code URI} of the endpoint addresses of the active seed - * peers. The {@code URI}s are returned in the order which the consumer - * should attempt to contact the seed peers. - * - *

            Using the endpoint address {@code URI}s is less optimal than using - * the route advertisements as there is no association between the - * potentially multiple message transport addresses referring to a single - * peer. - * - * @return The {@code URI}s of the active seed peers in the order - * in which the seed peers should be contacted. - */ - public URI[] getActiveSeedURIs(); - - /** - * Returns {@code true} if the provided peer advertisement is an acceptable - * peer as determined by the seeding manager. - * - * @param peeradv The {@code PeerAdvertisement} of the peer being tested. - */ - public boolean isAcceptablePeer(PeerAdvertisement peeradv); - - /** - * Returns {@code true} if the provided route advertisement is an acceptable - * peer as determined by the seeding manager. - * - * @param radv The {@code RouteAdvertisement} of the peer being tested. - */ - public boolean isAcceptablePeer(RouteAdvertisement radv); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/SequenceIterator.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/SequenceIterator.java deleted file mode 100644 index eec3b004..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/SequenceIterator.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import java.util.NoSuchElementException; - - -/** - * This class lets you combine a number of iterators. - */ -public class SequenceIterator implements Iterator { - - private Iterator iterators; - - private Iterator current = null; - - private Iterator previous = null; - - /** - * Creates a new instance of SequenceIterator - * - * @param iterators An iterator containing instances of Iterator. This - * iterator will iterate over all of the item in these iterators. - **/ - public SequenceIterator(Iterator iterators) { - this.iterators = iterators; - } - - /** - * Creates a new instance of SequenceIterator - **/ - public SequenceIterator(Iterator first, Iterator second) { - List iterators = new ArrayList(2); - - iterators.add(first); - iterators.add(second); - - this.iterators = iterators.iterator(); - } - - /** - * {@inheritDoc} - **/ - public boolean hasNext() { - - if ((null == current) || (!current.hasNext())) { - do { - if (!iterators.hasNext()) { - return false; - } - - current = (Iterator) iterators.next(); - } while (!current.hasNext()); - } - - return true; - } - - /** - * {@inheritDoc} - **/ - public Object next() { - if (!hasNext()) { - throw new NoSuchElementException("no next element"); - } - - previous = current; - return current.next(); - } - - /** - * {@inheritDoc} - **/ - public void remove() { - if (null == previous) { - throw new IllegalStateException("next() has not been called"); - } - - previous.remove(); - previous = null; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/TimeUtils.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/TimeUtils.java deleted file mode 100644 index 41c22921..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/TimeUtils.java +++ /dev/null @@ -1,439 +0,0 @@ -/* - * Copyright (c) 2002-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.util; - -/** - * Utilities for manipulating absolute and relative times and for accelerating - * and decelerating time for testing purposes. - *

            - * The "time warp" functionality is useful for debugging and is scoped to - * the class loader in which the TimeUtils class is loaded. - */ -public final class TimeUtils { - - /** - * Zero milliseconds (yes its redundant). - */ - public static final long ZEROMILLISECONDS = 0L; - - /** - * The number of milliseconds in a millisecond. (yes its redundant). - */ - public static final long AMILLISECOND = 1L; - - /** - * The number of milliseconds in a hundredth of a second. - */ - public static final long AHUNDREDTHOFASECOND = 10 * AMILLISECOND; - - /** - * The number of milliseconds in a tenth of a second. - */ - public static final long ATENTHOFASECOND = 100 * AMILLISECOND; - - /** - * The number of milliseconds in a second. - */ - public static final long ASECOND = 1000 * AMILLISECOND; - - /** - * The number of milliseconds in a minute. - */ - public static final long AMINUTE = 60 * ASECOND; - - /** - * The number of milliseconds in an hour. - */ - public static final long ANHOUR = 60 * AMINUTE; - - /** - * The number of milliseconds in a day. - */ - public static final long ADAY = 24 * ANHOUR; - - /** - * The number of milliseconds in a week. - */ - public static final long AWEEK = 7 * ADAY; - - /** - * The number of milliseconds in a fortnight (two weeks). - */ - public static final long AFORTNIGHT = 14 * ADAY; - - /** - * The number of milliseconds in the month of January. - */ - public static final long AJANUARY = 31 * ADAY; - - /** - * The number of milliseconds in the month of February in a non-leap year. - */ - public static final long AFEBRUARY = 28 * ADAY; - - /** - * The number of milliseconds in the month of February in a leap year. - */ - public static final long ALEAPFEBRUARY = 29 * ADAY; - - /** - * The number of milliseconds in the month of March. - */ - public static final long AMARCH = 31 * ADAY; - - /** - * The number of milliseconds in the month of April. - */ - public static final long ANAPRIL = 30 * ADAY; - - /** - * The number of milliseconds in the month of May. - */ - public static final long AMAY = 31 * ADAY; - - /** - * The number of milliseconds in the month of June. - */ - public static final long AJUNE = 30 * ADAY; - - /** - * The number of milliseconds in the month of July. - */ - public static final long AJULY = 31 * ADAY; - - /** - * The number of milliseconds in the month of August. - */ - public static final long ANAUGUST = 31 * ADAY; - - /** - * The number of milliseconds in the month of September. - */ - public static final long ASEPTEMBER = 30 * ADAY; - - /** - * The number of milliseconds in the month of October. - */ - public static final long ANOCTOBER = 31 * ADAY; - - /** - * The number of milliseconds in the month of November. - */ - public static final long ANOVEMBER = 30 * ADAY; - - /** - * The number of milliseconds in the month of December. - */ - public static final long ADECEMBER = 31 * ADAY; - - /** - * The number of milliseconds in a non-leap year. - */ - public static final long AYEAR = AJANUARY + AFEBRUARY + AMARCH + ANAPRIL + AMAY + AJUNE + AJULY + ANAUGUST + ASEPTEMBER - + ANOCTOBER + ANOVEMBER + ADECEMBER; - - /** - * The number of milliseconds in a leap year. - */ - public static final long ALEAPYEAR = AJANUARY + ALEAPFEBRUARY + AMARCH + ANAPRIL + AMAY + AJUNE + AJULY + ANAUGUST - + ASEPTEMBER + ANOCTOBER + ANOVEMBER + ADECEMBER; - - /** - * This odd little guy is for use in testing. it is applied anywhere the - * current time is used and allows modules which use timeutils to be tested - * through long (simulated) periods of time passing. - */ - static volatile long TIMEWARP = 0; - - /** - * Absolute time in millis at which we began timewarping. - */ - static long WARPBEGAN = 0; - - /** - * The rate at which time is warped using the auto-warper. - */ - static double WARPFACTOR = 1.0; - - /** - * Don't let anyone instantiate this class. - */ - private TimeUtils() { - } - - /** - * Return the current time. This value may differ from the value returned - * by {@link System#currentTimeMillis()} if the {@link #timeWarp(long)} or - * {@link #autoWarp(double)} features are being used. Using - * {@link #timeNow()} allows test harnesses to simulate long periods of - * time passing. - * - * @return The current time which has been possibly adjusted by a "time warp" - * factor. - */ - public static long timeNow() { - long now = System.currentTimeMillis(); - - if (WARPFACTOR != 1.0) { - long elapsed = now - WARPBEGAN; - - long dialation = (long) (elapsed * WARPFACTOR); - - TIMEWARP += (dialation - elapsed); - } - - return now + TIMEWARP; - } - - /** - * Convert a duration into a duration expressed in milliseconds to absolute - * time realtive to the current real time. Special handling for the maximum - * and minimum durations converts them to the maximum and minimum absolute - * times. - * - * @param duration a time duration expressed in milliseconds. - * @return an absolute time in milliseconds based on the duration's - * relation to the current real time. - */ - public static long toAbsoluteTimeMillis(long duration) { - - return toAbsoluteTimeMillis(duration, timeNow()); - } - - /** - * Convert a duration into a duration expressed in milliseconds to absolute - * time realtive to the provided absolute time. Special handling for the - * maximum and minimum durations converts them to the maximum and minimum - * absolute times. - * - * @param duration a time duration expressed in milliseconds. - * @param fromWhen an absolute time expressed in milliseconds. - * @return an absolute time in milliseconds based on the duration's - * relation to the provided absolute time. - */ - public static long toAbsoluteTimeMillis(long duration, long fromWhen) { - - // Special cases for the boundaries. - - if (Long.MAX_VALUE == duration) { - return Long.MAX_VALUE; - } - - if (Long.MIN_VALUE == duration) { - return Long.MIN_VALUE; - } - - long whence = fromWhen + duration; - - if (duration > 0) { - // check for overflow - if (whence < fromWhen) { - whence = Long.MAX_VALUE; - } - - } else { - // check for underflow - if (whence > fromWhen) { - whence = Long.MIN_VALUE; - } - } - - return whence; - } - - /** - * Convert an absolute real time in milliseconds to a duration relative - * to the current real time. Special handling for the maximum and minimum - * absolute times converts them to the maximum and minimum durations. - * - * @param whence an absolute real time expressed in milliseconds. - * @return a duration expressed in milliseconds relative to the current - * real time. - */ - public static long toRelativeTimeMillis(long whence) { - return toRelativeTimeMillis(whence, timeNow()); - } - - /** - * Convert an absolute real time in milliseconds to a duration relative - * to the specified absolute real time. Special handling for the maximum - * and minimum absolute times converts them to the maximum and minimum - * durations. - * - * @param whence An absolute real time expressed in milliseconds. - * @param fromWhen The base time in absolute real time expressed in - * milliseconds from which the relative time will be calculated. - * @return a duration expressed in milliseconds relative to the provided - * absolute time. - */ - public static long toRelativeTimeMillis(long whence, long fromWhen) { - // Special cases for the boundaries. - - if (Long.MAX_VALUE == whence) { - return Long.MAX_VALUE; - } - - if (Long.MIN_VALUE == whence) { - return Long.MIN_VALUE; - } - - return whence - fromWhen; - } - - /** - * Multiplies a duration in relative milliseconds by a multiplier while - * accounting for overflow and underflow of the magnitude value. - * - * @param duration a time duration expressed in milliseconds. - * @param multiplier a non-negative value which will be multiplied against - * the duration. - * @return a time duration expressed in milliseconds. - */ - public static long multiplyRelativeTimeMillis(long duration, long multiplier) { - if (multiplier < 0) { - throw new IllegalArgumentException("Only non-negative multipliers are allowed."); - } - - long result_mag = (Long.MIN_VALUE != duration) - ? Long.highestOneBit(Math.abs(duration)) + Long.highestOneBit(multiplier) - : Long.SIZE + Long.highestOneBit(multiplier); - long result = duration * multiplier; - - if (result_mag > (Long.SIZE - 1)) { - // over or underflowed - result = (duration < 0) ? Long.MIN_VALUE : Long.MAX_VALUE; - } - - return result; - } - - /** - * A utility for advancing the timewarp by the number of milliseconds - * specified. May not be used if you are also using {@link #autoWarp(double)}. - * - * @param advanceby Advance the timewarp by the number of milliseconds - * specified. - */ - public static void timeWarp(long advanceby) { - if (0 != WARPBEGAN) { - throw new IllegalStateException("auto time warping already initialized at warp factor " + WARPFACTOR); - } - - TIMEWARP += advanceby; - } - - /** - * A utility for automagically adjusting the time dialation of the - * time warp. - * - * @param warpfactor a decimal ratio at which artifical time will pass. - *

            - *

              - *
            • To have time pass at the rate of an hour every minute, initialize - * with: (double)(TimeUtils.ANHOUR / TimeUtils.AMINUTE).
            • - *
            • To have time pass at five times normal rate, initialize - * with: 5.0.
            • - *
            • etc.
            • - *
            - */ - public static void autoWarp(double warpfactor) { - if (0 != WARPBEGAN) { - throw new IllegalStateException("Auto time warping already initialized at warp factor " + WARPFACTOR); - } - - if (warpfactor <= 0.0) { - throw new IllegalArgumentException("Time should not stand still or run backwards. It's unnatural."); - } - - if (warpfactor != 1.0) { - WARPFACTOR = warpfactor; - WARPBEGAN = System.currentTimeMillis(); - } - } - - /** - * Return a relative time adjusted by the current warping factor. - * Needed for external methods which do not use {@link #timeNow()} such - * as {@link Object#wait(long)} and - * {@link java.net.Socket#setSoTimeout(int)}. - * - * @param initial The initial time value to "warp". - * @return The provided initial time adjusted by the current warping factor. - */ - public static long warpedRelativeTime(long initial) { - if (0 == initial) { - return 0; - } - - long adjusted = (long) (initial * WARPFACTOR); - - // Handle overflow and underflow - if (initial < 0) { - if (adjusted >= 0) { - adjusted = Long.MIN_VALUE; - } - } else { - if (adjusted < 0) { - adjusted = Long.MAX_VALUE; - } - } - - // since 0 is usually a special "wait forever" value we don't allow time - // to be reduced to zero because that would cause a change of behaviour - // in many cases. - return (0 != adjusted) ? adjusted : 1; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/TimerThreadNamer.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/TimerThreadNamer.java deleted file mode 100644 index d0f711af..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/TimerThreadNamer.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.util.TimerTask; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - - -/** - * A simple timer task who's sole purpose is to name the Thread on which timer - * tasks are running. You normally use it by : - * - *
            
            - *  Timer timer = new Timer();
            - *  timer.schedule( new TimerThreadNamer( "name for timer" ), 0 );
            - * 
            - * - * @deprecated Beginning with JSE 5.0 you may now name a Timer directly. - * - *

            Note that this implementation assumes the Timer implemntation found in - * Sun JDK 1.2-1.5 (and possibly later) in that there is a single thread - * attached to each Timer object. - **/ -@Deprecated -public class TimerThreadNamer extends TimerTask { - - private final static transient Logger LOG = Logger.getLogger(TimerThreadNamer.class.getName()); - - private boolean firstRun = true; - - private String nameToUse; - - /** - * Construct a Timer Thread Namer object - * - * @param useName The name which the timer thread will be given. - **/ - public TimerThreadNamer(String useName) { - nameToUse = useName; - - } - - /** - * {@inheritDoc} - **/ - @Override - public synchronized void run() { - - if (firstRun) { - Thread.currentThread().setName(nameToUse); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Naming TimerThread to : " + nameToUse); - } - nameToUse = null; - firstRun = false; - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/URISeedingManager.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/URISeedingManager.java deleted file mode 100644 index 835f95a8..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/URISeedingManager.java +++ /dev/null @@ -1,554 +0,0 @@ -/* - * Copyright (c) 2002-2004 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.text.MessageFormat; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; -import net.jxta.document.Attribute; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.MimeMediaType; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.endpoint.EndpointAddress; -import net.jxta.impl.endpoint.EndpointUtils; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.AccessPointAdvertisement; -import net.jxta.protocol.PeerAdvertisement; -import net.jxta.protocol.RouteAdvertisement; - - -/** - * A seeding manager that supports both explicit seed peers and loading of - * seeds from seeding resources. - */ -public class URISeedingManager extends RdvAdvSeedingManager { - - /** - * Logger - */ - private static final transient Logger LOG = Logger.getLogger(URISeedingManager.class.getName()); - - /** - * The minimum amount of time we will wait between attempts to resolve the - * seeding URI sources. - */ - private static final long MINIMUM_SEEDING_REFRESH_INTERVAL = 5 * TimeUtils.AMINUTE; - - /** - * The standard interval at which we will attempt to refresh from the - * seeding URI sources. Also the maximum we will wait between failed - * attempts. - */ - private static final long STANDARD_SEEDING_REFRESH_INTERVAL = 30 * TimeUtils.AMINUTE; - - /** - * Whether we are restricted to using seed rdvs only. - */ - private boolean allowOnlySeeds = false; - - /** - * These URIs specify location of seed peer lists. The URIs will be resolved - * via URLConnection and are assumed to refer to plain text lists of - * absolute URIs or an XML document containing a list of Route Advertisements. - */ - private final Set seedingURIs = new HashSet(); - - /** - * The absolute time in milliseconds after which we will attempt to refresh - * the active seeds list using the seeding URIs. - */ - private long nextSeedingURIrefreshTime = 0; - - /** - * The number of sequential failures we have encountered while loading - */ - private int failedSeedingLoads = 0; - - /** - * These are seed peers which were specified as part of the configuration - * data or programmatically. These seeds are never deleted. - */ - private final Set permanentSeeds = new HashSet(); - - /** - * The ranked list of active seed peers. The seed addresses are ranked as - * follows : - * - *

              - *
            1. The lists of seed addresses returned by reading from the seeding - * addresses in the order they were returned. The seeding addresses are - * processed in random order.
            2. - *
            3. The list of permanent seed addresses in random order.
            4. - *
            - * - * Consumers of the seed list should process the list in the order returned - * and not request a new list until they have exhausted all entries from - * the each returned lists or found an active seed. - */ - private final List activeSeeds = new ArrayList(); - - - /** - * Get an instance of URISeedingManager. - * - * @param aclLocation The location of the ACL file or {@code null} if no - * ACL file should be used. - * @param allowOnlySeeds If {@code true} then the only peers which are part - * of the seed peer set will be - */ - public URISeedingManager(URI aclLocation, boolean allowOnlySeeds, PeerGroup group, String serviceName) { - super(aclLocation, group, serviceName); - - this.allowOnlySeeds = allowOnlySeeds; - } - - /** - * {@inheritDoc} - */ - public void stop() { - super.stop(); - } - - /** - * Adds the specified URI to the list of permanent seeds. Even if - * {@code allowOnlySeeds} is in effect, this seed may now be used, as if it - * was part of the initial configuration. - * - * @param seed The URI of the seed peer. - */ - public synchronized void addSeed(URI seed) { - RouteAdvertisement ra = (RouteAdvertisement) - AdvertisementFactory.newAdvertisement(RouteAdvertisement.getAdvertisementType()); - AccessPointAdvertisement apa = (AccessPointAdvertisement) - AdvertisementFactory.newAdvertisement(AccessPointAdvertisement.getAdvertisementType()); - - ra.addDestEndpointAddress(new EndpointAddress(seed)); - - permanentSeeds.add(ra); - activeSeeds.add(ra); - } - - /** - * Adds the specified URI to the list of permanent seeds. Even if - * {@code allowOnlySeeds} is in effect, this seed may now be used, as if it - * was part of the initial configuration. - * - * @param seed The RouteAdvertisement of the seed peer. - */ - public synchronized void addSeed(RouteAdvertisement seed) { - permanentSeeds.add(seed.clone()); - activeSeeds.add(seed.clone()); - } - - /** - * Adds the specified URI to the list of seeding URIs. - * - * @param seeding The URI of the seeding list. - */ - public synchronized void addSeedingURI(URI seeding) { - seedingURIs.add(seeding); - - // Reset the refresh timer so that our new seeding URI will get used. - nextSeedingURIrefreshTime = TimeUtils.timeNow(); - } - - /** - * {@inheritDoc} - */ - public synchronized URI[] getActiveSeedURIs() { - List result = new ArrayList(); - - refreshActiveSeeds(); - - int eaIndex = 0; - boolean addedEA; - - do { - addedEA = false; - - for (RouteAdvertisement aRA : activeSeeds) { - List eas = aRA.getDest().getVectorEndpointAddresses(); - - if (eaIndex < eas.size()) { - String anEndpointAddress = eas.get(eaIndex); - - try { - result.add(new URI(anEndpointAddress)); - addedEA = true; - } catch (URISyntaxException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "bad address in route : " + anEndpointAddress, failed); - } - } - } - } - - // Next loop we use the next most preferred address. - eaIndex++; - } while (addedEA); - - // Add more primordial seeds. - if(!allowOnlySeeds) { - for(URI eachURI : Arrays.asList(super.getActiveSeedURIs())) { - if(!result.contains(eachURI)) { - result.add(eachURI); - } - } - } - - return result.toArray(new URI[result.size()]); - } - - /** - * {@inheritDoc} - */ - public synchronized RouteAdvertisement[] getActiveSeedRoutes() { - - refreshActiveSeeds(); - - List result = new ArrayList(activeSeeds); - - // Add more primordial seeds. - if(!allowOnlySeeds) { - for(RouteAdvertisement eachRoute : Arrays.asList(super.getActiveSeedRoutes())) { - if(!result.contains(eachRoute)) { - result.add(eachRoute); - } - } - } - - return result.toArray(new RouteAdvertisement[result.size()]); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized boolean isAcceptablePeer(PeerAdvertisement peeradv) { - RouteAdvertisement route = EndpointUtils.extractRouteAdv(peeradv); - - boolean acceptable = true; - - if (allowOnlySeeds) { - acceptable = isSeedPeer(route); - } - - if (!acceptable) { - return false; - } - - if (null != route) { - return isAcceptablePeer(route); - } else { - return acl.getGrantAll(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized boolean isAcceptablePeer(RouteAdvertisement radv) { - boolean acceptable = true; - - if (allowOnlySeeds) { - acceptable = isSeedPeer(radv); - } - - return acceptable && super.isAcceptablePeer(radv); - } - - private void refreshActiveSeeds() { - if (TimeUtils.timeNow() < nextSeedingURIrefreshTime) { - return; - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Regenerating active seeds list."); - } - - activeSeeds.clear(); - - if (!seedingURIs.isEmpty()) { - List allSeedingURIs = new ArrayList(seedingURIs); - boolean allLoadsFailed = true; - - Collections.shuffle(allSeedingURIs); - - for (URI aSeedingURI : allSeedingURIs) { - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Loading seeding list from : " + aSeedingURI); - } - - RouteAdvertisement ras[] = loadSeeds(aSeedingURI); - - for (RouteAdvertisement aRA : Arrays.asList(ras)) { - if (!activeSeeds.contains(aRA)) { - // Only add non-duplicates. - activeSeeds.add(aRA); - allLoadsFailed = false; - } - } - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Failed loading seeding list from : " + aSeedingURI); - } - } - } - - if (allLoadsFailed) { - // Allow for an early reload if we couldn't contact any of the - // seeding URIS. - failedSeedingLoads++; - long nextAttemptInterval = Math.min(MINIMUM_SEEDING_REFRESH_INTERVAL * failedSeedingLoads, - STANDARD_SEEDING_REFRESH_INTERVAL); - - nextSeedingURIrefreshTime = TimeUtils.toAbsoluteTimeMillis(nextAttemptInterval); - } else { - failedSeedingLoads = 0; - nextSeedingURIrefreshTime = TimeUtils.toAbsoluteTimeMillis(STANDARD_SEEDING_REFRESH_INTERVAL); - } - } - - // Add the (shuffled) permanent seeds at the last. - List asList = new ArrayList(permanentSeeds); - - Collections.shuffle(asList); - activeSeeds.addAll(asList); - } - - /** - * Evaluates if the given route corresponds to one of our seeds. This is - * to support the allowOnlySeeds flag. The test is not completely foolproof - * since our list of seeds is just transport addresses. We could be given a - * pve that exhibits an address that corresponds to one of our seeds but is - * fake. And we might later succeed in connecting to that peer via one - * the other, real addresses. As a result, allowOnlySeeds is *not* a - * security feature, just a convenience for certain kind of deployments. - * The remote peer's certificates should be examined in order to fully - * establish that it an appropriate peer. - */ - private boolean isSeedPeer(RouteAdvertisement route) { - List addrList = route.getDestEndpointAddresses(); - - ListIterator eachAddr = addrList.listIterator(); - - // convert each EndpointAddress to a URI to compare with seedHosts - while (eachAddr.hasNext()) { - EndpointAddress anAddr = (EndpointAddress) eachAddr.next(); - - eachAddr.set(anAddr.toURI()); - } - - addrList.retainAll(Arrays.asList(getActiveSeedURIs())); - - // What's left is the intersection of activeSeeds and the set of - // endpoint addresses in the given APA. If it is non-empty, then we - // accept the route as that of a seed host. - return (!addrList.isEmpty()); - } - - /** - * Load a list of seed peer RouteAdvertisements from the specified URI. - *

            - * Two formats are supported: - *

            - *
            TEXT
            - *
            A simple UTF-8 or US ASCII text file containing one seed - * endpoint address per line. These entries are converted into very - * simple {@code RouteAdvertisement}s.
            - *
            XML
            - *
            A simple XML file containing a sequence of seed - * {@code RouteAdvertisement}s. The seed advertisements may be ordered - * or unordered.
            - *
            - * - * @param seedingURI The intended source of the {@code RouteAdvertisement}s. - * @return The loaded {@code RouteAdvertisement}s. - * @throws IOException Thrown for errors encountered loading the seed - * RouteAdvertisements. - */ - static RouteAdvertisement[] loadSeeds(URI seedingURI) throws IOException { - boolean isXML; - URL seedingURL = seedingURI.toURL(); - URLConnection connection = seedingURL.openConnection(); - - connection.setDoInput(true); - InputStream is = connection.getInputStream(); - - // Determine if the input file is an XML document or a plain text list. - // If it is not XML then we assume it is text. - String content_type = connection.getContentType(); - MimeMediaType type; - - if (null == content_type) { - // If we couldn't get a content-type from the connection then let's - // try to get it from the URI path. - String name = seedingURI.getPath(); - int extIdx = name.lastIndexOf('.'); - int sepIdx = name.lastIndexOf('/'); - - if ((-1 != extIdx) && (extIdx > sepIdx)) { - String ext = name.substring(extIdx + 1); - - type = StructuredDocumentFactory.getMimeTypeForFileExtension(ext); - } else { - // Type is unknown. :-( - type = MimeMediaType.AOS; - } - } else { - type = new MimeMediaType(content_type); - } - - isXML = MimeMediaType.XML_DEFAULTENCODING.equalsIngoringParams(type) - || MimeMediaType.APPLICATION_XML_DEFAULTENCODING.equalsIngoringParams(type); - - BufferedReader seeds = new BufferedReader(new InputStreamReader(is)); - - List result = new ArrayList(); - - if (isXML) { - // Read in XML format seeds. (a list of Route Advertisements) - XMLDocument xmldoc = (XMLDocument) - StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XML_DEFAULTENCODING, seeds); - - Enumeration eachRA = xmldoc.getChildren(RouteAdvertisement.getAdvertisementType()); - - while (eachRA.hasMoreElements()) { - XMLElement anRAElement = eachRA.nextElement(); - RouteAdvertisement ra = (RouteAdvertisement) AdvertisementFactory.newAdvertisement(anRAElement); - - result.add(ra); - } - - boolean randomize = true; - - Attribute ordered = xmldoc.getAttribute("ordered"); - - if (null != ordered) { - randomize = !Boolean.valueOf(ordered.getValue()); - } - - if (randomize) { - Collections.shuffle(result); - } - } else { - // Read in plain text format seeds. A list of Endpoint Addresses - while (true) { - String aSeed = seeds.readLine(); - - if (null == aSeed) { - break; - } - - aSeed = aSeed.trim(); - - if (0 == aSeed.length()) { - continue; - } - - try { - URI validation = URI.create(aSeed); - EndpointAddress ea = new EndpointAddress(validation.toString()); - - RouteAdvertisement ra = (RouteAdvertisement) AdvertisementFactory.newAdvertisement( - RouteAdvertisement.getAdvertisementType()); - - ra.addDestEndpointAddress(ea); - - // Add the world's most pathetic RouteAdvertisement to the result. - result.add(ra); - } catch (IllegalArgumentException badURI) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "bad URI in seeding list : " + aSeed, badURI); - } - } - } - } - - is.close(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(MessageFormat.format("Loaded #{0} seeds from : {1}", result.size(), seedingURI)); - } - - return result.toArray(new RouteAdvertisement[result.size()]); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/UnbiasedQueue.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/UnbiasedQueue.java deleted file mode 100644 index 25b8a576..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/UnbiasedQueue.java +++ /dev/null @@ -1,875 +0,0 @@ -/* - * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util; - - -import java.util.ArrayList; -import java.util.List; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - -import net.jxta.impl.util.TimeUtils; - - -/** - * A generic queue class. This queue is explicitly NOT a synchronized queue. - * - *

            FIXME 20020511 bondolo@jxta.org This could be more efficient with a - * circular queue implementation, but its a pain to write since we allow the - * queue to be resizable. - * - *

            FIXME 20020511 bondolo@jxta.org Exercise for the reader: Extend this - * class so that it does both LIFO and FIFO. - * - *

            FIXME 20020910 bondolo@jxta.org Needs an optional listener callback - * for droppped elments. - * - *

            FIXME 20020910 bondolo@jxta.org Needs an optional "strategy" for - * element insertion and removal. - * - * @deprecated Please convert all code to use the java.util.concurrent BlockingQueue instead. - * - */ -@Deprecated -public class UnbiasedQueue { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(UnbiasedQueue.class.getName()); - - /** - * Default number of queue elements. - */ - protected static final int DEFAULT_MAX_OBJECTS = 100; - - /** - * Default object dropping behaviour - */ - protected static final boolean DROP_OLDEST_OBJECT = true; - - /** - * Number of milliseconds between notifications that objects are being dropped. - */ - protected static final long DROPPED_OBJECT_WARNING_INTERVAL = 10 * TimeUtils.ASECOND; - - /** - * Contains the objects we currently have queued. - */ - protected List queue = null; - - /** - * The maximum number of objects we will hold in the queue at one time. - */ - protected int maxObjects; - - /** - * If true the queue is being closed and is currently in the process of - * being flushed. All new "push" requests will be refused. - */ - protected volatile boolean closeFlag = false; - - /** - * When we need to drop objects, drop the oldest obj. - */ - protected boolean dropOldestObject = true; - - /** - * total number of objects which have been enqueued into this queue - */ - protected long numEnqueued = 0; - - /** - * sum of queue sizes at enqueue time. - */ - protected long sumOfQueueSizesEnqueue = 0; - - /** - * total number of objects which have been dequeued from this queue - */ - protected long numDequeued = 0; - - /** - * sum of queue sizes at dequeue time. - */ - protected long sumOfQueueSizesDequeue = 0; - - /** - * the number of objects we have dropped since we began working. - */ - protected long numDropped = 0; - - /** - * absolute time in millis when it will be ok to display a obj about - * dropping objects. We throttle this so that there is a chance to do work - * rather than just always spewing warnings. - */ - protected long nextDroppedWarn = 0L; - - /** - * An inner class for wrapping arbitrary queues with synchronization. - */ - protected static class SynchronizedQueue extends UnbiasedQueue { - UnbiasedQueue innerqueue; - - /** - * Constructs a SynchronizedQueue from an UnbiasedQueue - * instance. - */ - public SynchronizedQueue(UnbiasedQueue queue) { - innerqueue = queue; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isClosed() { - synchronized (innerqueue.queue) { - return innerqueue.isClosed(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void close() { - synchronized (innerqueue.queue) { - innerqueue.close(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void clear() { - synchronized (innerqueue.queue) { - innerqueue.clear(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean push(Object obj) { - synchronized (innerqueue.queue) { - return innerqueue.push(obj); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean pushBack(Object obj) { - synchronized (innerqueue.queue) { - return innerqueue.pushBack(obj); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean push(Object obj, long timeout) throws InterruptedException { - synchronized (innerqueue.queue) { - return innerqueue.push(obj, timeout); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean pushBack(Object obj, long timeout) throws InterruptedException { - synchronized (innerqueue.queue) { - return innerqueue.pushBack(obj, timeout); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Object peek() { - synchronized (innerqueue.queue) { - return innerqueue.peek(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Object pop() { - synchronized (innerqueue.queue) { - return innerqueue.pop(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Object pop(long timeout) throws InterruptedException { - synchronized (innerqueue.queue) { - return innerqueue.pop(timeout); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Object[] popMulti(int maxObjs) { - synchronized (innerqueue.queue) { - return innerqueue.popMulti(maxObjs); - } - } - - /** - * {@inheritDoc} - */ - @Override - public int getMaxQueueSize() { - synchronized (innerqueue.queue) { - return innerqueue.getMaxQueueSize(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void setMaxQueueSize(int maxObjs) { - synchronized (innerqueue.queue) { - innerqueue.setMaxQueueSize(maxObjs); - } - } - - @Override - public int getCurrentInQueue() { - synchronized (innerqueue.queue) { - return innerqueue.getCurrentInQueue(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public long getNumEnqueued() { - synchronized (innerqueue.queue) { - return innerqueue.getNumEnqueued(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public double getAvgInQueueAtEnqueue() { - synchronized (innerqueue.queue) { - return innerqueue.getAvgInQueueAtEnqueue(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public long getNumDequeued() { - synchronized (innerqueue.queue) { - return innerqueue.getNumDequeued(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public double getAvgInQueueAtDequeue() { - synchronized (innerqueue.queue) { - return innerqueue.getAvgInQueueAtDequeue(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public long getNumDropped() { - synchronized (innerqueue.queue) { - return innerqueue.getNumDropped(); - } - } - } - - /** - * Returns a synchronized (thread-safe) list backed by the specified queue. - * Most UnbiasedQueue subclasses are either unsynchronized or internally - * synchronized. If you need to do any atomic operations upon - * UnbiasedQueues (or subclasses) then this method should be used to - * "wrap" the queue with synchronization. - * - *

            In order to guarantee serial access, it is critical that all access - * to the backing queue is accomplished through the returned queue. - * - * @param queue the queue to be "wrapped" in a synchronized queue. - */ - public static UnbiasedQueue synchronizedQueue(UnbiasedQueue queue) { - return new SynchronizedQueue(queue); - } - - /** - * Default constructor. 100 element FIFO queue which drops oldest element - * when full. - */ - public UnbiasedQueue() { - this(DEFAULT_MAX_OBJECTS, DROP_OLDEST_OBJECT); - } - - /** - * Full featured constructor for creating a new UnBiasedQueue. - * - * @param maxsize Queue will not grow larger than this size. Use - * {@link java.lang.Integer#MAX_VALUE} for "unbounded" queue size. - * @param dropOldest Controls behaviour of element insertion when the - * queue is full. If true and the queue is full upon a - * {@link #push(Object) push} operation then the oldest element will be - * dropped to be replaced with the element currently being pushed. If - * false then the element will not be inserted if the queue is full. - */ - public UnbiasedQueue(int maxsize, boolean dropOldest) { - this(maxsize, dropOldest, new ArrayList()); - } - - /** - * Full featured constructor for creating a new UnBiasedQueue. - * - * @param maxsize Queue will not grow larger than this size. Use - * {@link java.lang.Integer#MAX_VALUE} for "unbounded" queue size. - * @param dropOldest Controls behaviour of element insertion when the - * queue is full. If true and the queue is full upon a - * {@link #push(Object) push} operation then the oldest element will be - * dropped to be replaced with the element currently being pushed. If - * false then the element will not be inserted if the queue is - * full. - * @param queue the List class instance to use. This does not need to be - * a synchronized list class. (and it works more effciently if it isn't). - */ - public UnbiasedQueue(int maxsize, boolean dropOldest, List queue) { - if (maxsize <= 0) { - throw new IllegalArgumentException("size must be > 0"); - } - - if (null == queue) { - throw new IllegalArgumentException("queue must be non-null"); - } - - maxObjects = maxsize; - this.queue = queue; - closeFlag = false; - - dropOldestObject = dropOldest; - } - - /** - * {@inheritDoc} - * - *

            A diagnostic toString implementation. - */ - @Override - public synchronized String toString() { - - return this.getClass().getName() + " :" + " size=" + getCurrentInQueue() + " capacity=" + getMaxQueueSize() + " enqueued=" - + getNumEnqueued() + " avgAtEnqueue=" + getAvgInQueueAtEnqueue() + " dequeued=" + getNumDequeued() - + " avgAtDequeue=" + getAvgInQueueAtDequeue(); - } - - /** - * Atomically return whether or not this queue has been closed. Closed - * queues will not accept "push" requests, but elements will still be - * returned with "pop". - * - * @return boolean indicating whether this queue has been closed. - */ - public boolean isClosed() { - return closeFlag; // closeFlag is volatile. - } - - /** - * Close the queue. This will prevent any further objects from being enqueued. - */ - public void close() { - closeFlag = true; - synchronized (queue) { - queue.notifyAll(); - } - } - - /** - * Flush the queue of all pending objects. - */ - public void clear() { - numDropped += queue.size(); - queue.clear(); - } - - /** - * Attempt to push an object onto the queue. If the queue is full then the - * object will not be pushed. This method does not use any synchronization - * and should not be used if other threads are using {@link #pop(long)} to - * retrieve elements. - * - * @param obj object to push - * @return true if the obj was pushed, otherwise false. - */ - public boolean push(Object obj) { - if (queue.size() >= maxObjects) { - return false; - } - - numEnqueued++; - sumOfQueueSizesEnqueue += queue.size(); - queue.add(obj); - - return true; - } - - /** - * Attempt to push an object back at the head the queue. If the queue is - * full then the object will not be pushed. This method does not use any - * synchronization and should not be used if other threads are using - * {@link #pop(long)} to retrieve elements. - * - * @param obj object to push - * @return true if the obj was pushed, otherwise false. - */ - public boolean pushBack(Object obj) { - if (queue.size() >= maxObjects) { - return false; - } - - numEnqueued++; - sumOfQueueSizesEnqueue += queue.size(); - queue.add(0, obj); - - return true; - } - - /** - * Push an object onto the queue. If the queue is full then the push will - * wait for up to "timeout" milliseconds to push the object. At the end of - * "timeout" milliseconds, the push will either return false or remove the - * oldest item from the queue and insert "obj". This behaviour is contolled - * by the constructor parameter "dropOldest". - * - * @param obj Object to be pushed onto the queue - * @param timeout Time in milliseconds to try to insert the item into a full - * queue. Per Java standards, a timeout of "0" (zero) will wait indefinitly. - * Negative values force no wait period at all. - * @return true if the object was intersted into the queue, otherwise false. - * @throws InterruptedException if the operation is interrupted before - * the timeout interval is completed. - */ - public boolean push(Object obj, long timeout) throws InterruptedException { - return push3(obj, timeout, false); - } - - /** - * Push an object back at the head of the queue. If the queue is full then - * the push will wait for up to "timeout" milliseconds to push the object. - * At the end of "timeout" milliseconds, the push will either return false - * or remove the oldest item from the queue and insert "obj". This behaviour - * is contolled by the constructor parameter "dropOldest". - * - *

            Timeout control is accomplished via synchronization and - * {@link Object#wait(long)}. {@link #pushBack(Object,long)} should only - * be used in conjunction with {@link #push(Object,long)} and - * {@link #pop(long)} - * - * @param obj Object to be pushed onto the queue - * @param timeout Time in milliseconds to try to insert the item into a full - * queue. Per Java standards, a timeout of "0" (zero) will wait indefinitly. - * Negative values force no wait period at all. - * @return true if the object was intersted into the queue, - * otherwise false. - * @throws InterruptedException if the operation is interrupted before - * the timeout interval is completed. - */ - public boolean pushBack(Object obj, long timeout) throws InterruptedException { - return push3(obj, timeout, true); - } - - private boolean push3(Object obj, long timeout, boolean atHead) throws InterruptedException { - if (null == obj) { - throw new AssertionError("obj is null"); - } - - if (null == queue) { - throw new AssertionError("queue is null"); - } - - if (0 == timeout) { - timeout = Long.MAX_VALUE; - } - - long absoluteTimeOut = TimeUtils.toAbsoluteTimeMillis(timeout); - - synchronized (queue) { - // this is the loop we stay in until there is space in the queue, - // the queue becomes closed or we get tired of waiting. - do { - // This queue is closed. No additional objects allowed. - if (isClosed()) { - queue.notify(); // inform someone who is waiting. we dont have to tell everyone though. - return false; - } - - if (queue.size() >= maxObjects) { - long waitfor = TimeUtils.toRelativeTimeMillis(absoluteTimeOut); - - if (waitfor > 0) { - queue.wait(waitfor); - - // something happened, we check again. - continue; - } - - // Queue is full but its time to do something. - // discard an element or simply return. - if (dropOldestObject) { - // Issue a warning if we have not done so recently. - long now = TimeUtils.timeNow(); - - if ((now > nextDroppedWarn) && Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Queue full, dropped one or more elements. Now dropped " + numDropped + " elements."); - nextDroppedWarn = now + DROPPED_OBJECT_WARNING_INTERVAL; - } - - if (atHead) { - // we have chosen to drop this element since it is - // the oldest. We can safely return true because we - // took the right action for this element. - - numEnqueued++; // one was queued. - numDropped++; // one was dropped. - // (happens they are the same) - - queue.notify(); // inform someone who is waiting. we dont have to tell everyone though. - return true; - } else { - // Due to queue resizing, we have have to drop more than - // one element - while (queue.size() >= maxObjects) { - numDropped++; - queue.remove(0); - } - } - } else { - queue.notify(); // inform someone who is waiting. we dont have to tell everyone though. - return false; - } - - } else { - break; - } - } while (!isClosed()); - - boolean pushed = (atHead ? pushBack(obj) : push(obj)); - - queue.notify(); // inform someone who is waiting. we dont have to tell everyone though. - return pushed; - } - } - - /** - * Return the next Object from the queue without removing it. - * - * @return Object, null if the queue is empty. - */ - public Object peek() { - Object result = null; - - if (queue.isEmpty()) { - return null; - } - - result = queue.get(0); - - return result; - } - - /** - * Remove and return the next Object from the queue. - * - * @return Object, null if the queue is empty. - */ - public Object pop() { - Object result = null; - - if (queue.isEmpty()) { - return null; - } - - sumOfQueueSizesDequeue += queue.size(); - numDequeued++; - - result = queue.remove(0); - - return result; - } - - /** - * Gets a Object from the queue. If no Object is immediately available, - * then wait the specified amount of time for an Object to be inserted. - * - * @param timeout Amount of time to wait in milliseconds for an object to - * be available. Per Java convention, a timeout of zero (0) means wait an - * infinite amount of time. Negative values mean do not wait at all. - * @return The next object in the queue. - * @throws InterruptedException if the operation is interrupted before - * the timeout interval is completed. - */ - public Object pop(long timeout) throws InterruptedException { - - if (0 == timeout) { - timeout = Long.MAX_VALUE; - } - - long absoluteTimeOut = TimeUtils.toAbsoluteTimeMillis(timeout); - - Object result = null; - - synchronized (queue) { - do { - - /* - * Because there may be more than one thread waiting on this - * queue, when we are woken up we do not necessarily get the - * next obj in the queue. In this case, rather than terminating - * because we didn't get the obj we resume waiting, but we - * ensure that we never wait longer than the amount of time - * which was originally requested. (if we fail to get the obj - * after being woken its actually a little less than the - * requested time) - */ - result = pop(); - - if (null != result) { - break; - } // we have an obj - - if (isClosed()) { // we didn't get one and its closed so there - break; - } // is no chance there will ever be one. - - long waitfor = TimeUtils.toRelativeTimeMillis(absoluteTimeOut); - - if (waitfor <= 0) { // there is no wait time left. - break; - } - - queue.wait(waitfor); - } while (!isClosed()); - - // wake someone else who might be waiting. This is apparently better - // than just letting the scheduler notice the synchro is no longer - // occupied. - queue.notify(); - } - - return result; - } - - /** - * Returns an array of objects, possibly empty, from the queue. - * - * @param maxObjs the maximum number of items to return. - * @return an array of objects, possibly empty containing the returned - * queue elements. - */ - public Object[] popMulti(int maxObjs) { - if (maxObjs <= 0) { - throw new IllegalArgumentException("maxObjs must be > 0"); - } - - maxObjs = Math.min(maxObjs, queue.size()); - Object[] result = new Object[maxObjs]; - - for (int eachElement = 0; eachElement < maxObjs; eachElement++) { - sumOfQueueSizesDequeue += queue.size(); - numDequeued++; - result[eachElement] = queue.remove(0); - } - - return result; - } - - /** - * How many objects will fit in this queue - * - * @return int indicating how many objects will fit in the queue. - */ - public int getMaxQueueSize() { - return maxObjects; - } - - /** - * Set how many objects this queue may store. Note that if there are more - * objects already in the queue than the specified amount then the queue - * will retain its current capacity. - * - * @param maxObjs The number of objects which the queue must be able to - * store. - */ - public void setMaxQueueSize(int maxObjs) { - maxObjects = maxObjs; - } - - /** - * Return the number of elements currently in the queue. This method is - * useful for statistical sampling, but should not be used to determine - * program logic due to the multi-threaded behaviour of these queues. - * - *

            You should use the return values and timeout behaviour of the - * {@link #push(Object)} and {@link #pop(long)} methods to regulate how you - * use the queue. - * - * @return the number of elements currently in the queue. Be warned that - * even two sequential calls to this method may return different answers - * due to activity on other threads. - */ - public int getCurrentInQueue() { - return queue.size(); - } - - /** - * Return the total number of objects which have been enqueued on to this - * queue during its existance. - * - * @return how many objects have been queued. - */ - public long getNumEnqueued() { - return numEnqueued; - } - - /** - * Return the average number of elements in the queue at Enqueue time. - * - * @return average number of elements which were in the queue at during all - * of the "push" operations which returned a "true" result. Does not - * include the item being pushed. If no elements have ever been enqueued - * then "NaN" will be returned. - */ - public double getAvgInQueueAtEnqueue() { - if (numEnqueued > 0) { - return (double) sumOfQueueSizesEnqueue / numEnqueued; - } else { - return Double.NaN; - } - } - - /** - * Return the total number of objects which have been dequeued from this - * queue during its existance. - * - * @return how many objects have been queued. - */ - public long getNumDequeued() { - return numDequeued; - } - - /** - * Return the average number of elements in the queue at dequeue time. - * - * @return average number of elements which were in the queue at during all - * of the "pop" operations which returned a non-null result. Includes the - * item being "pop"ed in the average. If no elements have ever been dequeued - * then "NaN" will be returned. - */ - public double getAvgInQueueAtDequeue() { - if (numDequeued > 0) { - return (double) sumOfQueueSizesDequeue / numDequeued; - } else { - return Double.NaN; - } - } - - /** - * Return the total number of objects which have been dropped by this queue - * during its existance. - * - * @return how many objects have been dropped. - */ - public long getNumDropped() { - return numDropped; - } - - public void interrupt() { - synchronized (queue) { - queue.notify(); - } - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/cm/DumpCm.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/cm/DumpCm.java deleted file mode 100644 index ee6564ab..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/cm/DumpCm.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.cm; - - -import net.jxta.impl.xindice.core.DBException; -import net.jxta.impl.xindice.core.data.Record; -import net.jxta.impl.xindice.core.data.Value; -import net.jxta.impl.xindice.core.filer.BTreeCallback; -import net.jxta.impl.xindice.core.filer.BTreeFiler; -import net.jxta.impl.xindice.core.indexer.IndexQuery; -import net.jxta.impl.xindice.core.indexer.NameIndexer; - -import java.io.DataInputStream; -import java.io.File; -import java.io.IOException; - - -/** - * A utility to dump the CM databases. - */ - -public class DumpCm { - - private static final IndexQuery ANY = new IndexQuery(IndexQuery.ANY, "*"); - - public interface DumpCmCallback { - void println(String val); - } - - public static void dump(String args[], DumpCmCallback callback) throws IOException { - String type = null; - String dir = null; - String file = null; - - for (int i = 0; i < args.length; i++) { - if (args[i].equals("-type") && i + 1 < args.length) { - type = args[++i]; - } else if (args[i].equals("-dir") && i + 1 < args.length) { - dir = args[++i]; - } else if (args[i].equals("-file") && i + 1 < args.length) { - file = args[++i]; - } else { - throw new IllegalArgumentException("Incorrect option"); - } - } - - if (callback == null) { - throw new IllegalArgumentException("No callback was provided."); - } - - if (type == null || dir == null || file == null) { - throw new IllegalArgumentException("Missing mandatory option"); - } - - if (type.equals("index")) { - dumpIndex(dir, file, callback); - } else if (type.equals("offsets")) { - dumpOffsets(dir, file, callback); - } else if (type.equals("db")) { - dumpDatabase(dir, file, callback); - } else { - throw new IllegalArgumentException("Incorrect type"); - } - } - - public static void dumpIndex(String dir, String file, DumpCmCallback callback) throws IOException { - NameIndexer indexer = new NameIndexer(); - - // remove the suffix if present (setLocation automatically adds it back) - final String SUFFIX = ".idx"; - - if (file.endsWith(SUFFIX)) { - file = file.substring(0, file.length() - SUFFIX.length()); - } - - indexer.setLocation(dir, file); - try { - if (!indexer.open()) { - throw new IOException("Failed to open index file " + dir + File.separator + file + SUFFIX); - } - callback.println("Index " + dir + File.separator + file + SUFFIX); - indexer.query(ANY, new IndexCallback(callback)); - } catch (DBException dbe) { - throw new IOException(dbe.getMessage()); - } - } - - private static final class IndexCallback implements BTreeCallback { - - private DumpCmCallback callback = null; - - public IndexCallback(DumpCmCallback callback) { - this.callback = callback; - } - - public boolean indexInfo(Value val, long pos) { - callback.println(pos + " \t " + val.toString()); - return true; - } - } - - public static void dumpOffsets(String dir, String file, DumpCmCallback callback) throws IOException { - BTreeFiler filer = new BTreeFiler(); - - // remove the suffix if present (setLocation automatically adds it back) - final String SUFFIX = ".tbl"; - - if (file.endsWith(SUFFIX)) { - file = file.substring(0, file.length() - SUFFIX.length()); - } - - filer.setLocation(dir, file); - try { - if (!filer.open()) { - throw new IOException("Failed to open offsets file " + dir + File.separator + file + SUFFIX); - } - callback.println("Offsets " + dir + File.separator + file + SUFFIX); - filer.query(ANY, new OffsetsCallback(filer, callback)); - } catch (DBException dbe) { - throw new IOException(dbe.getMessage()); - } - } - - private static final class OffsetsCallback implements BTreeCallback { - - private BTreeFiler filer = null; - private DumpCmCallback callback = null; - - public OffsetsCallback(BTreeFiler filer, DumpCmCallback callback) { - this.filer = filer; - this.callback = callback; - } - - public boolean indexInfo(Value val, long pos) { - Record record = null; - - try { - record = filer.readRecord(pos); - } catch (DBException dbe) { - callback.println("Error reading record: " + dbe.getMessage()); - } - - StringBuilder offsets = new StringBuilder(); - DataInputStream dis = null; - - if (record != null) { - dis = new DataInputStream(record.getValue().getInputStream()); - } - try { - int size = 0; - - if (dis != null) { - size = dis.readInt(); - } - for (int i = 0; i < size; i++) { - if (dis != null) { - offsets.append(Long.toString(dis.readLong())); - } - offsets.append(" "); - } - } catch (IOException ie) { - callback.println("Error reading record: " + ie.getMessage()); - } - - callback.println(pos + " \t " + val.toString() + "\n\t " + offsets.toString()); - return true; - } - } - - public static void dumpDatabase(String dir, String file, DumpCmCallback callback) throws IOException { - BTreeFiler filer = new BTreeFiler(); - - // remove the suffix if present (setLocation automatically adds it back) - final String SUFFIX = ".tbl"; - - if (file.endsWith(SUFFIX)) { - file = file.substring(0, file.length() - SUFFIX.length()); - } - - filer.setLocation(dir, file); - try { - if (!filer.open()) { - throw new IOException("Failed to open database file " + dir + File.separator + file + SUFFIX); - } - callback.println("Database " + dir + File.separator + file + SUFFIX); - filer.query(ANY, new DatabaseCallback(filer, callback)); - } catch (DBException dbe) { - throw new IOException(dbe.getMessage()); - } - } - - private static final class DatabaseCallback implements BTreeCallback { - - private BTreeFiler filer = null; - private DumpCmCallback callback = null; - - public DatabaseCallback(BTreeFiler filer, DumpCmCallback callback) { - this.filer = filer; - this.callback = callback; - } - - public boolean indexInfo(Value val, long pos) { - Record record = null; - - try { - record = filer.readRecord(pos); - } catch (DBException dbe) { - callback.println("Error reading record: " + dbe.getMessage()); - } - - if (record != null) { - callback.println(pos + " \t " + val.toString() + "\n" + record.getValue().toString()); - } - return true; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/package.html b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/package.html deleted file mode 100644 index 006640af..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/package.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - A collection of utility classes used by the JXTA implementation. These - utilities are not exposed in the public JXTA API because they are either - specific to the implementation or not specifically related to JXTA. - - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/AdaptiveFlowControl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/AdaptiveFlowControl.java deleted file mode 100644 index f460de78..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/AdaptiveFlowControl.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -import net.jxta.impl.util.TimeUtils; - - -public class AdaptiveFlowControl extends FlowControl { - - static final int DEFAULT_RWINDOW = 2; - - /** - * global state. - */ - private int MAX_TENSION = 3; - private int tension = 0; - private long nextRwinChange = TimeUtils.timeNow(); - private long prevAveRTT = 10 * TimeUtils.ASECOND; - private int RINGSZ = 8; - private long[] ackTimeRing = new long[RINGSZ]; - private int currAckRingOff = 0; - private int nbSamples = 0; - private long currAvePeriod = 1; - private long prevAvePeriod = 1; // not in use yet. - private long periodRangeSlow = Long.MAX_VALUE; // not in use, yet. - private long periodRangeFast = (periodRangeSlow / 3) * 2; - - /** - * Current recommended rwindow. - */ - private volatile int rwindow = 0; - - /** - * state of the currentAck being processed - */ - - // Accum of acked packets - private int numberACKed = 0; - - // Accum of missing packets - private int numberMissing = 0; - - // Time this ACK arrived - private long currACKTime = 0; - - // These variables are used to evaluate the longest run - // of consecutive holes in the sack list. That is consecutive - // seqnums from the retrQ that are not being acknowleged, - // followed by an acknowleged one. - private int prevHole = -2; - private int btbHoles = 0; - private int maxHoleRun = 0; - - /** - * Constructs an adaptive flow control module with an initial rwindow of - * DEFAULT_RWINDOW. - */ - public AdaptiveFlowControl() { - this(DEFAULT_RWINDOW); - } - - /** - * @param rwindow Use this value as the initial value (not recommended - * except for experimental purposes. - */ - public AdaptiveFlowControl(int rwindow) { - this.currACKTime = TimeUtils.timeNow(); - this.rwindow = rwindow; - } - - /** - * {@inheritDoc} - */ - @Override - public int getRwindow() { - return rwindow; - } - - /** - * {@inheritDoc} - */ - @Override - public void ackEventBegin() { - currACKTime = TimeUtils.timeNow(); - numberACKed = 0; - numberMissing = 0; - maxHoleRun = 0; - - // Note the currently open holerun carries over from the prev ACK. - // So, we leave prevHole and btbHoles alone. - } - - /** - * {@inheritDoc} - */ - @Override - public void packetACKed(int seqnum) { - if (btbHoles > maxHoleRun) { - maxHoleRun = btbHoles; - } - btbHoles = 0; - prevHole = -2; - numberACKed++; - } - - /** - * {@inheritDoc} - */ - @Override - public void packetMissing(int seqnum) { - - if (seqnum != prevHole + 1) { - // End of run, begining of next - if (btbHoles > maxHoleRun) { - maxHoleRun = btbHoles; - } - btbHoles = 0; - } - btbHoles++; - prevHole = seqnum; - numberMissing++; - } - - boolean fastMode = true; - int takeAchance = 0; - - /** - * {@inheritDoc} - */ - @Override - public int ackEventEnd(int rQSize, long aveRTT, long lastRTT) { - - // Compute average ack rate. If nothing was acked by this - // ack msg, consider it a bad sign as far as ack rates go: as good - // as no ack at all. - - // Even if a few ack messages where lost, the current event - // encapsulate all the acks we missed. Count each of them - // as one individual ack for the purpose of rate computation: - // we want to count the messages the other side has received - // not the number of ack messages that found their way back. - - if (numberACKed > 0) { - for (int a = 0; a < numberACKed; ++a) { - - // Adds a new sample to the ring. Returns the new average - // sample period. Once the ring is filled, the average is - // computed by substracting the sample at the current - // offset (the oldest) from the new sample that replaces - // it, and dividing by the ring size (10). During the - // first round, we use the first sample, so precision is - // poorer. - - long oldest = ackTimeRing[currAckRingOff]; - - if (nbSamples < RINGSZ) { - // make a fake (very) oldest sample if there is nothing yet. - if (nbSamples == 0) { - ackTimeRing[0] = currACKTime / 2; - } - ++nbSamples; - oldest = ackTimeRing[0]; - } - ackTimeRing[currAckRingOff++] = currACKTime; - if (currAckRingOff == RINGSZ) { - currAckRingOff = 0; - } - prevAvePeriod = currAvePeriod; - currAvePeriod = (currACKTime - oldest) / nbSamples; - } - } - - // Compute rwindow. It should keep oscillating around - // the best value. - // Up to a certain point, the higher we keep rwindow the more - // we keep all the bandwidth utilized. Beyond that point we have - // it just serves to create congestion. - - int oldSize = rwindow; - - if (TimeUtils.toRelativeTimeMillis(nextRwinChange) < 0) { - if (maxHoleRun < 4) { - - if (numberACKed > 0) { - - if (currAvePeriod < periodRangeFast) { - - // All is well: new rate record. We can - // push some more. and adjust the - // expected rate range towards speed. - - periodRangeFast = currAvePeriod; - periodRangeSlow = (periodRangeFast * 3) / 2; - - prevAveRTT = aveRTT; - - tension = 0; - - } else { - - // If rate is not up and RTT has - // increased by one inter-ack period or more - // since the last time we took the mark, it - // looks like one or more packet just had to - // wait its turn. So packets are being - // buffered, which does not do any - // good. Refrain from pushing under these - // conditions. Wait for a more favorable time. - - // This compares the change in RTT with the period - // and gives us a badness index from 0 to 10 * n - // Beyond 20 or so, we start getting worried. - // The hairy formula below compensates for non - // linearity of the rtt_diff/period ratio with - // period. The formulat compresses the scale towards - // a period of 0. There is no compression at a period - // of around 100 and maximum compression at 0. - // To make the index less sensitive for low periods, - // increase the compression ratio. - - int compressionRatio100 = 90; - int pivot = 100; - long period = currAvePeriod <= 0 ? 1 : currAvePeriod; - long backupSign = (10 * pivot * (aveRTT - prevAveRTT)) - / (pivot * period + Math.max((compressionRatio100 * (pivot * period - period * period)) / 100, 0)); - - if (backupSign > 18) { - - // if detect a speed increase, we'll reset our - // idea of the normal RTT for next time. But we - // will drop rwindow tension for now. - - rwindow--; - tension = MAX_TENSION; - - // The first time this happens, it's the end of fast - // mode. - fastMode = false; - - } else if ((backupSign < 1) && (currAvePeriod >= periodRangeSlow)) { - - if (tension >= MAX_TENSION) { - // May be we should give it another chance - // and nudge it just a little. On very lossy - // links we may end-up with no congestion - // at all but stuck at low speed because - // we have stopped believing in speed increase. - if (takeAchance++ > 10) { - takeAchance = 0; - tension--; - } - } - } else { - takeAchance = 0; - } - } - - if (tension < MAX_TENSION) { - tension++; - rwindow++; - } - - } else { - // Carefull, the other side did not ack anything - // it is stuck on a missing packet...better slow down - tension = MAX_TENSION; - } - - } else { - - // We saturated the pipe. We need to slow down - // arbitrarily without changing our idea of speed, - // so that the correlation between speed and - // rwindow is shifted towards a smaller - // rwindow. - - rwindow -= (MAX_TENSION + 1); - prevAveRTT = aveRTT; - tension = MAX_TENSION; - - // The first time this happens, it's the end of fast - // mode. - fastMode = false; - } - - if (rwindow > rQSize) { - rwindow = rQSize; - } - - if (rwindow < 2) { - rwindow = 2; - } - - if (oldSize != rwindow) { - if (fastMode && (tension < MAX_TENSION)) { - nextRwinChange = TimeUtils.toAbsoluteTimeMillis(lastRTT / 10); - } else { - nextRwinChange = TimeUtils.toAbsoluteTimeMillis(aveRTT * 2); - } - } - } - - return rwindow; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/Defs.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/Defs.java deleted file mode 100644 index 34f12d49..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/Defs.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -import net.jxta.document.MimeMediaType; - - -public final class Defs { - - public static final int MAXQUEUESIZE = 100; - - public static final String NAMESPACE = "jxtarel"; - - public static final String RETRY_ELEMENT_NAME = "retry"; - public static final String RETRY_ELEMENT_VALUE = "RETRY"; - - public static final String ACK_ELEMENT_NAME = "ack"; - - public static final MimeMediaType MIME_TYPE_MSG = MimeMediaType.valueOf("application/x-jxta-msg"); - - public static final MimeMediaType MIME_TYPE_BLOCK = MimeMediaType.valueOf("application/x-jxta-reliable-block"); - - public static final MimeMediaType MIME_TYPE_ACK = MimeMediaType.valueOf("application/x-jxta-reliable-ack"); - - /** - * Static class - */ - private Defs() {} -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/FixedFlowControl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/FixedFlowControl.java deleted file mode 100644 index ab92b138..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/FixedFlowControl.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -public class FixedFlowControl extends FlowControl { - - static final int DEFAULT_RWINDOW = 5; - int maxRwindow = 0; - int rwindow = 2; - - /** - * Constructs a fixed flow control module with a fixed rwindow of - * DEFAULT_RWINDOW. It is not completely fixed. It grows by one - * at every ack message until it reaches the set RWINDOW. - */ - public FixedFlowControl() { - this(DEFAULT_RWINDOW); - } - - /** - * @param rwindow Use the specified value as the constant rwindow - */ - public FixedFlowControl(int rwindow) { - this.maxRwindow = rwindow; - } - - /** - * {@inheritDoc} - */ - @Override - public int getRwindow() { - return rwindow; - } - - /** - * {@inheritDoc} - */ - @Override - public int ackEventEnd(int rQSize, long aveRTT, long lastRTT) { - if (rwindow < maxRwindow) { - ++rwindow; - } - return rwindow; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/FlowControl.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/FlowControl.java deleted file mode 100644 index b2562e1a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/FlowControl.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -/** - * A basis for any flow control module to be plugged into - * ReliableOutputStream. Synchronization can is assumed to be - * provided externaly. However all implementations are required to - * allow the getRwindow() method to be called at any time without - * synchronization. - */ - -public abstract class FlowControl { - - /** - * Returns the rwindow size that this flow control module suggests to use - * at this point in time. - * @return the remote window size - */ - public abstract int getRwindow(); - - /** - * Indicates that a new ack message is being processed. - */ - public void ackEventBegin() {} - - /** - * Invoked for each packet that is believed to have been received - * per the current ack message. - * - * @param seqnum The sequence number of the received packet. - */ - public void packetACKed(int seqnum) {} - - /** - * Invoked for each packet that is believed to have been lost - * per the current ack message. - * - * @param seqnum The sequence number of the missing packet. - */ - public void packetMissing(int seqnum) {} - - /** - * Concludes rwindow update for this ackEvent. That's where all the - * smarts are. A number of externally computed parameters must be - * passed. - * - * @param rQSize the last known value of the remote queue size. - * @param aveRTT the latest estimate of the average RTT. - * @param lastRTT the RTT inferred from the most recent ACK message. - * @return int the new recommended value for rwindow. - */ - - public abstract int ackEventEnd(int rQSize, long aveRTT, long lastRTT); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/Incoming.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/Incoming.java deleted file mode 100644 index 5c510cc4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/Incoming.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -import net.jxta.endpoint.Message; - - -/** - * Incoming messages are delivered to a class implementing - * this interface. - */ -public interface Incoming { - - /** - * Receive this incoming message. This method should - * return quickly. If the receiving class needs to do - * substantial work with incoming messages, it should - * insert this message into a queue and then drain the - * queue processing the messages in its own thread. - * @param msg the message - */ - void recv(Message msg); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/IncomingPipeAdaptor.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/IncomingPipeAdaptor.java deleted file mode 100644 index b0462cfa..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/IncomingPipeAdaptor.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - -import net.jxta.pipe.InputPipe; -import net.jxta.endpoint.Message; - - -public class IncomingPipeAdaptor implements Runnable { - - private static final Logger LOG = Logger.getLogger(IncomingPipeAdaptor.class.getName()); - - private InputPipe pipe = null; - private Incoming incoming = null; - private Thread poller = null; - - public IncomingPipeAdaptor(InputPipe pipe, Incoming incoming) { - if (pipe == null) { - throw new IllegalArgumentException("pipe cannot be null"); - } - this.pipe = pipe; - - if (incoming == null) { - throw new IllegalArgumentException("incoming cannot be null"); - } - this.incoming = incoming; - - poller = new Thread(this, "Reliable IncomingPipe Message Poll Thread"); - poller.setDaemon(true); - poller.start(); - } - - public void run() { - try { - while (true) { - Message msg = null; - - try { - msg = pipe.waitForMessage(); - } catch (InterruptedException ignore) { - continue; - } - - if (msg != null) { - incoming.recv(msg); - } - } - } catch (Throwable all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/Outgoing.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/Outgoing.java deleted file mode 100644 index f61a1951..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/Outgoing.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -import java.io.IOException; -import net.jxta.endpoint.Message; - - -/** - * This interface specifies the methods that must be - * implemented by a connection in order to be able to - * reliably deliver messages over the connection. - */ -public interface Outgoing { - - /** - * Send a message to the remote peer. - * @param msg the message - * @return true is successful - * @throws java.io.IOException if io error occurs - */ - boolean send(Message msg) throws IOException; - - /** - * Close the connection. - */ - void close(); - - /** - * Amount of a connection must be idle before a - * reconnection attempt will be considered. - * @return min idle reconnect time in millis - */ - long getMinIdleReconnectTime(); - - /** - * Sets the Timeout attribute. A timeout of 0 blocks forever - * - * @param timeout The new soTimeout value - */ - void setTimeout(int timeout); - - /** - * Amount of time after which a connection is - * considered idle and may be scavenged. - * @return idle timeout in millis - */ - long getIdleTimeout(); - - /** - * Amount if time during which retries may remain - * queued for retransmission. If still unACKed after - * this amount of time then the connection is - * considered dead. - * @return max retry age in millis - */ - long getMaxRetryAge(); - - /** - * Get the time when this connection was last used. - * @return last accessed in millis - */ - long getLastAccessed(); - - /** - * Set the time when this connection was last used. - * @param time in millis - */ - void setLastAccessed(long time); -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/OutgoingMsgrAdaptor.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/OutgoingMsgrAdaptor.java deleted file mode 100644 index 0ebf7646..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/OutgoingMsgrAdaptor.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ -package net.jxta.impl.util.pipe.reliable; - - -import java.io.IOException; - -import net.jxta.endpoint.Message; -import net.jxta.endpoint.Messenger; -import net.jxta.impl.util.TimeUtils; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * OutgoingMessengerAdaptor - */ -public class OutgoingMsgrAdaptor implements Outgoing { - - private final static transient Logger LOG = Logger.getLogger(OutgoingMsgrAdaptor.class.getName()); - - private final Messenger msgr; - private int timeout; - private long lastAccessed = 0; - private boolean closed = false; - - /** - * Constructor for the OutgoingMsgrAdaptor object - * - *@param msgr the messenger used to send messages - *@param timeout timeout in milliseconds - */ - public OutgoingMsgrAdaptor(Messenger msgr, int timeout) { - if (msgr == null) { - throw new IllegalArgumentException("messenger cannot be null"); - } - this.msgr = msgr; - this.timeout = timeout; - - // initialize to some reasonable value - lastAccessed = TimeUtils.timeNow(); - } - - /** - * returns last accessed time as a string - * - *@return last accessed time as a string - */ - @Override - public String toString() { - return " lastAccessed=" + Long.toString(lastAccessed); - } - - /** - * Sets the Timeout attribute. A timeout of 0 blocks forever - * - * @param timeout The new soTimeout value - */ - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - /** - * close the messenger (does not close the messenger) - */ - public void close() { - closed = true; - } - - /** - * Gets the minIdleReconnectTime of the OutgoingMsgrAdaptor - * (obsolete). - *@return The minIdleReconnectTime value - */ - public long getMinIdleReconnectTime() { - return timeout; - } - - /** - * Gets the idleTimeout of the OutgoingMsgrAdaptor. The adaptor never times out. - *@return Long.MAX_VALUE - */ - public long getIdleTimeout() { - return Long.MAX_VALUE; - } - - /** - * Gets the maxRetryAge attribute of the OutgoingMsgrAdaptor - * - *@return The maxRetryAge value - */ - public long getMaxRetryAge() { - return timeout == 0 ? Long.MAX_VALUE : timeout; - } - - /** - * Gets the lastAccessed time of OutgoingMsgrAdaptor - * - *@return The lastAccessed in milliseconds - */ - public long getLastAccessed() { - return lastAccessed; - } - - /** - * Sets the lastAccessed of OutgoingMsgrAdaptor - * - *@param time The new lastAccessed in milliseconds - */ - public void setLastAccessed(long time) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Setting lastAccessed to :" + lastAccessed); - } - lastAccessed = time; - } - - /** - * Sends a message - * - *@param msg message to send - *@return true if message send is successful - *@exception IOException if an io error occurs - */ - public boolean send(Message msg) throws IOException { - if (closed) { - throw new IOException("broken connection"); - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Sending a Message"); - } - - msgr.sendMessageB(msg, null, null); - return true; - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/OutgoingPipeAdaptor.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/OutgoingPipeAdaptor.java deleted file mode 100644 index 34f0b406..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/OutgoingPipeAdaptor.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -import java.io.IOException; - -import net.jxta.endpoint.Message; -import net.jxta.impl.util.TimeUtils; -import net.jxta.pipe.OutputPipe; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -public class OutgoingPipeAdaptor implements Outgoing { - - private static final Logger LOG = Logger.getLogger(OutgoingPipeAdaptor.class.getName()); - - private final OutputPipe pipe; - - private long lastAccessed = 0; - - public OutgoingPipeAdaptor(OutputPipe pipe, int wsize) { - if (pipe == null) { - throw new IllegalArgumentException("pipe cannot be null."); - } - - this.pipe = pipe; - - // initialize to some reasonable value - lastAccessed = TimeUtils.timeNow(); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return pipe.toString() + " lastAccessed=" + Long.toString(lastAccessed); - } - - /** - * {@inheritDoc} - */ - public boolean send(Message msg) throws IOException { - try { - return pipe.send(msg); - } catch (IOException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to send message " + msg, ex); - } - - return false; - } - } - - /** - * {@inheritDoc} - */ - public void close() { - pipe.close(); - } - - /** - * {@inheritDoc} - */ - public long getMinIdleReconnectTime() { - return 10 * TimeUtils.AMINUTE; - } - - /** - * {@inheritDoc} - */ - public void setTimeout(int timeout) {} - - /** - * {@inheritDoc} - * - *

            Default should be "never", otherwise, connection closes while not - * in active use and ReliableOutputStream does NOT reconnect automatically. - */ - public long getIdleTimeout() { - return Long.MAX_VALUE; - } - - /** - * {@inheritDoc} - * - *

            This is the important tunable: how long to wait on a stale connection. - */ - public long getMaxRetryAge() { - return 2 * TimeUtils.AMINUTE; - } - - /** - * {@inheritDoc} - */ - public long getLastAccessed() { - return lastAccessed; - } - - /** - * {@inheritDoc} - */ - public void setLastAccessed(long time) { - lastAccessed = time; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/OutgoingPipeAdaptorSync.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/OutgoingPipeAdaptorSync.java deleted file mode 100644 index 80b5afd2..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/OutgoingPipeAdaptorSync.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -import java.io.IOException; -import java.lang.IllegalStateException; - -import net.jxta.pipe.OutputPipe; -import net.jxta.endpoint.Message; -import net.jxta.impl.util.TimeUtils; - - -/** - * And ountgoing pipe adaptor which does not use a thread or queue. - * Additionally, the pipe does not need to be provided at construction time. - * The send() method blocks until the pipe is specified. - */ -public class OutgoingPipeAdaptorSync implements Outgoing { - - private OutputPipe pipe = null; - private long lastAccessed = 0; - private boolean closed = false; - - public OutgoingPipeAdaptorSync(OutputPipe pipe) { - - // Null permitted. Send will block until setPipe is called. - this.pipe = pipe; - - // initialize to some reasonable value - lastAccessed = TimeUtils.timeNow(); - } - - public boolean sendNb(Message msg) throws IOException { - OutputPipe locPipe; - - synchronized (this) { - locPipe = pipe; - } - - if (closed || locPipe == null) { - return false; - } - - locPipe.send(msg); - - return true; - } - - public boolean send(Message msg) throws IOException { - - OutputPipe locPipe; - - synchronized (this) { - while (pipe == null && !closed) { - try { - wait(); - } catch (InterruptedException ignore) {} - } - if (closed) { - return false; - } - locPipe = pipe; - } - - return locPipe.send(msg); - } - - public void setPipe(OutputPipe pipe) { - synchronized (this) { - if (closed || this.pipe != null) { - throw new IllegalStateException("Cannot change pipe nor re-open"); - } - this.pipe = pipe; - notifyAll(); - } - } - - /** - * {@inheritDoc} - */ - public void close() { - synchronized (this) { - if (closed) { - return; - } - - closed = true; - - if (pipe != null) { - pipe.close(); - pipe = null; - } - - notifyAll(); - } - } - - /** - * {@inheritDoc} - */ - public long getMinIdleReconnectTime() { - return 10 * TimeUtils.AMINUTE; - } - - /** - * {@inheritDoc} - * - *

            Default should be "never", otherwise, connection closes while not - * in active use and ReliableOutputStream does NOT reconnect automatically. - */ - public long getIdleTimeout() { - return Long.MAX_VALUE; - } - - /** - * {@inheritDoc} - */ - public void setTimeout(int timeout) {} - - /** - * {@inheritDoc} - * - *

            This is the important tunable: how long to wait on a stale connection. - */ - public long getMaxRetryAge() { - return 1 * TimeUtils.AMINUTE; - } - - /** - * {@inheritDoc} - */ - public long getLastAccessed() { - return lastAccessed; - } - - /** - * {@inheritDoc} - */ - public void setLastAccessed(long time) { - lastAccessed = time; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return ((pipe == null) ? "no pipe yet" : pipe.toString()) + " lastAccessed=" + Long.toString(lastAccessed); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/ReliableInputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/ReliableInputStream.java deleted file mode 100644 index 5233416b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/ReliableInputStream.java +++ /dev/null @@ -1,779 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InterruptedIOException; -import java.net.SocketTimeoutException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import net.jxta.endpoint.ByteArrayMessageElement; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.WireFormatMessageFactory; -import net.jxta.impl.util.TimeUtils; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * Acts as a reliable input stream. Accepts data which - * arrives in messages and orders it. - */ -public class ReliableInputStream extends InputStream implements Incoming { - - /** - * Logger - */ - private static final Logger LOG = Logger.getLogger(ReliableInputStream.class.getName()); - - /** - * Connection we are working for. - */ - private Outgoing outgoing; - - private volatile boolean closed = false; - private boolean closing = false; - - private MsgListener listener = null; - - /** - * The amount of time that read() operation will block. > 0 - */ - private long timeout; - - /** - * The current sequence number we are reading bytes from. - */ - private volatile int sequenceNumber = 0; - - /** - * Queue of incoming messages. - */ - private final List inputQueue = new ArrayList(); - - /** - * The I/O record for the message we are currently using for stream data. - */ - private final Record record; - - /** - * Input record Object - */ - private static class Record { - public InputStream inputStream; - // next inbuff byte - public long nextByte; - // size of Record - public long size; - - public Record() { - inputStream = null; // allocated by caller - nextByte = 0; // We read here (set by caller) - size = 0; // Record size(set by caller) - } - - /** reset the record element - * - */ - public void resetRecord() { - if (null != inputStream) { - try { - inputStream.close(); - } catch (IOException ignored) {} - } - inputStream = null; - size = nextByte = 0; - } - } - - - /** - * An input queue element which breaks out a received message in - * enqueueMessage(). - */ - private static class IQElt implements Comparable { - final int seqnum; - final MessageElement elt; - boolean ackd = false; - - IQElt(int sequence, MessageElement element) { - seqnum = sequence; - elt = element; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof IQElt) { - IQElt targ = (IQElt) obj; - - return (this.seqnum == targ.seqnum); - } - return false; - } - - public int compareTo(IQElt el) { - return this.seqnum < el.seqnum ? -1 : this.seqnum == el.seqnum ? 0 : 1; - } - - /** - * {@inheritDoc} - */ - public int compareTo(Object o) { - return compareTo((IQElt) o); - } - } - - public ReliableInputStream(Outgoing outgoing, int timeout) { - this(outgoing, timeout, null); - } - - public ReliableInputStream(Outgoing outgoing, int timeout, MsgListener listener) { - this.outgoing = outgoing; - setTimeout(timeout); - - record = new Record(); - this.listener = listener; - // 1 <= seq# <= maxint, monotonically increasing - // Incremented before compare. - sequenceNumber = 0; - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - if (listener != null) { - LOG.info("Listener based ReliableInputStream created"); - } - } - } - - /** - * {@inheritDoc} - * - *

            This is an explicit close operation. All subsequent {@code read()} - * operations will fail. - */ - @Override - public void close() throws IOException { - super.close(); - synchronized (inputQueue) { - closed = true; - inputQueue.clear(); - inputQueue.notifyAll(); - } - } - - /** - * Returns true if closed - * - * @return true if closed - */ - public boolean isInputShutdown() { - return closed; - } - - /** - * Prepare this input stream to being closed. It will still deliver the - * packets that have been received, but nothing more. This is meant to be - * called in response to the other side having initiated closure. We assume - * that when the other side does it it means that it is satisfied with what - * we have acknowledged so far. - */ - public void softClose() { - synchronized (inputQueue) { - closing = true; - inputQueue.notifyAll(); - } - } - - /** - * Sets the Timeout attribute. A timeout of 0 blocks forever - * - * @param timeout The new soTimeout value - */ - public void setTimeout(int timeout) { - if (timeout < 0) { - throw new IllegalArgumentException("Timeout must be >=0"); - } - - this.timeout = (0 == timeout) ? Long.MAX_VALUE : timeout; - } - - /** - * {@inheritDoc} - */ - @Override - public int read() throws IOException { - if (closed) { - return -1; - } - - byte[] a = new byte[1]; - - while (true) { - int len = local_read(a, 0, 1); - - if (len < 0) { - break; - } - if (len > 0) { - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Read() : " + (a[0] & 255)); - } - - return a[0] & 0xFF; // The byte - } - } - - // If we've reached EOF, there's nothing to do but close(). - - close(); - return -1; - } - - /** - * {@inheritDoc} - */ - @Override - public int read(byte[] a, int offset, int length) throws IOException { - if (closed) { - return -1; - } - - if (0 == length) { - return 0; - } - - int i = local_read(a, offset, length); - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Read(byte[], int, " + length + "), bytes read = " + i); - } - - // If we've reached EOF; there's nothing to do but close(). - if (i == -1) { - close(); - } - return i; - } - - /** - * Send a sequential ACK and selective ACKs for all of - * the queued messages. - * - * @param seqnAck the sequence number being sequential ACKed - */ - private void sendACK(int seqnAck) { - // No need to sync on inputQueue, acking as many as we can is want we want - List selectedAckList = new ArrayList(); - List queue; - - synchronized (inputQueue) { - queue = new ArrayList(inputQueue); - } - - Iterator eachInQueue = queue.iterator(); - - while (eachInQueue.hasNext() && (selectedAckList.size() < Defs.MAXQUEUESIZE)) { - IQElt anIQElt = eachInQueue.next(); - - if (anIQElt.seqnum > seqnAck) { - if (!anIQElt.ackd) { - selectedAckList.add(anIQElt.seqnum); - anIQElt.ackd = true; - } - } - } - - // PERMIT DUPLICATE ACKS. Just a list and one small message. - sendACK(seqnAck, selectedAckList); - } - - /** - * Build an ACK message. The message provides a sequential ACK count and - * an optional list of selective ACKs. - * - * @param seqnAck the sequence number being sequential ACKed - * @param sackList a list of selective ACKs. Must be sorted in increasing - * order. - */ - private void sendACK(int seqnAck, List sackList) { - ByteArrayOutputStream bos = new ByteArrayOutputStream((1 + sackList.size()) * 4); - DataOutputStream dos = new DataOutputStream(bos); - - try { - dos.writeInt(seqnAck); - for (Integer aSackList : sackList) { - dos.writeInt(aSackList); - } - dos.close(); - bos.close(); - - Message ACKMsg = new Message(); - MessageElement elt = new ByteArrayMessageElement(Defs.ACK_ELEMENT_NAME, Defs.MIME_TYPE_ACK, bos.toByteArray(), null); - - ACKMsg.addMessageElement(Defs.NAMESPACE, elt); - - outgoing.send(ACKMsg); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("SENT ACK, seqn#" + seqnAck + " and " + sackList.size() + " SACKs "); - } - } catch (IOException e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "sendACK caught IOException:", e); - } - } - } - - /** - * {@inheritDoc} - */ - public void recv(Message msg) { - queueIncomingMessage(msg); - } - - public boolean hasNextMessage() { - return !inputQueue.isEmpty(); - } - - Message nextMessage(boolean blocking) throws IOException { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("nextMessage blocking? [" + blocking + "]"); - } - MessageElement elt = dequeueMessage(sequenceNumber + 1, blocking); - - if (null == elt) { - return null; - } - sequenceNumber += 1; // next msg sequence number - - Message msg; - - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Converting message seqn :" + (sequenceNumber - 1) + "element to message"); - } - - msg = WireFormatMessageFactory.fromWire(elt.getStream(), Defs.MIME_TYPE_MSG, null); - } catch (IOException ex) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Could not deserialize message " + elt.getElementName(), ex); - } - return null; - } - return msg; - } - - /** - * queue messages by sequence number. - */ - private void queueIncomingMessage(Message msg) { - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Queue Incoming Message begins for " + msg); - } - - long startEnqueue = TimeUtils.timeNow(); - - Iterator eachElement = msg.getMessageElements(Defs.NAMESPACE, Defs.MIME_TYPE_BLOCK); - - // OK look for jxta message - while (!closed && !closing && eachElement.hasNext()) { - MessageElement elt = eachElement.next(); - - eachElement.remove(); - - int msgSeqn; - - try { - msgSeqn = Integer.parseInt(elt.getElementName()); - } catch (NumberFormatException n) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.warning("Discarding element (" + elt.getElementName() + ") Not one of ours."); - } - continue; - } - - IQElt newElt = new IQElt(msgSeqn, elt); - - // OK we must enqueue - - // We rely on the sender to not to send more than the window size - // because we do not limit the number of elements we allow to be - // enqueued. - - // see if this is a duplicate - if (newElt.seqnum <= sequenceNumber) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RCVD OLD MESSAGE : Discard seqn#" + newElt.seqnum + " now at seqn#" + sequenceNumber); - } - break; - } - - synchronized (inputQueue) { - - // dbl check with the lock held. - if (closing || closed) { - return; - } - - // Insert this message into the input queue. - // 1. Do not add duplicate messages - // 2. Store in increasing sequence nos. - int insertIndex = inputQueue.size(); - boolean duplicate = false; - - for (int j = 0; j < inputQueue.size(); j++) { - IQElt iq = inputQueue.get(j); - - if (newElt.seqnum < iq.seqnum) { - insertIndex = j; - break; - } else if (newElt.seqnum == iq.seqnum) { - duplicate = true; - break; - } - } - - if (duplicate) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RCVD OLD MESSAGE : Discard duplicate msg, seqn#" + newElt.seqnum); - } - break; - } - - inputQueue.add(insertIndex, newElt); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Enqueued msg with seqn#" + newElt.seqnum + " at index " + insertIndex); - } - - inputQueue.notifyAll(); - } - } - - if (listener != null) { - Message newmsg = null; - - while (true) { - try { - newmsg = nextMessage(false); - } catch (IOException io) {// do nothing as this exception will never occur - } - if (newmsg == null) { - break; - } - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("In listener mode, calling back listener"); - } - listener.processIncomingMessage(newmsg); - } catch (Throwable all) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Uncaught Throwable calling listener", all); - } - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - long waited = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), startEnqueue); - - LOG.fine("Queue Incoming Message for " + msg + " completed in " + waited + " msec."); - } - } - - long nextRetransRequest = TimeUtils.toAbsoluteTimeMillis(TimeUtils.ASECOND); - - /** - * Dequeue the message with the desired sequence number waiting as needed - * until the message is available. - * - * @param desiredSeqn the sequence number to be dequeued. - * @param blocking If {@code true} then this method should block while - * waiting for the specified message sequence number. - * @return the Message Element with the desired sequence number or null if - * the queue has been closed. - */ - private MessageElement dequeueMessage(int desiredSeqn, boolean blocking) throws IOException { - IQElt iQ = null; - - // Wait for incoming message here - long startDequeue = TimeUtils.timeNow(); - long timeoutAt = TimeUtils.toAbsoluteTimeMillis(timeout); - int wct = 0; - - synchronized (inputQueue) { - while (!closed) { - if (inputQueue.isEmpty()) { - if (!blocking) { - return null; - } - if (closing) { - return null; - } - try { - wct++; - inputQueue.wait(TimeUtils.ASECOND); - if (timeoutAt < TimeUtils.timeNow()) { - throw new SocketTimeoutException("Read timeout reached"); - } - } catch (InterruptedException e) { - Thread.interrupted(); - } - // reset retrans request timer since we don't want to immediately - // request retry after a long wait for out of order messages. - - nextRetransRequest = TimeUtils.toAbsoluteTimeMillis(TimeUtils.ASECOND); - continue; - } - - iQ = inputQueue.get(0); // FIFO - - if (iQ.seqnum < desiredSeqn) { - // Ooops a DUPE slipped in the head of the queue undetected - // (seqnum consistency issue). - // Just drop it. - inputQueue.remove(0); - // if such is the case then notify the other end so that - // the message does not remain in the retry queue eventually - // triggering a broken pipe exception - sendACK(iQ.seqnum); - continue; - } else if (iQ.seqnum != desiredSeqn) { - if (TimeUtils.toRelativeTimeMillis(nextRetransRequest) < 0) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Trigger retransmission. Wanted seqn#" + desiredSeqn + " found seqn#" + iQ.seqnum); - } - sendACK(desiredSeqn - 1); - nextRetransRequest = TimeUtils.toAbsoluteTimeMillis(TimeUtils.ASECOND); - } - if (!blocking) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Message out of sequece in Non-Blocking mode. returning"); - } - // not the element of interest return nothing - return null; - } - try { - wct++; - inputQueue.wait(TimeUtils.ASECOND); - if (timeoutAt < TimeUtils.timeNow()) { - throw new SocketTimeoutException("Read timeout reached"); - } - } catch (InterruptedException e) { - throw new InterruptedIOException("IO interrupted "); - } - continue; - } - inputQueue.remove(0); - break; - } - } - nextRetransRequest = 0; - // if we are closed then we return null - if (null == iQ) { - return null; - } - - sendACK(desiredSeqn); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - long waited = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), startDequeue); - - LOG.fine("DEQUEUED seqn#" + iQ.seqnum + " in " + waited + " msec on input queue"); - if (wct > 0) { - LOG.fine("DEQUEUE waited " + wct + " times on input queue"); - } - } - return iQ.elt; - } - - /** - * {@inheritDoc} - */ - @Override - public int available() throws IOException { - if (listener != null) { - throw new IOException("available() not supported in async mode"); - } - if (closed) { - throw new IOException("Stream closed"); - } - synchronized (record) { - if (record.inputStream != null) { - if ((record.size == 0) || (record.nextByte == record.size)) { - if (inputQueue.isEmpty()) { - return 0; - } - // reset the record - record.resetRecord(); // GC as necessary(inputStream byte[]) - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting next data block at seqn#" + (sequenceNumber + 1)); - } - MessageElement elt = dequeueMessage(sequenceNumber + 1, false); - - if (null == elt) { - return 0; - } - sequenceNumber += 1; // next msg sequence number - // Get the length of the Record - record.size = elt.getByteLength(); - record.inputStream = elt.getStream(); - } - return record.inputStream.available(); - } - } - return 0; - } - - private int local_read(byte[] buf, int offset, int length) throws IOException { - - if (listener != null) { - throw new IOException("read() not supported in async mode"); - } - - synchronized (record) { - if ((record.size == 0) || (record.nextByte == record.size)) { - - // reset the record - record.resetRecord(); // GC as necessary(inputStream byte[]) - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Getting next data block at seqn#" + (sequenceNumber + 1)); - } - - MessageElement elt = dequeueMessage(sequenceNumber + 1, true); - - if (null == elt) { - return -1; - } - - sequenceNumber += 1; // next msg sequence number - - // Get the length of the Record - record.size = elt.getByteLength(); - record.inputStream = elt.getStream(); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("new seqn#" + sequenceNumber + ", bytes = " + record.size); - } - } - - // return the requested Record data - // These calls should NEVER ask for more data than is in the - // received Record. - - long left = record.size - record.nextByte; - int copyLen = (int) Math.min(length, left); - int copied = 0; - - do { - int res = record.inputStream.read(buf, offset + copied, copyLen - copied); - - if (res < 0) { - break; - } - copied += res; - } while (copied < copyLen); - - record.nextByte += copied; - - if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { - LOG.finer("Requested " + length + ", Read " + copied + " bytes"); - } - - return copied; - } - } - - /** - * Returns the message listener for this pipe - * @return MsgListener - * - */ - public MsgListener getListener() { - return listener; - } - - /** - * The listener interface for receiving {@link net.jxta.endpoint.Message} - */ - public interface MsgListener { - - /** - * Called for each message received. - * - * @param message The message to be received. - */ - void processIncomingMessage(Message message); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/ReliableOutputStream.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/ReliableOutputStream.java deleted file mode 100644 index f6129632..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/util/pipe/reliable/ReliableOutputStream.java +++ /dev/null @@ -1,1277 +0,0 @@ -/* - * Copyright (c) 2003-2007 Sun Microsystems, Inc. All rights reserved. - * - * The Sun Project JXTA(TM) Software License - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, if any, must - * include the following acknowledgment: "This product includes software - * developed by Sun Microsystems, Inc. for JXTA(TM) technology." - * Alternately, this acknowledgment may appear in the software itself, if - * and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must - * not be used to endorse or promote products derived from this software - * without prior written permission. For written permission, please contact - * Project JXTA at http://www.jxta.org. - * - * 5. Products derived from this software may not be called "JXTA", nor may - * "JXTA" appear in their name, without prior written permission of Sun. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN - * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * JXTA is a registered trademark of Sun Microsystems, Inc. in the United - * States and other countries. - * - * Please see the license information page at : - * for instructions on use of - * the license in source files. - * - * ==================================================================== - * - * This software consists of voluntary contributions made by many individuals - * on behalf of Project JXTA. For more information on Project JXTA, please see - * http://www.jxta.org. - * - * This license is based on the BSD license adopted by the Apache Foundation. - */ - -package net.jxta.impl.util.pipe.reliable; - - -import java.io.ByteArrayOutputStream; -import net.jxta.endpoint.ByteArrayMessageElement; -import net.jxta.endpoint.Message; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.endpoint.WireFormatMessage; -import net.jxta.endpoint.WireFormatMessageFactory; -import net.jxta.impl.util.TimeUtils; -import net.jxta.logging.Logging; - -import java.io.DataInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Level; -import java.util.logging.Logger; - - -/** - * Accepts data and packages it into messages for sending to the remote. The - * messages are kept in a retry queue until the remote peer acknowledges - * receipt of the message. - */ -public class ReliableOutputStream extends OutputStream implements Incoming { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(ReliableOutputStream.class.getName()); - - /** - * Initial estimated Round Trip Time - */ - private final static long initRTT = 10 * TimeUtils.ASECOND; - - /** - * The default size for the blocks we will chunk the stream into. - */ - private final static int DEFAULT_MESSAGE_CHUNK_SIZE = 63 * 1024; - - private final static MessageElement RETELT = new StringMessageElement(Defs.RETRY_ELEMENT_NAME, Defs.RETRY_ELEMENT_VALUE, null); - - /** - * A lock we use to ensure that write operations happen in order. - */ - private final Object writeLock = new String("writeLock"); - - /** - * The buffer we cache writes to. - */ - private byte[] writeBuffer = null; - - /** - * Number of bytes written to the write buffer. - */ - private int writeCount = 0; - - /** - * Set the default write buffer size. - */ - private int writeBufferSize = DEFAULT_MESSAGE_CHUNK_SIZE; - - /** - * Absolute time in milliseconds at which the write buffer began - * accumulating bytes to be written. - */ - private long writeBufferAge = Long.MAX_VALUE; - - /** - * If less than {@code TimeUtils.timenow()} then we are closed otherwise - * this is the absolute time at which we will become closed. We begin by - * setting this value as {@Long.MAX_VALUE} until we establish an earlier - * close deadline. - */ - private long closedAt = Long.MAX_VALUE; - - /** - * If {@code true} then we have received a close request from the remote - * side. They do not want to receive any more messages from us. - */ - private volatile boolean remoteClosed = false; - - /** - * If {@code true} then we have closed this stream locally and will not - * accept any further messages for sending. Unacknowledged messages will - * be retransmitted until the linger delay is passed. - */ - private volatile boolean localClosed = false; - - /** - * The relative time in milliseconds that we will allow our connection to - * linger. - */ - private long lingerDelay = 120 * TimeUtils.ASECOND; - - /** - * Sequence number of the message we most recently sent out. - */ - private AtomicInteger sequenceNumber = new AtomicInteger(0); - - /** - * Sequence number of highest sequential ACK. - */ - private volatile int maxACK = 0; - - /** - * connection we are working for - */ - private final Outgoing outgoing; - - /** - * The daemon thread that performs retransmissions. - */ - private Thread retrThread = null; - - // for retransmission - /** - * Average round trip time in milliseconds. - */ - private volatile long aveRTT = initRTT; - private volatile long remRTT = 0; - - /** - * Has aveRTT been set at least once over its initial guesstimate value. - */ - private boolean aveRTTreset = false; - - /** - * Number of ACK message received. - */ - private AtomicInteger numACKS = new AtomicInteger(0); - - /** - * When to start computing aveRTT - */ - private int rttThreshold = 0; - - /** - * Retry Time Out measured in milliseconds. - */ - private volatile long RTO = 0; - - /** - * Minimum Retry Timeout measured in milliseconds. - */ - private volatile long minRTO = initRTT * 5; - - /** - * Maximum Retry Timeout measured in milliseconds. - */ - private volatile long maxRTO = initRTT * 60; - - /** - * absolute time in milliseconds of last sequential ACK. - */ - private volatile long lastACKTime = 0; - - /** - * absolute time in milliseconds of last SACK based retransmit. - */ - private volatile long sackRetransTime = 0; - - // running average of receipients Input Queue - private int nIQTests = 0; - private int aveIQSize = 0; - - /** - * Our estimation of the current free space in the remote input queue. - */ - private volatile int mrrIQFreeSpace = 0; - - /** - * Our estimation of the maximum size of the remote input queue. - */ - private int rmaxQSize = Defs.MAXQUEUESIZE; - - /** - * The flow control module. - */ - private final FlowControl fc; - - /** - * Cache of the last rwindow recommendation by fc. - */ - private volatile int rwindow = 0; - - /** - * retrans queue element - */ - private static class RetrQElt { - - /** - * sequence number of this message. - */ - final int seqnum; - - /** - * the message - */ - final Message msg; - - /** - * absolute time of original enqueuing - */ - final long enqueuedAt; - - /** - * has been marked as retransmission - */ - int marked; - - /** - * absolute time when this msg was last transmitted - */ - long sentAt; - - /** - * Constructor for the RetrQElt object - * - * @param seqnum sequence number - * @param msg the message - */ - public RetrQElt(int seqnum, Message msg) { - this.seqnum = seqnum; - this.msg = msg; - this.enqueuedAt = TimeUtils.timeNow(); - this.sentAt = this.enqueuedAt; - this.marked = 0; - } - } - - /** - * The collection of messages available for re-transmission. - */ - protected final List retrQ = new ArrayList(); - - /** - * Constructor for the ReliableOutputStream object - * - * @param outgoing the outgoing object - */ - public ReliableOutputStream(Outgoing outgoing) { - // By default use the old behaviour: fixed fc with a rwin of 20 - this(outgoing, new FixedFlowControl(20)); - } - - /** - * Constructor for the ReliableOutputStream object - * - * @param outgoing the outgoing object - * @param fc flow-control - */ - public ReliableOutputStream(Outgoing outgoing, FlowControl fc) { - this.outgoing = outgoing; - - // initial RTO is set to maxRTO so as to give time - // to the receiver to catch-up - this.RTO = maxRTO; - - this.mrrIQFreeSpace = rmaxQSize; - this.rttThreshold = rmaxQSize; - - // Init last ACK Time to now - this.lastACKTime = TimeUtils.timeNow(); - this.sackRetransTime = TimeUtils.timeNow(); - - // Attach the flowControl module - this.fc = fc; - - // Update our initial rwindow to reflect fc's initial value - this.rwindow = fc.getRwindow(); - } - - /** - * {@inheritDoc} - */ - @Override - public void close() throws IOException { - flush(); - - super.close(); - localClosed = true; - closedAt = TimeUtils.toRelativeTimeMillis(lingerDelay); - - synchronized (retrQ) { - retrQ.notifyAll(); - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Closed."); - } - } - - public long getLingerDelay() { - return lingerDelay; - } - - public void setLingerDelay(long linger) { - if (linger < 0) { - throw new IllegalArgumentException("Linger delay may not be negative."); - } - - if (0 == linger) { - linger = Long.MAX_VALUE; - } - - lingerDelay = linger; - } - - /** - * Return the size of the buffers we are using for accumulating writes. - * - * @return size of our write buffers. - */ - public int setSendBufferSize() { - return writeBufferSize; - } - - /** - * Set the size of the buffers we will use for accumulating writes. - * - * @param size The desired size of write buffers. - * @throws IOException if an I/O error occurs. In particular, an IOException is thrown if the output stream is closed. - */ - public void setSendBufferSize(int size) throws IOException { - if (size <= 0) { - throw new IllegalArgumentException("Send buffer size may not be <= 0"); - } - - // Flush any existing buffered writes. Then next write will use the new buffer size. - synchronized (writeLock) { - flushBuffer(); - writeBufferSize = size; - } - } - - /** - * We have received a close request from the remote peer. We must stop - * retransmissions immediately. - */ - public void hardClose() { - remoteClosed = true; - closedAt = TimeUtils.timeNow(); - - // Clear the retry queue. Remote side doesn't care. - synchronized (retrQ) { - retrQ.clear(); - retrQ.notifyAll(); - } - - // Clear the write queue. Remote side doesn't care. - synchronized (writeLock) { - writeCount = 0; - writeBuffer = null; - writeBufferAge = Long.MAX_VALUE; - } - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Hard closed."); - } - } - - /** - * Returns the state of the stream - * - * @return true if closed - */ - public boolean isClosed() { - return localClosed || remoteClosed; - } - - /** - * {@inheritDoc} - */ - @Override - public void flush() throws IOException { - synchronized (writeLock) { - flushBuffer(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void write(int b) throws IOException { - write(new byte[] { (byte) b }, 0, 1); - } - - /** - * {@inheritDoc} - */ - @Override - public void write(byte b[], int off, int len) throws IOException { - synchronized (writeLock) { - if (isClosed()) { - throw new IOException("stream is closed"); - } - - if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { - throw new IndexOutOfBoundsException(); - } - - if (len == 0) { - return; - } - - int current = off; - int end = current + len; - - while (current < end) { - if (0 == writeCount) { - // No bytes written? We need a new buffer. - writeBuffer = new byte[writeBufferSize]; - writeBufferAge = TimeUtils.timeNow(); - } - - int remain = end - current; - - int available = writeBuffer.length - writeCount; - int copy = Math.min(available, remain); - - System.arraycopy(b, current, writeBuffer, writeCount, copy); - writeCount += copy; - current += copy; - - if (writeBuffer.length == writeCount) { - flushBuffer(); - } - } - } - } - - /** - * Flush the internal buffer. {@code writeLock} must have been previously - * acquired. - * @throws IOException if an I/O error occurs. In particular, an IOException is thrown if the output stream is closed. - */ - private void flushBuffer() throws IOException { - if (writeCount > 0) { - // send the message - try { - writeBuffer(writeBuffer, 0, writeCount); - } finally { - writeCount = 0; - writeBuffer = null; - writeBufferAge = Long.MAX_VALUE; - } - } - } - - /** - * Write the internal buffer. {@code writeLock} must have been previously - * acquired. - * - * @param b data - * @param off the start offset in the data. - * @param len the number of bytes to write. - * @throws IOException if an I/O error occurs. In particular, an IOException is thrown if the output stream is closed. - */ - private void writeBuffer(byte[] b, int off, int len) throws IOException { - if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { - throw new IndexOutOfBoundsException(); - } - - if (len == 0) { - return; - } - - if (null == retrThread) { - retrThread = new Thread(new Retransmitter(), "JXTA Reliable Retransmiter for " + this); - retrThread.setDaemon(true); - retrThread.start(); - } - - // allocate new message - Message jmsg = new Message(); - - synchronized (retrQ) { - while (true) { - if (isClosed()) { - throw new IOException("Connection is " + (localClosed ? "closing" : "closed")); - } - if (retrQ.size() > Math.min(rwindow, mrrIQFreeSpace * 2)) { - try { - retrQ.wait(1000); - } catch (InterruptedException ignored) {// ignored - } - continue; - } - break; - } - - int sequenceToUse = sequenceNumber.incrementAndGet(); - MessageElement element = new ByteArrayMessageElement(Integer.toString(sequenceToUse), Defs.MIME_TYPE_BLOCK, b, off - , - len, null); - - jmsg.addMessageElement(Defs.NAMESPACE, element); - RetrQElt retrQel = new RetrQElt(sequenceToUse, jmsg.clone()); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Reliable WRITE : seqn#" + sequenceNumber + " length=" + len); - } - - // place copy on retransmission queue - retrQ.add(retrQel); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Retrans Enqueue added seqn#" + sequenceNumber + " retrQ.size()=" + retrQ.size()); - } - } - - outgoing.send(jmsg); - mrrIQFreeSpace--; - // assume we have now taken a slot - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("SENT : seqn#" + sequenceNumber + " length=" + len); - } - } - - /** - * Serialize a JXTA message as a reliable message. - * - *

            This method bypasses the built-in buffering and ignores the MTU size. - * - * @param msg message to send - * @return message sequence number - * @throws IOException if an I/O error occurs - */ - public int send(Message msg) throws IOException { - WireFormatMessage msgSerialized = WireFormatMessageFactory.toWire(msg, Defs.MIME_TYPE_MSG, null); - ByteArrayOutputStream baos = new ByteArrayOutputStream((int) msgSerialized.getByteLength()); - - msgSerialized.sendToStream(baos); - baos.close(); - byte[] bytes = baos.toByteArray(); - - synchronized (writeLock) { - flushBuffer(); - writeBuffer(bytes, 0, bytes.length); - return sequenceNumber.get(); - } - } - - /** - * Gets the maxAck attribute of the ReliableOutputStream object - * - * @return The maxAck value - */ - public int getMaxAck() { - return maxACK; - } - - /** - * Gets the seqNumber attribute of the ReliableOutputStream object - * - * @return The seqNumber value - */ - public int getSeqNumber() { - return sequenceNumber.get(); - } - - /** - * Gets the queueFull attribute of the ReliableOutputStream object - * - * @return The queueFull value - */ - protected boolean isQueueFull() { - return mrrIQFreeSpace < 1; - } - - /** - * Gets the queueEmpty attribute of the ReliableOutputStream object. - * - * @return {@code true} if the queue is empty otherwise {@code false}. - */ - public boolean isQueueEmpty() { - synchronized (retrQ) { - return retrQ.isEmpty(); - } - } - - /** - * Waits for the retransmit queue to become empty. - * - * @param timeout The relative time in milliseconds to wait for the queue to - * become empty. - * @return {@code true} if the queue is empty otherwise {@code false}. - * @throws InterruptedException if interrupted - */ - public boolean waitQueueEmpty(long timeout) throws InterruptedException { - long timeoutAt = TimeUtils.toAbsoluteTimeMillis(timeout); - - synchronized (retrQ) { - while (!retrQ.isEmpty() && (TimeUtils.timeNow() < timeoutAt)) { - long sleepTime = TimeUtils.toRelativeTimeMillis(timeoutAt); - - if (sleepTime > 0) { - retrQ.wait(sleepTime); - } - } - - return retrQ.isEmpty(); - } - } - - /** - * wait for activity on the retry queue - * - * @param timeout timeout in millis - * @throws InterruptedException when interrupted - */ - public void waitQueueEvent(long timeout) throws InterruptedException { - synchronized (retrQ) { - retrQ.wait(timeout); - } - } - - /** - * Calculates a message retransmission time-out - * - * @param dt base time - * @param msgSeqNum Message sequence number - */ - private void calcRTT(long dt, int msgSeqNum) { - - if (numACKS.incrementAndGet() == 1) { - // First ACK arrived. We can start computing aveRTT on the messages - // we send from now on. - rttThreshold = sequenceNumber.get() + 1; - } - - if (msgSeqNum > rttThreshold) { - // Compute only when it has stabilized a bit - // Since the initial mrrIQFreeSpace is small; the first few - // messages will be sent early on and may wait a long time - // for the return channel to initialize. After that things - // start flowing and RTT becomes relevant. - // Carefull with the computation: integer division with round-down - // causes cumulative damage: the ave never goes up if this is not - // taken care of. We keep the reminder from one round to the other. - - if (!aveRTTreset) { - aveRTT = dt; - aveRTTreset = true; - } else { - long tmp = (8 * aveRTT) + ((8 * remRTT) / 9) + dt; - - aveRTT = tmp / 9; - remRTT = tmp - aveRTT * 9; - } - } - - // Set retransmission time out: 2.5 x RTT - // RTO = (aveRTT << 1) + (aveRTT >> 1); - RTO = aveRTT * 2; - - // Enforce a min/max - RTO = Math.max(RTO, minRTO); - RTO = Math.min(RTO, maxRTO); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RTT = " + dt + "ms aveRTT = " + aveRTT + "ms" + " RTO = " + RTO + "ms"); - } - } - - /** - * @param iq Description of the Parameter - * @return Description of the Return Value - */ - private int calcAVEIQ(int iq) { - int n = nIQTests; - - nIQTests += 1; - aveIQSize = ((n * aveIQSize) + iq) / nIQTests; - return aveIQSize; - } - - /** - * process an incoming message - * - * @param msg message to process - */ - public void recv(Message msg) { - - Iterator eachACK = msg.getMessageElements(Defs.NAMESPACE, Defs.MIME_TYPE_ACK); - - while (eachACK.hasNext()) { - MessageElement elt = eachACK.next(); - - eachACK.remove(); - int sackCount = ((int) elt.getByteLength() / 4) - 1; - - try { - DataInputStream dis = new DataInputStream(elt.getStream()); - int seqack = dis.readInt(); - int[] sacs = new int[sackCount]; - - for (int eachSac = 0; eachSac < sackCount; eachSac++) { - sacs[eachSac] = dis.readInt(); - } - Arrays.sort(sacs); - // take care of the ACK here; - ackReceived(seqack, sacs); - } catch (IOException failed) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failure processing ACK", failed); - } - } - } - } - - /** - * Process an ACK Message. We remove ACKed - * messages from the retry queue. We only - * acknowledge messages received in sequence. - *

            - * The seqnum is for the largest unacknowledged seqnum - * the recipient has received. - *

            - * The sackList is a sequence of all of the - * received messages in the sender's input Q. All - * will be sequence numbers higher than the - * sequential ACK seqnum. - *

            - * Recipients are passive and only ack upon the - * receipt of an in sequence message. - *

            - * They depend on our RTO to fill holes in message - * sequences. - * - * @param seqnum message sequence number - * @param sackList array of message sequence numbers - */ - public void ackReceived(int seqnum, int[] sackList) { - - int numberACKed = 0; - long rttCalcDt = 0; - int rttCalcSeqnum = -1; - long fallBackDt = 0; - int fallBackSeqnum = -1; - - // remove acknowledged messages from retrans Q. - synchronized (retrQ) { - lastACKTime = TimeUtils.timeNow(); - fc.ackEventBegin(); - maxACK = Math.max(maxACK, seqnum); - - // dump the current Retry queue and the SACK list - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - StringBuilder dumpRETRQ = new StringBuilder("ACK RECEIVE : " + Integer.toString(seqnum)); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - dumpRETRQ.append('\n'); - } - dumpRETRQ.append("\tRETRQ (size=").append(retrQ.size()).append(")"); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - dumpRETRQ.append(" : "); - for (int y = 0; y < retrQ.size(); y++) { - if (0 != y) { - dumpRETRQ.append(", "); - } - RetrQElt r = retrQ.get(y); - - dumpRETRQ.append(r.seqnum); - } - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - dumpRETRQ.append('\n'); - } - dumpRETRQ.append("\tSACKLIST (size=").append(sackList.length).append(")"); - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - dumpRETRQ.append(" : "); - for (int y = 0; y < sackList.length; y++) { - if (0 != y) { - dumpRETRQ.append(", "); - } - dumpRETRQ.append(sackList[y]); - } - } - LOG.fine(dumpRETRQ.toString()); - } - - Iterator eachRetryQueueEntry = retrQ.iterator(); - - // First remove monotonically increasing seq#s in retrans vector - while (eachRetryQueueEntry.hasNext()) { - RetrQElt retrQElt = eachRetryQueueEntry.next(); - - if (retrQElt.seqnum > seqnum) { - break; - } - // Acknowledged - eachRetryQueueEntry.remove(); - - // Update RTT, RTO. Use only those that where acked - // w/o retrans otherwise the number may be phony (ack - // of first xmit received just after resending => RTT - // seems small). Also, we keep the worst of the bunch - // we encounter. If we really can't find a single - // non-resent message, we make do with a pessimistic - // approximation: we must not be left behind with an - // RTT that's too short, we'd keep resending like - // crazy. - long enqueuetime = retrQElt.enqueuedAt; - long dt = TimeUtils.toRelativeTimeMillis(lastACKTime, enqueuetime); - - // Update RTT, RTO - if (retrQElt.marked == 0) { - if (dt > rttCalcDt) { - rttCalcDt = dt; - rttCalcSeqnum = retrQElt.seqnum; - } - } else { - // In case we find no good candidate, make - // a guess by dividing by the number of attempts - // and keep the worst of them too. Since we - // know it may be too short, we will not use it - // if shortens rtt. - dt /= (retrQElt.marked + 1); - if (dt > fallBackDt) { - fallBackDt = dt; - fallBackSeqnum = retrQElt.seqnum; - } - } - fc.packetACKed(retrQElt.seqnum); - retrQElt = null; - numberACKed++; - } - // Update last accessed time in response to getting seq acks. - if (numberACKed > 0) { - outgoing.setLastAccessed(TimeUtils.timeNow()); - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("SEQUENTIALLY ACKD SEQN = " + seqnum + ", (" + numberACKed + " acked)"); - } - // most recent remote IQ free space - mrrIQFreeSpace = rmaxQSize - sackList.length; - // let's look at average sacs.size(). If it is big, then this - // probably means we must back off because the system is slow. - // Our retrans Queue can be large and we can overwhelm the - // receiver with retransmissions. - // We will keep the rwin <= ave real input queue size. - int aveIQ = calcAVEIQ(sackList.length); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("remote IQ free space = " + mrrIQFreeSpace + " remote avg IQ occupancy = " + aveIQ); - } - - int retrans = 0; - - if (sackList.length > 0) { - Iterator eachRetrQElement = retrQ.iterator(); - int currentSACK = 0; - - while (eachRetrQElement.hasNext()) { - RetrQElt retrQElt = eachRetrQElement.next(); - - while (sackList[currentSACK] < retrQElt.seqnum) { - currentSACK++; - if (currentSACK == sackList.length) { - break; - } - } - if (currentSACK == sackList.length) { - break; - } - if (sackList[currentSACK] == retrQElt.seqnum) { - fc.packetACKed(retrQElt.seqnum); - numberACKed++; - eachRetrQElement.remove(); - - // Update RTT, RTO. Use only those that where acked w/o retrans - // otherwise the number is completely phony. - // Also, we keep the worst of the bunch we encounter. - long enqueuetime = retrQElt.enqueuedAt; - long dt = TimeUtils.toRelativeTimeMillis(lastACKTime, enqueuetime); - - // Update RTT, RTO - if (retrQElt.marked == 0) { - if (dt > rttCalcDt) { - rttCalcDt = dt; - rttCalcSeqnum = retrQElt.seqnum; - } - } else { - // In case we find no good candidate, make - // a guess by dividing by the number of attempts - // and keep the worst of them too. Since we - // know it may be too short, we will not use it - // if shortens rtt. - dt /= (retrQElt.marked + 1); - if (dt > fallBackDt) { - fallBackDt = dt; - fallBackSeqnum = retrQElt.seqnum; - } - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("SACKD SEQN = " + retrQElt.seqnum); - } - - // GC this stuff - retrQElt = null; - - } else { - // Retransmit? Only if there is a hole in the selected - // acknowledgement list. Otherwise let RTO deal. - - // Given that this SACK acknowledged messages still - // in the retrQ: - // seqnum is the max consectively SACKD message. - // seqnum < retrQElt.seqnum means a message has not reached - // receiver. EG: sacklist == 10,11,13 seqnum == 11 - // We retransmit 12. - if (seqnum < retrQElt.seqnum) { - fc.packetMissing(retrQElt.seqnum); - retrans++; - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETR: Fill hole, SACK, seqn#" + retrQElt.seqnum + ", Window =" + retrans); - } - } - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("SELECTIVE ACKD (" + numberACKed + ") " + retrans + " retrans wanted"); - } - } - - // Compute aveRTT on the most representative message, - // if any. That's the most accurate data. - // Failing that we use the fall back, provided that it not - // more recent than aveRTT ago - that would decrease aveRTT - // and in the absence of solid data, we do not want to take - // that risk. - if (rttCalcSeqnum != -1) { - calcRTT(rttCalcDt, rttCalcSeqnum); - // get fc to recompute rwindow - rwindow = fc.ackEventEnd(rmaxQSize, aveRTT, rttCalcDt); - } else if ((fallBackSeqnum != -1) && (fallBackDt > aveRTT)) { - calcRTT(fallBackDt, fallBackSeqnum); - // get fc to recompute rwindow - rwindow = fc.ackEventEnd(rmaxQSize, aveRTT, fallBackDt); - } - retrQ.notifyAll(); - } - } - - /** - * retransmit unacknowledged messages - * - * @param rwin max number of messages to retransmit - * @param triggerTime base time - * @return number of messages retransmitted. - */ - private int retransmit(int rwin, long triggerTime) { - - List retransMsgs = new ArrayList(); - - int numberToRetrans; - - // build a list of retries. - synchronized (retrQ) { - numberToRetrans = Math.min(retrQ.size(), rwin); - if (numberToRetrans > 0 && Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Number of messages pending retransmit =" + numberToRetrans); - } - for (int j = 0; j < numberToRetrans; j++) { - RetrQElt r = retrQ.get(j); - - // Mark message as retransmission - // need to know if a msg was retr or not for RTT eval - if (r.marked == 0) { - // First time: we're here because this message has not arrived, but - // the next one has. It may be an out of order message. - // Experience shows that such a message rarely arrives older than - // 1.2 * aveRTT. Beyond that, it's lost. It is also rare that we - // detect a hole within that delay. So, often enough, as soon as - // a hole is detected, it's time to resend...but not always. - if (TimeUtils.toRelativeTimeMillis(triggerTime, r.sentAt) < (6 * aveRTT) / 5) { - // Nothing to worry about, yet. - continue; - } - } else { - // That one has been retransmitted at least once already. - // So, we don't have much of a clue other than the age of the - // last transmission. It is unlikely that it arrives before aveRTT/2 - // but we have to anticipate its loss at the risk of making dupes. - // Otherwise the receiver will reach the hole, and that's really - // expensive. (Think that we've been trying for a while already.) - - if (TimeUtils.toRelativeTimeMillis(triggerTime, r.sentAt) < aveRTT) { - // Nothing to worry about, yet. - continue; - } - } - r.marked++; - // Make a copy to for sending - retransMsgs.add(r); - } - } - - // send the retries. - int retransmitted = 0; - Iterator eachRetrans = retransMsgs.iterator(); - - while (eachRetrans.hasNext()) { - RetrQElt r = eachRetrans.next(); - - eachRetrans.remove(); - try { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETRANSMIT seqn#" + r.seqnum); - } - Message sending = r.msg; - - // its possible that the message was - // acked while we were working in this - // case r.msg will have been nulled. - if (null != sending) { - sending = sending.clone(); - sending.replaceMessageElement(Defs.NAMESPACE, RETELT); - if (outgoing.send(sending)) { - r.sentAt = TimeUtils.timeNow(); - mrrIQFreeSpace--; - // assume we have now taken a slot - retransmitted++; - } else { - break; - // don't bother continuing sending now. - } - } - } catch (IOException e) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "FAILED RETRANS seqn#" + r.seqnum, e); - } - break; - // don't bother continuing. - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RETRANSMITED " + retransmitted + " of " + numberToRetrans); - } - - return retransmitted; - } - - /** - * Retransmission daemon thread - */ - private class Retransmitter implements Runnable { - - int nAtThisRTO = 0; - volatile int nretransmitted = 0; - - /** - * Constructor for the Retransmitter object - */ - public Retransmitter() { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("STARTED Reliable Retransmitter, RTO = " + RTO); - } - } - - /** - * Gets the retransCount attribute of the Retransmitter object - * - * @return The retransCount value - */ - public int getRetransCount() { - return nretransmitted; - } - - /** - * {@inheritDoc} - * - *

            Main processing method for the Retransmitter object - */ - public void run() { - try { - int idleCounter = 0; - - while (TimeUtils.toRelativeTimeMillis(closedAt) > 0) { - long conn_idle = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), outgoing.getLastAccessed()); - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine(outgoing + " idle for " + conn_idle); - } - - // check to see if we have not idled out. - if (outgoing.getIdleTimeout() < conn_idle) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Shutting down idle " + "connection " + outgoing); - } - - break; - } - - long sinceLastACK; - long oldestInQueueWait; - - synchronized (retrQ) { - try { - if (RTO > 0) { - retrQ.wait(RTO); - } - Thread.currentThread().setName( - "JXTA Reliable Retransmiter for " + this + " Queue size : " + retrQ.size()); - } catch (InterruptedException e) {// ignored - } - - if (TimeUtils.toRelativeTimeMillis(closedAt) <= 0) { - break; - } - - // see if we recently did a retransmit triggered by a SACK - long sinceLastSACKRetr = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), sackRetransTime); - - if (sinceLastSACKRetr < RTO) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("SACK retrans " + sinceLastSACKRetr + "ms ago"); - } - continue; - } - // See how long we've waited since RTO was set - sinceLastACK = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), lastACKTime); - - if (!retrQ.isEmpty()) { - RetrQElt elt = retrQ.get(0); - - oldestInQueueWait = TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), elt.enqueuedAt); - } else { - oldestInQueueWait = 0; - } - } - - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("Last ACK " + sinceLastACK + "ms ago. Age of oldest in Queue " + oldestInQueueWait + "ms."); - } - - // see if the queue has gone dead - if (oldestInQueueWait > outgoing.getMaxRetryAge()) { - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("Shutting down stale connection " + outgoing); - } - - break; - } - - // get real wait as max of age of oldest in retrQ and - // lastAck time - long realWait = Math.max(oldestInQueueWait, sinceLastACK); - - // Retransmit only if RTO has expired. - // a. real wait time is longer than RTO - // b. oldest message on Q has been there longer - // than RTO. This is necessary because we may - // have just sent a message, and we do not - // want to overrun the receiver. Also, we - // do not want to restransmit a message that - // has not been idle for the RTO. - if ((realWait >= RTO) && (oldestInQueueWait >= RTO)) { - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("RTO RETRANSMISSION [" + rwindow + "]"); - } - // retransmit - int retransed = retransmit(rwindow, TimeUtils.timeNow()); - - // Total - nretransmitted += retransed; - // number at this RTO - nAtThisRTO += retransed; - // See if real wait is too long and queue is non-empty - // Remote may be dead - double until max. - // Double after window restransmitted msgs at this RTO - // exceeds the rwindow, and we've had no response for - // twice the current RTO. - if ((retransed > 0) && (realWait >= 2 * RTO) && (nAtThisRTO >= 2 * rwindow)) { - RTO = (realWait > maxRTO ? maxRTO : 2 * RTO); - nAtThisRTO = 0; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine( - "RETRANSMISSION " + retransed + " retrans " + nAtThisRTO + " at this RTO (" + RTO + ") " - + nretransmitted + " total retrans"); - } - } else { - idleCounter += 1; - // reset RTO to min if we are idle - if (idleCounter == 2) { - RTO = minRTO; - idleCounter = 0; - nAtThisRTO = 0; - } - if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { - LOG.fine("IDLE : RTO=" + RTO + " WAIT=" + realWait); - } - } - } - } catch (Throwable all) { - LOG.log(Level.SEVERE, "Uncaught Throwable in thread :" + Thread.currentThread().getName(), all); - } finally { - hardClose(); - - retrThread = null; - - if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { - LOG.info("STOPPED Retransmit thread"); - } - } - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/Debug.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/Debug.java deleted file mode 100644 index 6ddf13f9..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/Debug.java +++ /dev/null @@ -1,125 +0,0 @@ -package net.jxta.impl.xindice; - - -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - - */ - -import net.jxta.impl.xindice.util.*; -import java.io.*; - -import java.util.logging.Logger; -import java.util.logging.Level; -import net.jxta.logging.Logging; - - -/** - * Debug is a debugging class for the Xindice Server. Because the class - * and the Debugging field are final, the Java compiler should always - * inline the methods and optimize them away if Debugging is set to false. - */ - -public final class Debug { - - /** - * Log4J Logger. Since this is the logger for the whole of xindice, we - * compose the name a little differently than normal. - **/ - private final static Logger LOG = Logger.getLogger(Debug.class.getName()); - - public static final boolean Debugging = true; - - public static void SetPrintStream(PrintStream out) { - ; - } - - public static void println(Object obj, Object message) { - if (Debugging) { - if (obj instanceof Named) { - LOG.fine(((Named) obj).getName() + ": " + message); - } else { - LOG.fine(message + "\n\t@ " + obj); - } - } - } - - public static void println(Object message) { - if (Debugging) { - LOG.fine(message.toString()); - } - } - - public static void println() { - if (Debugging) { - LOG.fine(""); - } - } - - public static void printStackTrace(Throwable t) { - if (Debugging) { - LOG.log(Level.WARNING, t.getMessage(), t); - } - } - - public static void setPrintStream(PrintStream outStream) { - ; - } - - public static void setPrefix(String debugPrefix) { - ; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/DBException.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/DBException.java deleted file mode 100644 index 9fdb2f62..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/DBException.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core; - -import net.jxta.impl.xindice.util.XindiceException; - -/** - * A DBException is thrown by the database if an exception occurs in the - * managing (creating, dropping) database objects such as Collections, - * Indexes, and XMLObjects. - */ -public class DBException extends XindiceException { - public int faultCode; - - public DBException() { - this(FaultCodes.GEN_UNKNOWN, "", null); - } - - public DBException(int faultCode) { - this(faultCode, "", null); - } - - public DBException(int faultCode, String message) { - this(faultCode, message, null); - } - - public DBException(int faultCode, String message, Throwable cause) { - super(message, cause); - this.faultCode = faultCode; - } - -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/DBObject.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/DBObject.java deleted file mode 100644 index 4b13995f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/DBObject.java +++ /dev/null @@ -1,127 +0,0 @@ -package net.jxta.impl.xindice.core; - - -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - - */ - - -/** - * DBObject is the interface implemented by all Xindice database objects. - * DBObjects are typically objects that can be managed using XML - * configuration information, which is typically stored in the system - * database. XMLObjects are not considered DBObjects because of the - * steps involved in having to generate them, which is usually - * compilation of source code. - */ - -public interface DBObject { - - /** - * create creates a new DBObject and any associated resources for the new - * DBObject, such as disk files, etc. - * - * @return Whether or not the DBObject was created - * @throws DBException if a DB error occurs - */ - boolean create() throws DBException; - - /** - * open opens the DBObject - * - * @return Whether or not the DBObject was opened - * @throws DBException if a DB error occurs - */ - boolean open() throws DBException; - - /** - * isOpened returns whether or not the DBObject is opened for business. - * - * @return The open status of the DBObject - * @throws DBException if a DB error occurs - */ - boolean isOpened() throws DBException; - - /** - * exists returns whether or not a physical representation of this - * DBObject actually exists. In the case of a HashFiler, this would - * check for the file, and in the case of an FTPFiler, it might - * perform a connection check. - * - * @return Whether or not the physical resource exists - * @throws DBException if a DB error occurs - */ - boolean exists() throws DBException; - - /** - * drop instructs the DBObjectimplementation to remove itself from - * existence. The DBObject's parent is responsible for removing any - * references to the DBObject in its own context. - * - * @return Whether or not the DBObject was dropped - * @throws DBException if a DB error occurs - */ - boolean drop() throws DBException; - - /** - * close closes the DBObject - * - * @return Whether or not the DBObject was closed - * @throws DBException if a DB error occurs - */ - boolean close() throws DBException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/FaultCodes.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/FaultCodes.java deleted file mode 100644 index b7f21a9c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/FaultCodes.java +++ /dev/null @@ -1,555 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core; - -import java.util.HashMap; -import java.util.Map; - -/** - * FaultCodes defines the Xindice specific fault codes and associated error - * messages. - */ -public abstract class FaultCodes { - - // the constants below have been pasted from - // org.apache.xindice.client.corba.db.FaultCodes - - // - // Constant value - // - public static final int GEN = (int) (0l); - - // - // Constant value - // - public static final int OBJ = (int) (100l); - - // - // Constant value - // - public static final int COL = (int) (200l); - - // - // Constant value - // - public static final int IDX = (int) (300l); - - // - // Constant value - // - public static final int TRX = (int) (400l); - - // - // Constant value - // - public static final int DBE = (int) (500l); - - // - // Constant value - // - public static final int QRY = (int) (600l); - - // - // Constant value - // - public static final int SEC = (int) (700l); - - // - // Constant value - // - public static final int URI = (int) (800l); - - // - // Constant value - // - public static final int JAVA = (int) (2000l); - - // - // Constant value - // - public static final int GEN_UNKNOWN = (int) (0l); - - // - // Constant value - // - public static final int GEN_GENERAL_ERROR = (int) (40l); - - // - // Constant value - // - public static final int GEN_CRITICAL_ERROR = (int) (70l); - - // - // Constant value - // - public static final int GEN_FATAL_ERROR = (int) (90l); - - // - // Constant value - // - public static final int OBJ_OBJECT_NOT_FOUND = (int) (100l); - - // - // Constant value - // - public static final int OBJ_METHOD_NOT_FOUND = (int) (101l); - - // - // Constant value - // - public static final int OBJ_NULL_RESULT = (int) (140l); - - // - // Constant value - // - public static final int OBJ_INVALID_RESULT = (int) (141l); - - // - // Constant value - // - public static final int OBJ_DUPLICATE_OBJECT = (int) (142l); - - // - // Constant value - // - public static final int OBJ_RUNTIME_EXCEPTION = (int) (170l); - - // - // Constant value - // - public static final int OBJ_CLASS_FORMAT_ERROR = (int) (171l); - - // - // Constant value - // - public static final int OBJ_INVALID_CONTEXT = (int) (172l); - - // - // Constant value - // - public static final int OBJ_CANNOT_CREATE = (int) (173l); - - // - // Constant value - // - public static final int COL_COLLECTION_NOT_FOUND = (int) (200l); - - // - // Constant value - // - public static final int COL_DOCUMENT_NOT_FOUND = (int) (201l); - - // - // Constant value - // - public static final int COL_DUPLICATE_COLLECTION = (int) (240l); - - // - // Constant value - // - public static final int COL_NULL_RESULT = (int) (241l); - - // - // Constant value - // - public static final int COL_NO_FILER = (int) (242l); - - // - // Constant value - // - public static final int COL_NO_INDEXMANAGER = (int) (242l); - - // - // Constant value - // - public static final int COL_DOCUMENT_MALFORMED = (int) (243l); - - // - // Constant value - // - public static final int COL_CANNOT_STORE = (int) (244l); - - // - // Constant value - // - public static final int COL_CANNOT_RETRIEVE = (int) (245l); - - // - // Constant value - // - public static final int COL_COLLECTION_READ_ONLY = (int) (246l); - - // - // Constant value - // - public static final int COL_COLLECTION_CLOSED = (int) (247l); - - // - // Constant value - // - public static final int COL_CANNOT_CREATE = (int) (270l); - - // - // Constant value - // - public static final int COL_CANNOT_DROP = (int) (271l); - - // - // Constant value - // - public static final int IDX_VALUE_NOT_FOUND = (int) (300l); - - // - // Constant value - // - public static final int IDX_INDEX_NOT_FOUND = (int) (301l); - - // - // Constant value - // - public static final int IDX_MATCHES_NOT_FOUND = (int) (340l); - - // - // Constant value - // - public static final int IDX_DUPLICATE_INDEX = (int) (341l); - - // - // Constant value - // - public static final int IDX_NOT_SUPPORTED = (int) (370l); - - // - // Constant value - // - public static final int IDX_STYLE_NOT_FOUND = (int) (371l); - - // - // Constant value - // - public static final int IDX_CORRUPTED = (int) (372l); - - // - // Constant value - // - public static final int IDX_CANNOT_CREATE = (int) (373l); - - // - // Constant value - // - public static final int TRX_DOC_LOCKED = (int) (400l); - - // - // Constant value - // - public static final int TRX_NO_CONTEXT = (int) (440l); - - // - // Constant value - // - public static final int TRX_NOT_ACTIVE = (int) (441l); - - // - // Constant value - // - public static final int TRX_NOT_SUPPORTED = (int) (470l); - - // - // Constant value - // - public static final int DBE_NO_PARENT = (int) (500l); - - // - // Constant value - // - public static final int DBE_CANNOT_DROP = (int) (570l); - - // - // Constant value - // - public static final int DBE_CANNOT_CREATE = (int) (571l); - - // - // Constant value - // - public static final int QRY_NULL_RESULT = (int) (600l); - - // - // Constant value - // - public static final int QRY_COMPILATION_ERROR = (int) (640l); - - // - // Constant value - // - public static final int QRY_PROCESSING_ERROR = (int) (641l); - - // - // Constant value - // - public static final int QRY_NOT_SUPPORTED = (int) (670l); - - // - // Constant value - // - public static final int QRY_STYLE_NOT_FOUND = (int) (671l); - - // - // Constant value - // - public static final int SEC_INVALID_USER = (int) (770l); - - // - // Constant value - // - public static final int SEC_INVALID_GROUP = (int) (771l); - - // - // Constant value - // - public static final int SEC_INVALID_ACCESS = (int) (772l); - - // - // Constant value - // - public static final int SEC_INVALID_CREDENTIALS = (int) (773l); - - // - // Constant value - // - public static final int URI_EMPTY = (int) (800l); - - // - // Constant value - // - public static final int URI_NULL = (int) (801l); - - // - // Constant value - // - public static final int URI_PARSE_ERROR = (int) (820l); - - // - // Constant value - // - public static final int JAVA_RUNTIME_ERROR = (int) (2070l); - - private static final Map FaultMsg = new HashMap(); - - private FaultCodes() {} - - static { - // General errors 0 series - putCodeMessage(GEN_UNKNOWN, "Unknown"); - putCodeMessage(GEN_GENERAL_ERROR, "General Error"); - putCodeMessage(GEN_CRITICAL_ERROR, "Critical Error"); - putCodeMessage(GEN_FATAL_ERROR, "Fatal Error"); - - // XMLObject invocation errors 100 series - putCodeMessage(OBJ_OBJECT_NOT_FOUND, "XMLObject Not Found"); - putCodeMessage(OBJ_METHOD_NOT_FOUND, "XMLObject Method Not Found"); - putCodeMessage(OBJ_NULL_RESULT, "XMLObject Null Result"); - putCodeMessage(OBJ_INVALID_RESULT, "XMLObject Invalid Result"); - putCodeMessage(OBJ_DUPLICATE_OBJECT, "XMLObject Duplicate Object"); - putCodeMessage(OBJ_RUNTIME_EXCEPTION, "XMLObject Runtime Exception"); - putCodeMessage(OBJ_CLASS_FORMAT_ERROR, "XMLObject Class Format Error"); - putCodeMessage(OBJ_INVALID_CONTEXT, "XMLObject Invalid Context"); - putCodeMessage(OBJ_CANNOT_CREATE, "XMLObject Cannot Create"); - - // Collection-related errors 200 series - putCodeMessage(COL_COLLECTION_NOT_FOUND, "Collection Not Found"); - putCodeMessage(COL_DOCUMENT_NOT_FOUND, "Collection Document Not Found"); - putCodeMessage(COL_DUPLICATE_COLLECTION, "Collection Duplicated"); - putCodeMessage(COL_NULL_RESULT, "Collection Null Result"); - putCodeMessage(COL_NO_FILER, "Collection No Filer"); - putCodeMessage(COL_NO_INDEXMANAGER, "Collection No IndexManager"); - putCodeMessage(COL_DOCUMENT_MALFORMED, "Collection Document Malformed"); - putCodeMessage(COL_CANNOT_STORE, "Collection Cannot Store"); - putCodeMessage(COL_CANNOT_RETRIEVE, "Collection Cannot Retrieve"); - putCodeMessage(COL_COLLECTION_READ_ONLY, "Collection Read-only"); - putCodeMessage(COL_COLLECTION_CLOSED, "Collection Closed"); - putCodeMessage(COL_CANNOT_CREATE, "Collection Cannot Create"); - putCodeMessage(COL_CANNOT_DROP, "Collection Cannot Drop"); - - // Index-related errors 300 series - putCodeMessage(IDX_VALUE_NOT_FOUND, "Index Value Not Found"); - putCodeMessage(IDX_INDEX_NOT_FOUND, "Index Not Found"); - putCodeMessage(IDX_MATCHES_NOT_FOUND, "Index Matches Not Found"); - putCodeMessage(IDX_DUPLICATE_INDEX, "Index Duplicate Index"); - putCodeMessage(IDX_NOT_SUPPORTED, "Index Not Supported"); - putCodeMessage(IDX_STYLE_NOT_FOUND, "Index Style Not Found"); - putCodeMessage(IDX_CORRUPTED, "Index Corrupted"); - putCodeMessage(IDX_CANNOT_CREATE, "Index Cannot Create"); - - // Transaction-related errors 400 series - putCodeMessage(TRX_DOC_LOCKED, "Transaction Document Locked"); - putCodeMessage(TRX_NO_CONTEXT, "Transaction No Context"); - putCodeMessage(TRX_NOT_ACTIVE, "Transaction Not Active"); - putCodeMessage(TRX_NOT_SUPPORTED, "Transaction Not Supported"); - - // Database-related errors 500 series - putCodeMessage(DBE_NO_PARENT, "Database No Parent"); - putCodeMessage(DBE_CANNOT_DROP, "Database Cannot Drop"); - putCodeMessage(DBE_CANNOT_CREATE, "Database Cannot Create"); - - // Query-related errors 600 series - putCodeMessage(QRY_NULL_RESULT, "Query Null Result"); - putCodeMessage(QRY_COMPILATION_ERROR, "Query Compilation Error"); - putCodeMessage(QRY_PROCESSING_ERROR, "Query Processing Error"); - putCodeMessage(QRY_NOT_SUPPORTED, "Query Not Supported"); - putCodeMessage(QRY_STYLE_NOT_FOUND, "Query Style Not Found"); - - // Security-related errors 700 series - putCodeMessage(SEC_INVALID_USER, "Security Invalid User"); - putCodeMessage(SEC_INVALID_GROUP, "Security Invalid Group"); - putCodeMessage(SEC_INVALID_ACCESS, "Security Invalid Access"); - putCodeMessage(SEC_INVALID_CREDENTIALS, "Security Invalid Credentials"); - - // URI-related errors 800 series - putCodeMessage(URI_EMPTY, "URI Empty"); - putCodeMessage(URI_NULL, "URI Null"); - putCodeMessage(URI_PARSE_ERROR, "URI Parse Error"); - - // Java-related errors 2000 series - putCodeMessage(JAVA_RUNTIME_ERROR, "Java Runtime Error"); - } - - private static void putCodeMessage(int code, String message) { - FaultMsg.put(code, message); - } - - /** - * getMessage returns a textual form for the specified fault code. - * - * @param code The Fault Code - * @return It's textual form - */ - public static String getMessage(int code) { - String msg = FaultMsg.get(code); - - return msg != null ? msg : ""; - } - - /** - * getFaultCodeType examines the provided exception to determine - * the general fault code that is associated with it. General - * fault codes are reduced from actual fault codes to be one of - * the GEN_ prefixed fault code values. - * - * @param e The Exception to examine - * @return The General Fault Code - */ - public static int getFaultCodeType(Exception e) { - int code = 0; - - if (e instanceof DBException) { - code = ((DBException) e).faultCode; - } - // Strip it to the General series - code = code % 100; - // Narrow to a General value - code = code - (code % 10); - return code; - } - - /** - * getFaultCodeSeries examines the provided exception to - * determine the fault code series that is associated with it. - * Series are reduced from actual fault codes to be one of - * the fault code prefixes (ex: COL, DB, SEC). - * - * @param e The Exception to examine - * @return The Fault Code Series - */ - public static int getFaultCodeSeries(Exception e) { - int code = 0; - - if (e instanceof DBException) { - code = ((DBException) e).faultCode; - } - // Strip it to the series - code = code - (code % 100); - return code; - } - - /** - * getFaultCode examines the provided exception to determine - * the fault code that is associated with it. - * - * @param e The Exception to examine - * @return The Fault Code - */ - public static int getFaultCode(Exception e) { - if (e instanceof DBException) { - return ((DBException) e).faultCode; - } else { - return 0; - } - } - - /** - * getFaultMessage examines the provided exception to determine - * the fault message that is associated with it. - * - * @param e The Exception to examine - * @return The Fault Message - */ - public static String getFaultMessage(Exception e) { - return getMessage(getFaultCode(e)); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/Key.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/Key.java deleted file mode 100644 index 8091cd09..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/Key.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.data; - -/** - * Key extends Value by providing a hash value for the Key. - */ -public final class Key extends Value { - private int hash = 0; - - public Key(Value value) { - super(value); - } - - public Key(byte[] data) { - super(data); - } - - public Key(byte[] data, int pos, int len) { - super(data, pos, len); - } - - public Key(String data) { - super(data); - } - - // TODO: This has to be revisited - private void calculateHash() { - hash = 0; - int pl = pos + len; - - for (int i = pos; i < pl; i++) { - hash = (hash << 5) ^ data[i]; - hash = hash % 1234567891; - } - hash = Math.abs(hash); - } - - public int getHash() { - if (hash == 0) { - calculateHash(); - } - return hash; - } - - @Override - public boolean equals(Value value) { - if (value instanceof Key) { - Key key = (Key) value; - - return getHash() == key.getHash() && compareTo(key) == 0; - } else { - return super.equals(value); - } - } - - @Override - public int hashCode() { - return getHash(); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof Key) { - return equals((Key) obj); - } else { - return super.equals(obj); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/Record.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/Record.java deleted file mode 100644 index 7b775f9f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/Record.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.data; - -import java.util.Map; - -/** - * Record is a container for Key/Value pairs. Record also provides - * metadata for a Value stored in the database. - */ -public final class Record { - public static final String CREATED = "created"; - public static final String MODIFIED = "modified"; - public static final String LIFETIME = "lifetime"; - public static final String EXPIRATION = "expiration"; - public static final String OWNER = "owner"; - public static final String GROUP = "group"; - - private Key key = null; - private Value value = null; - private Map meta = null; - - public Record() {} - - public Record(Key key, Value value, Map meta) { - this.key = key; - this.value = value; - this.meta = meta; - } - - public Record(Key key, Value value) { - this.key = key; - this.value = value; - } - - /** - * setKey sets the Record's Key. - * - * @param key The new key - */ - public void setKey(Key key) { - this.key = key; - } - - /** - * getKey returns the Record's Key. - * - * @return The Record's Key - */ - public Key getKey() { - return key; - } - - /** - * setValue sets the Record's Value. - * - * @param value The new Value - */ - public void setValue(Value value) { - this.value = value; - } - - /** - * setValue sets the Record's Value. - * - * @param value The new Value - */ - public void setValue(String value) { - this.value = new Value(value); - } - - /** - * getValue returns the Record's Value. - * - * @return The Record's Value - */ - public Value getValue() { - return value; - } - - /** - * getMetaData returns metadata about the Value. - * - * @param name The property name - * @return The metadata value - */ - public Object getMetaData(Object name) { - return meta != null ? meta.get(name) : null; - } - - @Override - public String toString() { - return - (key != null ? key.toString() : "") + (value != null ? " = " + value.toString() : "") - + (meta != null ? " meta " + meta.toString() : ""); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/RecordSet.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/RecordSet.java deleted file mode 100644 index b4b3074a..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/RecordSet.java +++ /dev/null @@ -1,103 +0,0 @@ -package net.jxta.impl.xindice.core.data; - - -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -import net.jxta.impl.xindice.core.DBException; - -/** - * RecordSet is an interface for iterating over a set of Records. - * It is almost always returned by Filers. - */ -public interface RecordSet { - - /** - * hasMoreRecords returns whether or not there are any Records - * left in the set. - * - * @return Whether there are any more Records - * @throws net.jxta.impl.xindice.core.filer.BTreeException if a DB exception occurs - */ - boolean hasMoreRecords() throws DBException; - - /** - * getNextRecord returns the next Record in the set. - * - * @return The next Record - * @throws net.jxta.impl.xindice.core.filer.BTreeException if a DB exception occurs - */ - Record getNextRecord() throws DBException; - - /** - * getNextKey returns the next Record's Key, and skips the - * RecordSet ahead to the next Record. - * - * @return The next Key - * @throws net.jxta.impl.xindice.core.filer.BTreeException if a DB exception occurs - */ - Key getNextKey() throws DBException; - - /** - * getNextValue returns the next Record's Value, and skips the - * RecordSet ahead to the next Record. - * - * @return The next Value - * @throws net.jxta.impl.xindice.core.filer.BTreeException if a DB exception occurs - */ - Value getNextValue() throws DBException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/Value.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/Value.java deleted file mode 100644 index 3291128b..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/data/Value.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.data; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; - -/** - * Value is the primary base class for all data storing objects. - * The content window of Value objects are immutable, but the - * underlying byte array is not. - * - */ -public class Value implements Comparable { - - protected byte[] data = null; - protected int pos = 0; - protected int len = -1; - - public Value(Value value) { - this.data = value.data; - this.pos = value.pos; - this.len = value.len; - } - - public Value(byte[] data) { - this.data = data; - this.len = data.length; - } - - public Value(byte[] data, int pos, int len) { - this.data = data; - this.pos = pos; - this.len = len; - } - - public Value(String data) { - try { - this.data = data.getBytes("utf-8"); - this.len = this.data.length; - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("Java doesn't support UTF-8 encoding", e); - } - } - - /** - * getData retrieves the data being stored by the Value as a byte array. - * - * @return The Data - */ - public final byte[] getData() { - if (len != data.length) { - byte[] b = new byte[len]; - - System.arraycopy(data, pos, b, 0, len); - return b; - } else { - return data; - } - } - - /** - * getLength retrieves the length of the data being stored by the Value. - * - * @return The Value length - */ - public final int getLength() { - return len; - } - - /** - * getInputStream returns an InputStream for the Value. - * - * @return An InputStream - */ - public final InputStream getInputStream() { - return new ByteArrayInputStream(data, pos, len); - } - - /** - * streamTo streams the content of the Value to an OutputStream. - * - * @param out the OutputStream - * @throws java.io.IOException if an io error occurs - */ - public final void streamTo(OutputStream out) throws IOException { - out.write(data, pos, len); - } - - public final void copyTo(byte[] tdata, int tpos) { - System.arraycopy(data, pos, tdata, tpos, len); - } - - public final void copyTo(byte[] tdata, int tpos, int len) { - System.arraycopy(data, pos, tdata, tpos, len); - } - - @Override - public final String toString() { - try { - return new String(data, pos, len, "utf-8"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("Java doesn't seem to support UTF-8!", e); - } - } - - @Override - public int hashCode() { - return toString().hashCode(); - } - - public boolean equals(Value value) { - return len == value.len && compareTo(value) == 0; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof Value) { - return equals((Value) obj); - } else { - return equals(new Value(obj.toString())); - } - } - - public final int compareTo(Value value) { - byte[] ddata = value.data; - int dpos = value.pos; - int dlen = value.len; - - int stop = len > dlen ? dlen : len; - - for (int i = 0; i < stop; i++) { - byte b1 = data[pos + i]; - byte b2 = ddata[dpos + i]; - - if (b1 == b2) { - // do nothing - } else { - short s1 = (short) (b1 >>> 0); - short s2 = (short) (b2 >>> 0); - - return s1 > s2 ? (i + 1) : -(i + 1); - } - } - - if (len == dlen) { - return 0; - } else { - return len > dlen ? stop + 1 : -(stop + 1); - } - } - - public final int compareTo(Object obj) { - if (obj instanceof Value) { - return compareTo((Value) obj); - } else { - return compareTo(new Value(obj.toString())); - } - } - - public final boolean startsWith(Value value) { - if (len < value.len) { - return false; - } - - byte[] ddata = value.data; - int dpos = value.pos; - - for (int i = 0; i < value.len; i++) { - if (data[i + pos] != ddata[i + dpos]) { - return false; - } - } - - return true; - } - - public final boolean endsWith(Value value) { - if (len < value.len) { - return false; - } - - byte[] ddata = value.data; - int dpos = value.pos; - - int offset = len - value.len; - - for (int i = 0; i < value.len; i++) { - if (data[i + pos + offset] != ddata[i + dpos]) { - return false; - } - } - - return true; - } - - public final boolean contains(Value value) { - if (len < value.len) { - return false; - } - boolean match; - byte[] ddata = value.data; - int dpos = value.pos; - - for (int offset = 0; offset <= len - value.len; offset++) { - match = true; - for (int i = 0; i < value.len; i++) { - if (data[i + pos + offset] != ddata[i + dpos]) { - match = false; - } - } - if (match) { - return true; - } - } - return false; - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTree.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTree.java deleted file mode 100644 index 958e456f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTree.java +++ /dev/null @@ -1,1194 +0,0 @@ -package net.jxta.impl.xindice.core.filer; - - -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - - */ - -import net.jxta.impl.xindice.core.DBException; -import net.jxta.impl.xindice.core.FaultCodes; -import net.jxta.impl.xindice.core.data.Value; -import net.jxta.impl.xindice.core.indexer.IndexQuery; - -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.lang.ref.WeakReference; -import java.util.Arrays; -import java.util.Map; -import java.util.WeakHashMap; - -import java.util.logging.Level; -import net.jxta.logging.Logging; -import java.util.logging.Logger; - - -/** - * BTree represents a Variable Magnitude Simple-Prefix B+Tree File. - * A BTree is a bit flexible in that it can be used for set or - * map-based indexing. HashFiler uses the BTree as a set for - * producing RecordSet entries. The Indexers use BTree as a map for - * indexing entity and attribute values in Documents. - *

            - * For those who don't know how a Simple-Prefix B+Tree works, the primary - * distinction is that instead of promoting actual keys to branch pages, - * when leaves are split, a shortest-possible separator is generated at - * the pivot. That separator is what is promoted to the parent branch - * (and continuing up the list). As a result, actual keys and pointers - * can only be found at the leaf level. This also affords the index the - * ability to ignore costly merging and redistribution of pages when - * deletions occur. Deletions only affect leaf pages in this - * implementation, and so it is entirely possible for a leaf page to be - * completely empty after all of its keys have been removed. - *

            - * Also, the Variable Magnitude attribute means that the btree attempts - * to store as many values and pointers on one page as is possible. - *

            - * This implementation supports the notion of nested roots. This means - * that you can create a btree where the pointers actually point to the - * root of a separate btree being managed in the same file. - */ - -public class BTree extends Paged { - private final static Logger LOG = Logger.getLogger(BTree.class.getName()); - protected static final byte LEAF = 1; - protected static final byte BRANCH = 2; - protected static final byte STREAM = 3; - - /** - * Cache of the recently used tree nodes. - * - * Cache contains weak references to the BTreeNode objects, keys are page numbers (Long objects). - * Access synchronized by this map itself. - */ - private final Map> cache = new WeakHashMap>(); - - private BTreeFileHeader fileHeader; - private BTreeRootInfo rootInfo; - private BTreeNode rootNode; - - public BTree() { - super(); - fileHeader = (BTreeFileHeader) getFileHeader(); - } - - public BTree(File file) { - this(); - setFile(file); - } - - /** - * Setting this option forces all system buffers with the underlying device - * if sync is set writes return after all modified data and attributes of the DB - * have been written to the device. - * by default sync is true. - * {@link java.io.FileDescriptor} - * @param sync if true, invokes FD.sync(), an expensive operation, required to ensure high consistency, especially - * with system failures. - */ - public void setSync(boolean sync) { - this.sync = sync; - } - - @Override - public boolean open() throws DBException { - if (super.open()) { - long p = fileHeader.getRootPage(); - - rootInfo = new BTreeRootInfo(p); - rootNode = getBTreeNode(p, null); - return true; - } else { - return false; - } - } - - @Override - public boolean create() throws DBException { - if (super.create()) { - try { - // Don't call this.open() as it will try to read rootNode from the disk - super.open(); - - long p = fileHeader.getRootPage(); - - rootInfo = new BTreeRootInfo(p); - - // Initialize root node - rootNode = new BTreeNode(getPage(p), null, new Value[0], new long[0]); - rootNode.ph.setStatus(LEAF); - rootNode.write(); - synchronized (cache) { - cache.put(rootNode.page.getPageNum(), new WeakReference(rootNode)); - } - close(); - return true; - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Failed to create BTree, return false", e); - } - } - } - return false; - } - - /** - * addValue adds a Value to the BTree and associates a pointer with - * it. The pointer can be used for referencing any type of data, it - * just so happens that Xindice uses it for referencing pages of - * associated data in the BTree file or other files. - * - * @param value The Value to add - * @param pointer The pointer to associate with it - * @return The previous value for the pointer (or -1) - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - public long addValue(Value value, long pointer) throws IOException, BTreeException { - return getRootNode().addValue(value, pointer); - } - - /** - * addValue adds a Value to the BTree and associates a pointer with - * it. The pointer can be used for referencing any type of data, it - * just so happens that Xindice uses it for referencing pages of - * associated data in the BTree file or other files. - * - * @param root The BTree's root information (for nested trees) - * @param value The Value to add - * @param pointer The pointer to associate with it - * @return The previous value for the pointer (or -1) - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - public long addValue(BTreeRootInfo root, Value value, long pointer) throws IOException, BTreeException { - return getRootNode(root).addValue(value, pointer); - } - - /** - * removeValue removes a Value from the BTree and returns the - * associated pointer for it. - * - * @param value The Value to remove - * @return The pointer that was associated with it - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - public long removeValue(Value value) throws IOException, BTreeException { - return getRootNode().removeValue(value); - } - - /** - * removeValue removes a Value from the BTree and returns the - * associated pointer for it. - * - * @param root The BTree's root information (for nested trees) - * @param value The Value to remove - * @return The pointer that was associated with it - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - public long removeValue(BTreeRootInfo root, Value value) throws IOException, BTreeException { - return getRootNode(root).removeValue(value); - } - - /** - * findValue finds a Value in the BTree and returns the associated - * pointer for it. - * - * @param value The Value to find - * @return The pointer that was associated with it - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - public long findValue(Value value) throws IOException, BTreeException { - return getRootNode().findValue(value); - } - - /** - * findValue finds a Value in the BTree and returns the associated - * pointer for it. - * - * @param root The BTree's root information (for nested trees) - * @param value The Value to find - * @return The pointer that was associated with it - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - public long findValue(BTreeRootInfo root, Value value) throws IOException, BTreeException { - return getRootNode(root).findValue(value); - } - - /** - * query performs a query against the BTree and performs callback - * operations to report the search results. - * - * @param query The IndexQuery to use (or null for everything) - * @param callback The callback instance - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - public void query(IndexQuery query, BTreeCallback callback) throws IOException, BTreeException { - getRootNode().query(query, callback); - } - - /** - * query performs a query against the BTree and performs callback - * operations to report the search results. - * - * @param root The BTree's root information (for nested trees) - * @param query The IndexQuery to use (or null for everything) - * @param callback The callback instance - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - public void query(BTreeRootInfo root, IndexQuery query, BTreeCallback callback) throws IOException, BTreeException { - getRootNode(root).query(query, callback); - } - - /** - * createBTreeRoot creates a new BTree root node in the BTree file - * based on the provided value for the main tree. - * - * @param v The sub-tree Value to create - * @return The new BTreeRootInfo instance - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - protected final BTreeRootInfo createBTreeRoot(Value v) throws IOException, BTreeException { - BTreeNode n = createBTreeNode(BTree.LEAF, null); - n.write(); - long position = n.page.getPageNum(); - - addValue(v, position); - return new BTreeRootInfo(v, position); - } - - /** - * createBTreeRoot creates a new BTree root node in the BTree file - * based on the provided root information, and value for the tree. - * - * @param root The BTreeRootInfo to build off of - * @param v The sub-tree Value to create - * @return The new BTreeRootInfo instance - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - protected final BTreeRootInfo createBTreeRoot(BTreeRootInfo root, Value v) throws IOException, BTreeException { - BTreeNode n = createBTreeNode(BTree.LEAF, null); - - n.write(); - - long position = n.page.getPageNum(); - - addValue(v, position); - return new BTreeRootInfo(root, v, position); - } - - /** - * findBTreeRoot searches for a BTreeRoot in the file and returns - * the BTreeRootInfo for the specified value based on the main tree. - * - * @param v The sub-tree Value to search for - * @return The new BTreeRootInfo instance - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - protected final BTreeRootInfo findBTreeRoot(Value v) throws IOException, BTreeException { - long position = findValue(v); - - return new BTreeRootInfo(v, position); - } - - /** - * findBTreeRoot searches for a BTreeRoot in the file and returns - * the BTreeRootInfo for the specified value based on the provided - * BTreeRootInfo value. - * - * @param root The BTreeRootInfo to search from - * @param v The sub-tree Value to search for - * @return The new BTreeRootInfo instance - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - protected final BTreeRootInfo findBTreeRoot(BTreeRootInfo root, Value v) throws IOException, BTreeException { - long position = findValue(root, v); - - return new BTreeRootInfo(root, v, position); - } - - /** - * setRootNode resets the root for the specified root object to the - * provided BTreeNode's page number. - * - * This method is not thread safe. - * - * @param root The root to reset - * @param newRoot the new root node to use - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - protected final void setRootNode(BTreeRootInfo root, BTreeNode newRoot) throws IOException, BTreeException { - BTreeRootInfo parent = root.getParent(); - - if (parent == null) { - rootNode = newRoot; - long p = rootNode.page.getPageNum(); - - rootInfo.setPage(p); - fileHeader.setRootPage(p); - } else { - long p = newRoot.page.getPageNum(); - - root.setPage(p); - addValue(parent, root.name, p); - } - } - - /** - * setRootNode resets the file's root to the provided - * BTreeNode's page number. - * - * This method is not thread safe. - * - * @param rootNode the new root node to use - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - protected final void setRootNode(BTreeNode rootNode) throws IOException, BTreeException { - setRootNode(rootInfo, rootNode); - } - - /** - * getRootNode retreives the BTree node for the specified - * root object. - * - * @param root The root object to retrieve with - * @return The root node - */ - protected final BTreeNode getRootNode(BTreeRootInfo root) { - if (root.page == rootInfo.page) { - return rootNode; - } else { - return getBTreeNode(root.getPage(), null); - } - } - - /** - * getRootNode retreives the BTree node for the file's root. - * - * @return The root node - */ - protected final BTreeNode getRootNode() { - return rootNode; - } - - private BTreeNode getBTreeNode(long page, BTreeNode parent) { - try { - BTreeNode node = null; - - synchronized (cache) { - WeakReference ref = cache.get(page); - - if (ref != null) { - node = ref.get(); - } - - if (node == null) { - node = new BTreeNode(getPage(page), parent); - } else { - node.parent = parent; - } - - cache.put(node.page.getPageNum(), new WeakReference(node)); - } - - node.read(); - return node; - } catch (Exception e) { - if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { - LOG.log(Level.WARNING, "Ignored exception", e); - } - return null; - } - } - - private BTreeNode createBTreeNode(byte status, BTreeNode parent) throws IOException { - Page p = getFreePage(); - BTreeNode node = new BTreeNode(p, parent, new Value[0], new long[0]); - - node.ph.setStatus(status); - synchronized (cache) { - cache.put(p.getPageNum(), new WeakReference(node)); - } - return node; - } - - /** - * BTreeRootInfo - */ - public final class BTreeRootInfo { - private final BTreeRootInfo parent; - private final Value name; - private long page; - - public BTreeRootInfo(BTreeRootInfo parent, String name, long page) { - this.parent = parent; - this.name = new Value(name); - this.page = page; - } - - public BTreeRootInfo(BTreeRootInfo parent, Value name, long page) { - this.parent = parent; - this.name = name; - this.page = page; - } - - public BTreeRootInfo(String name, long page) { - this.parent = rootInfo; - this.name = new Value(name); - this.page = page; - } - - public BTreeRootInfo(Value name, long page) { - this.parent = rootInfo; - this.name = name; - this.page = page; - } - - private BTreeRootInfo(long page) { - parent = null; - name = null; - this.page = page; - } - - public BTreeRootInfo getParent() { - return parent; - } - - public Value getName() { - return name; - } - - public synchronized long getPage() { - return page; - } - - public synchronized void setPage(long page) { - this.page = page; - } - } - - - /** - * BTreeNode - */ - private final class BTreeNode { - private final Page page; - private final BTreePageHeader ph; - private Value[] values; - private long[] ptrs; - private BTreeNode parent; - private boolean loaded; - - public BTreeNode(Page page) { - this(page, null); - } - - public BTreeNode(Page page, BTreeNode parent) { - this.page = page; - this.parent = parent; - this.ph = (BTreePageHeader) page.getPageHeader(); - } - - public BTreeNode(Page page, BTreeNode parent, Value[] values, long[] ptrs) { - this(page, parent); - set(values, ptrs); - this.loaded = true; - } - - /** - * Sets values and pointers. - * Internal (to the BTreeNode) method, not synchronized. - * @param ptrs pointers - * @param values their values - */ - private void set(Value[] values, long[] ptrs) { - this.values = values; - this.ph.setValueCount((short) values.length); - this.ptrs = ptrs; - } - - /** - * Reads node only if it is not loaded yet - * @throws java.io.IOException if an io error occurs - */ - public synchronized void read() throws IOException { - if (!this.loaded) { - Value v = readValue(page); - DataInputStream is = new DataInputStream(v.getInputStream()); - - // Read in the Values - values = new Value[ph.getValueCount()]; - for (int i = 0; i < values.length; i++) { - short valSize = is.readShort(); - byte[] b = new byte[valSize]; - - is.read(b); - values[i] = new Value(b); - } - - // Read in the pointers - ptrs = new long[ph.getPointerCount()]; - for (int i = 0; i < ptrs.length; i++) { - ptrs[i] = is.readLong(); - } - - this.loaded = true; - } - } - - public synchronized void write() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(fileHeader.getWorkSize()); - DataOutputStream os = new DataOutputStream(bos); - - // Write out the Values - for (Value value : values) { - os.writeShort(value.getLength()); - value.streamTo(os); - } - - // Write out the pointers - for (long ptr : ptrs) { - os.writeLong(ptr); - } - - writeValue(page, new Value(bos.toByteArray())); - } - - /** - * Internal (to the BTreeNode) method. - * Because this method is called only by BTreeNode itself, no synchronization done inside of this method. - * @param idx the index - * @return the BTree node - */ - private BTreeNode getChildNode(int idx) { - if (ph.getStatus() == BRANCH && idx >= 0 && idx < ptrs.length) { - return getBTreeNode(ptrs[idx], this); - } else { - return null; - } - } - - /* Not used - private synchronized void getChildStream(int idx, Streamable stream) throws IOException { - if (ph.getStatus() == LEAF && idx >= 0 && idx < ptrs.length) { - Value v = readValue(ptrs[idx]); - DataInputStream dis = new DataInputStream(v.getInputStream()); - stream.read(dis); - } - } - */ - - public synchronized long removeValue(Value value) throws IOException, BTreeException { - int idx = Arrays.binarySearch(values, value); - - switch (ph.getStatus()) { - case BRANCH: - idx = idx < 0 ? -(idx + 1) : idx + 1; - return getChildNode(idx).removeValue(value); - - case LEAF: - if (idx < 0) { - throw new BTreeNotFoundException("Value '" + value + "' doesn't exist"); - } else { - long oldPtr = ptrs[idx]; - - set(deleteArrayValue(values, idx), deleteArrayLong(ptrs, idx)); - - write(); - return oldPtr; - } - - default: - throw new BTreeCorruptException("Invalid page type '" + ph.getStatus() + "' in removeValue"); - } - } - - public synchronized long addValue(Value value, long pointer) throws IOException, BTreeException { - if (value == null) { - throw new BTreeException(FaultCodes.DBE_CANNOT_CREATE, "Can't add a null Value"); - } - - int idx = Arrays.binarySearch(values, value); - - switch (ph.getStatus()) { - case BRANCH: - idx = idx < 0 ? -(idx + 1) : idx + 1; - return getChildNode(idx).addValue(value, pointer); - - case LEAF: - if (idx >= 0) { - // Value was found... Overwrite - long oldPtr = ptrs[idx]; - - ptrs[idx] = pointer; - - set(values, ptrs); - - write(); - return oldPtr; - } else { - // Value was not found - idx = -(idx + 1); - - // Check to see if we've exhausted the block - boolean split = needSplit(value); - - set(insertArrayValue(values, value, idx), insertArrayLong(ptrs, pointer, idx)); - - if (split) { - split(); - } else { - write(); - } - } - return -1; - - default: - throw new BTreeCorruptException("Invalid Page Type In addValue"); - } - } - - private synchronized void promoteValue(Value value, long rightPointer) throws IOException, BTreeException { - // Check to see if we've exhausted the block - boolean split = needSplit(value); - - int idx = Arrays.binarySearch(values, value); - - idx = idx < 0 ? -(idx + 1) : idx + 1; - - set(insertArrayValue(values, value, idx), insertArrayLong(ptrs, rightPointer, idx + 1)); - - if (split) { - split(); - } else { - write(); - } - } - - private Value getSeparator(Value value1, Value value2) { - int idx = value1.compareTo(value2); - byte[] b = new byte[Math.abs(idx)]; - - value2.copyTo(b, 0, b.length); - return new Value(b); - } - - /** - * Do we need to split this node after adding one more value? - * @param value the value to split - * @return true if successful - */ - private boolean needSplit(Value value) { - // Do NOT split if just 4 key/values are in the node. - return this.values.length > 4 && // CurrLength + one Long pointer + value length + one short - this.ph.getDataLen() + 8 + value.getLength() + 2 > BTree.this.fileHeader.getWorkSize(); - } - - /** - * Internal to the BTreeNode method - * @throws java.io.IOException if an io error occurs - * @throws BTreeException if a DB exception occurs - */ - private void split() throws IOException, BTreeException { - Value[] leftVals; - Value[] rightVals; - long[] leftPtrs; - long[] rightPtrs; - Value separator; - - short vc = ph.getValueCount(); - int pivot = vc / 2; - - // Split the node into two nodes - switch (ph.getStatus()) { - case BRANCH: - leftVals = new Value[pivot]; - leftPtrs = new long[leftVals.length + 1]; - rightVals = new Value[vc - (pivot + 1)]; - rightPtrs = new long[rightVals.length + 1]; - - System.arraycopy(values, 0, leftVals, 0, leftVals.length); - System.arraycopy(ptrs, 0, leftPtrs, 0, leftPtrs.length); - System.arraycopy(values, leftVals.length + 1, rightVals, 0, rightVals.length); - System.arraycopy(ptrs, leftPtrs.length, rightPtrs, 0, rightPtrs.length); - - separator = values[leftVals.length]; - break; - - case LEAF: - leftVals = new Value[pivot]; - leftPtrs = new long[leftVals.length]; - rightVals = new Value[vc - pivot]; - rightPtrs = new long[rightVals.length]; - - System.arraycopy(values, 0, leftVals, 0, leftVals.length); - System.arraycopy(ptrs, 0, leftPtrs, 0, leftPtrs.length); - System.arraycopy(values, leftVals.length, rightVals, 0, rightVals.length); - System.arraycopy(ptrs, leftPtrs.length, rightPtrs, 0, rightPtrs.length); - - separator = getSeparator(leftVals[leftVals.length - 1], rightVals[0]); - break; - - default: - throw new BTreeCorruptException("Invalid Page Type In split"); - } - - // Promote the pivot to the parent branch - if (parent == null) { - // This can only happen if this is the root - BTreeNode rNode = createBTreeNode(ph.getStatus(), this); - - rNode.set(rightVals, rightPtrs); - - BTreeNode lNode = createBTreeNode(ph.getStatus(), this); - - lNode.set(leftVals, leftPtrs); - - ph.setStatus(BRANCH); - set(new Value[] { - separator - }, new long[] {lNode.page.getPageNum(), rNode.page.getPageNum()}); - - write(); - rNode.write(); - lNode.write(); - } else { - set(leftVals, leftPtrs); - - BTreeNode rNode = createBTreeNode(ph.getStatus(), parent); - - rNode.set(rightVals, rightPtrs); - - write(); - rNode.write(); - parent.promoteValue(separator, rNode.page.getPageNum()); - } - } - - // /////////////////////////////////////////////////////////////// - - public synchronized long findValue(Value value) throws IOException, BTreeException { - if (value == null) { - throw new BTreeNotFoundException("Can't search on null Value"); - } - - int idx = Arrays.binarySearch(values, value); - - switch (ph.getStatus()) { - case BRANCH: - idx = idx < 0 ? -(idx + 1) : idx + 1; - return getChildNode(idx).findValue(value); - - case LEAF: - if (idx < 0) { - throw new BTreeNotFoundException("Value '" + value + "' doesn't exist"); - } else { - return ptrs[idx]; - } - - default: - throw new BTreeCorruptException("Invalid page type '" + ph.getStatus() + "' in findValue"); - } - } - - // query is a BEAST of a method - public synchronized void query(IndexQuery query, BTreeCallback callback) throws IOException, BTreeException { - if (query != null && query.getOperator() != IndexQuery.ANY) { - Value[] qvals = query.getValues(); - int leftIdx = Arrays.binarySearch(values, qvals[0]); - int rightIdx = qvals.length > 1 ? Arrays.binarySearch(values, qvals[qvals.length - 1]) : leftIdx; - - switch (ph.getStatus()) { - case BRANCH: - leftIdx = leftIdx < 0 ? -(leftIdx + 1) : leftIdx + 1; - rightIdx = rightIdx < 0 ? -(rightIdx + 1) : rightIdx + 1; - - switch (query.getOperator()) { - case IndexQuery.BWX: - case IndexQuery.BW: - case IndexQuery.IN: - case IndexQuery.SW: - // TODO: Can leftIdx be less than 0 here? - if (leftIdx < 0) { - leftIdx = 0; - } - if (rightIdx > ptrs.length - 1) { - rightIdx = ptrs.length - 1; - } - for (int i = leftIdx; i <= rightIdx; i++) { - getChildNode(i).query(query, callback); - } - break; - - case IndexQuery.NBWX: - case IndexQuery.NBW: - case IndexQuery.NIN: - case IndexQuery.NSW: - if (leftIdx > ptrs.length - 1) { - leftIdx = ptrs.length - 1; - } - for (int i = 0; i <= leftIdx; i++) { - getChildNode(i).query(query, callback); - } - if (rightIdx < 0) { - rightIdx = 0; - } - for (int i = rightIdx; i < ptrs.length; i++) { - getChildNode(i).query(query, callback); - } - break; - - case IndexQuery.EQ: - getChildNode(leftIdx).query(query, callback); - break; - - case IndexQuery.LT: - case IndexQuery.LEQ: - if (leftIdx > ptrs.length - 1) { - leftIdx = ptrs.length - 1; - } - for (int i = 0; i <= leftIdx; i++) { - getChildNode(i).query(query, callback); - } - break; - - case IndexQuery.GT: - case IndexQuery.GEQ: - if (rightIdx < 0) { - rightIdx = 0; - } - for (int i = rightIdx; i < ptrs.length; i++) { - getChildNode(i).query(query, callback); - } - break; - - case IndexQuery.NEQ: - default: - for (int i = 0; i < ptrs.length; i++) { - getChildNode(i).query(query, callback); - } - break; - } - break; - - case LEAF: - switch (query.getOperator()) { - case IndexQuery.EQ: - if (leftIdx >= 0) { - callback.indexInfo(values[leftIdx], ptrs[leftIdx]); - } - break; - - case IndexQuery.NEQ: - for (int i = 0; i < ptrs.length; i++) { - if (i != leftIdx) { - callback.indexInfo(values[i], ptrs[i]); - } - } - break; - - case IndexQuery.BWX: - case IndexQuery.BW: - case IndexQuery.SW: - case IndexQuery.IN: - if (leftIdx < 0) { - leftIdx = -(leftIdx + 1); - } - if (rightIdx < 0) { - rightIdx = -(rightIdx + 1); - } - for (int i = 0; i < ptrs.length; i++) { // FIXME: VG: Optimize this loop - if (i >= leftIdx && i <= rightIdx && query.testValue(values[i])) { - callback.indexInfo(values[i], ptrs[i]); - } - } - break; - - case IndexQuery.NBWX: - case IndexQuery.NBW: - case IndexQuery.NSW: - if (leftIdx < 0) { - leftIdx = -(leftIdx + 1); - } - if (rightIdx < 0) { - rightIdx = -(rightIdx + 1); - } - for (int i = 0; i < ptrs.length; i++) { - if ((i <= leftIdx || i >= rightIdx) && query.testValue(values[i])) { - callback.indexInfo(values[i], ptrs[i]); - } - } - break; - - case IndexQuery.LT: - case IndexQuery.LEQ: - if (leftIdx < 0) { - leftIdx = -(leftIdx + 1); - } - for (int i = 0; i < ptrs.length; i++) { - if (i <= leftIdx && query.testValue(values[i])) { - callback.indexInfo(values[i], ptrs[i]); - } - } - break; - - case IndexQuery.GT: - case IndexQuery.GEQ: - if (rightIdx < 0) { - rightIdx = -(rightIdx + 1); - } - - for (int i = 0; i < ptrs.length; i++) { - if (i >= rightIdx && query.testValue(values[i])) { - callback.indexInfo(values[i], ptrs[i]); - } - } - break; - - case IndexQuery.NIN: - default: - for (int i = 0; i < ptrs.length; i++) { - if (query.testValue(values[i])) { - callback.indexInfo(values[i], ptrs[i]); - } - } - break; - } - break; - - default: - throw new BTreeCorruptException("Invalid Page Type In query"); - } - - } else { - // No Query - Just Walk The Tree - switch (ph.getStatus()) { - case BRANCH: - for (int i = 0; i < ptrs.length; i++) { - getChildNode(i).query(query, callback); - } - break; - - case LEAF: - for (int i = 0; i < values.length; i++) { - callback.indexInfo(values[i], ptrs[i]); - } - break; - - default: - throw new BTreeCorruptException("Invalid Page Type In query"); - } - } - } - } - - // ////////////////////////////////////////////////////////////////// - - @Override - public FileHeader createFileHeader() { - BTreeFileHeader header = new BTreeFileHeader(); - - header.setPageCount(1); - header.setTotalCount(1); - return header; - } - - @Override - public FileHeader createFileHeader(boolean read) throws IOException { - return new BTreeFileHeader(read); - } - - @Override - public FileHeader createFileHeader(long pageCount) { - return new BTreeFileHeader(pageCount); - } - - @Override - public FileHeader createFileHeader(long pageCount, int pageSize) { - return new BTreeFileHeader(pageCount, pageSize); - } - - @Override - public PageHeader createPageHeader() { - return new BTreePageHeader(); - } - - /** - * BTreeFileHeader - */ - - protected class BTreeFileHeader extends FileHeader { - private long rootPage = 0; - - public BTreeFileHeader() {} - - public BTreeFileHeader(long pageCount) { - super(pageCount); - } - - public BTreeFileHeader(long pageCount, int pageSize) { - super(pageCount, pageSize); - } - - public BTreeFileHeader(boolean read) throws IOException { - super(read); - } - - @Override - public synchronized void read(RandomAccessFile raf) throws IOException { - super.read(raf); - rootPage = raf.readLong(); - } - - @Override - public synchronized void write(RandomAccessFile raf) throws IOException { - super.write(raf); - raf.writeLong(rootPage); - } - - /** - * The root page of the storage tree - * @param rootPage the new root page - */ - public synchronized final void setRootPage(long rootPage) { - this.rootPage = rootPage; - setDirty(); - } - - /** - * The root page of the storage tree - * @return the root page - */ - public synchronized final long getRootPage() { - return rootPage; - } - } - - - /** - * BTreePageHeader - */ - - protected class BTreePageHeader extends PageHeader { - private short valueCount = 0; - - public BTreePageHeader() {} - - public BTreePageHeader(DataInputStream dis) throws IOException { - super(dis); - } - - @Override - public synchronized void read(DataInputStream dis) throws IOException { - super.read(dis); - if (getStatus() == UNUSED) { - return; - } - - valueCount = dis.readShort(); - } - - @Override - public synchronized void write(DataOutputStream dos) throws IOException { - super.write(dos); - dos.writeShort(valueCount); - } - - /** The number of values stored by this page - * @param valueCount the value count - */ - public synchronized final void setValueCount(short valueCount) { - this.valueCount = valueCount; - setDirty(); - } - - /** - * The number of values stored by this page - * @return the value count - */ - public synchronized final short getValueCount() { - return valueCount; - } - - /** - * The number of pointers stored by this page - * @return the pointer count - */ - public synchronized final short getPointerCount() { - if (getStatus() == BRANCH) { - return (short) (valueCount + 1); - } else { - return valueCount; - } - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeCallback.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeCallback.java deleted file mode 100644 index fe04d57c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeCallback.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.filer; - -import net.jxta.impl.xindice.core.data.Value; - -/** - * BTreeCallback is a callback interface for BTree queries. - */ - -public interface BTreeCallback { - - /** - * indexInfo is a callback method for index enumeration. - * - * @param value The Value being reported - * @param pointer The data pointer being reported - * @return false to cancel the enumeration - */ - boolean indexInfo(Value value, long pointer); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeCorruptException.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeCorruptException.java deleted file mode 100644 index 5d435974..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeCorruptException.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.filer; - -import net.jxta.impl.xindice.core.FaultCodes; - -/** - * A BTreecorruptException is thrown by the BTree if the BTree - * appears to be corrupted in some way. - */ - -public final class BTreeCorruptException extends BTreeException { - public BTreeCorruptException() { - super(FaultCodes.IDX_CORRUPTED); - } - - public BTreeCorruptException(String message) { - super(FaultCodes.IDX_CORRUPTED, message); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeException.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeException.java deleted file mode 100644 index d475410e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeException.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.filer; - -/** - * A BTreeException is thrown by the BTree if an exception occurs - * in the managing of the BTree. - */ -public class BTreeException extends FilerException { - public BTreeException(int faultCode) { - super(faultCode); - } - - public BTreeException(int faultCode, String message) { - super(faultCode, message); - } - - public BTreeException(int faultCode, String message, Throwable cause) { - super(faultCode, message, cause); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeFiler.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeFiler.java deleted file mode 100644 index 4ad7990f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeFiler.java +++ /dev/null @@ -1,491 +0,0 @@ -package net.jxta.impl.xindice.core.filer; - - -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -import net.jxta.impl.xindice.core.DBException; -import net.jxta.impl.xindice.core.FaultCodes; -import net.jxta.impl.xindice.core.data.Key; -import net.jxta.impl.xindice.core.data.Record; -import net.jxta.impl.xindice.core.data.RecordSet; -import net.jxta.impl.xindice.core.data.Value; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -/** - * BTreeFiler is a Filer implementation based on the BTree class. - */ -public final class BTreeFiler extends BTree implements Filer { - - protected static final byte RECORD = 20; - - private static final short PAGESIZE = 512; - // TODO: MAXKEYSIZE might need tuning - private static final short MAXKEYSIZE = 256; - - private BTreeFilerHeader fileHeader; - - private static final int DBE_CANNOT_READ = (int) (572l); - - public BTreeFiler() { - super(); - fileHeader = (BTreeFilerHeader) getFileHeader(); - } - - public void setLocation(String dir, String file) { - setFile(new File(dir, file + ".tbl")); - } - - public String getName() { - return getFile().getName(); - } - - @Override - public boolean open() throws DBException { - if (super.open()) { - // These are the only properties that can be changed after creation - fileHeader.setMaxKeySize(MAXKEYSIZE); - return true; - } else { - return false; - } - } - - @Override - public boolean create() throws DBException { - fileHeader.setPageSize(PAGESIZE); - fileHeader.setMaxKeySize(MAXKEYSIZE); - return super.create(); - } - - public Record readRecord(Key key) throws DBException { - if (key == null || key.getLength() == 0) { - return null; - } - - checkOpened(); - try { - long pos = findValue(key); - Record record = readRecord(pos); - - record.setKey(key); - return record; - } catch (BTreeNotFoundException b) {// do nothing - } catch (BTreeException b) { - throw b; - } catch (IOException e) { - throw new FilerException(DBE_CANNOT_READ, "Can't read record '" + key + "': " + e.getMessage(), e); - } - return null; - } - - public Record readRecord(long pos) throws DBException { - checkOpened(); - try { - Page startPage = getPage(pos); - Value v = readValue(startPage); - BTreeFilerPageHeader sph = (BTreeFilerPageHeader) startPage.getPageHeader(); - - HashMap meta = new HashMap(4); - - meta.put(Record.CREATED, sph.getCreated()); - meta.put(Record.MODIFIED, sph.getModified()); - meta.put(Record.LIFETIME, sph.getLifetime()); - meta.put(Record.EXPIRATION, sph.getExpiration()); - - return new Record(null, v, meta); - } catch (IOException e) { - throw new FilerException(DBE_CANNOT_READ, "Can't read record : " + e.getMessage(), e); - } - } - - public long writeRecord(Key key, Value value) throws DBException { - - return writeRecord(key, value, 0, 0); - } - - public long writeRecord(Key key, Value value, long lifetime, long expiration) throws DBException { - - if (key == null || key.getLength() == 0) { - throw new FilerException(FaultCodes.DBE_CANNOT_CREATE, "Invalid key: '" + key + "'"); - } - if (value == null) { - throw new FilerException(FaultCodes.DBE_CANNOT_CREATE, "Invalid null value"); - } - checkOpened(); - try { - Page p; - long pos; - try { - pos = findValue(key); - p = getPage(pos); - } catch (BTreeNotFoundException b) { - p = getFreePage(); - pos = p.getPageNum(); - addValue(key, p.getPageNum()); - fileHeader.incRecordCount(); - } - BTreeFilerPageHeader ph = (BTreeFilerPageHeader) p.getPageHeader(); - - long t = System.currentTimeMillis(); - - if (ph.getStatus() == UNUSED) { - ph.setCreated(t); - } - - ph.setModified(t); - ph.setLifetime(lifetime); - ph.setExpiration(expiration); - ph.setStatus(RECORD); - - writeValue(p, value); - flush(); - return pos; - } catch (IOException e) { - throw new FilerException(FaultCodes.DBE_CANNOT_CREATE, "Can't write record '" + key + "': " + e.getMessage(), e); - } - } - - public long writeRecord(long pos, Value value) throws DBException { - - if (value == null) { - throw new FilerException(FaultCodes.DBE_CANNOT_CREATE, "Invalid null value"); - } - checkOpened(); - try { - writeValue(pos, value); - flush(); - return pos; - } catch (IOException e) { - throw new FilerException(FaultCodes.DBE_CANNOT_CREATE, "Can't write record '" + value + "': " + e.getMessage(), e); - } - } - - public boolean deleteRecord(Key key) throws DBException { - if (key == null || key.getLength() == 0) { - return false; - } - checkOpened(); - try { - long pos = findValue(key); - Page p = getPage(pos); - - removeValue(key); - unlinkPages(p.getPageNum()); - - fileHeader.decRecordCount(); - - flush(); - - return true; - } catch (BTreeNotFoundException b) {// not found move on - } catch (IOException e) { - throw new FilerException(FaultCodes.DBE_CANNOT_DROP, "Can't delete record '" + key + "': " + e.getMessage(), e); - } - return false; - } - - public long getRecordCount() throws DBException { - checkOpened(); - return fileHeader.getRecordCount(); - } - - public RecordSet getRecordSet() throws DBException { - checkOpened(); - return new BTreeFilerRecordSet(); - } - - /** - * BTreeFilerRecordSet - */ - - private class BTreeFilerRecordSet implements RecordSet, BTreeCallback { - private List keys = new ArrayList(); - private Iterator it; - - public BTreeFilerRecordSet() throws DBException { - try { - query(null, this); - it = keys.iterator(); - } catch (IOException e) { - throw new FilerException(FaultCodes.GEN_CRITICAL_ERROR, "Error generating RecordSet", e); - } - } - - public synchronized boolean indexInfo(Value value, long pointer) { - keys.add(new Key(value)); - return true; - } - - public synchronized Key getNextKey() { - return it.next(); - } - - public synchronized Record getNextRecord() throws DBException { - return readRecord(it.next()); - } - - public synchronized Value getNextValue() throws DBException { - return getNextRecord().getValue(); - } - - public synchronized boolean hasMoreRecords() { - return it.hasNext(); - } - } - - // ////////////////////////////////////////////////////////////////// - - @Override - public FileHeader createFileHeader() { - return new BTreeFilerHeader(); - } - - @Override - public FileHeader createFileHeader(boolean read) throws IOException { - return new BTreeFilerHeader(read); - } - - @Override - public FileHeader createFileHeader(long pageCount) { - return new BTreeFilerHeader(pageCount); - } - - @Override - public FileHeader createFileHeader(long pageCount, int pageSize) { - return new BTreeFilerHeader(pageCount, pageSize); - } - - @Override - public PageHeader createPageHeader() { - return new BTreeFilerPageHeader(); - } - - /** - * BTreeFilerHeader - */ - - private final class BTreeFilerHeader extends BTreeFileHeader { - private long totalBytes = 0; - - public BTreeFilerHeader() {} - - public BTreeFilerHeader(long pageCount) { - super(pageCount); - } - - public BTreeFilerHeader(long pageCount, int pageSize) { - super(pageCount, pageSize); - } - - public BTreeFilerHeader(boolean read) throws IOException { - super(read); - } - - @Override - public synchronized void read(RandomAccessFile raf) throws IOException { - super.read(raf); - totalBytes = raf.readLong(); - } - - @Override - public synchronized void write(RandomAccessFile raf) throws IOException { - super.write(raf); - raf.writeLong(totalBytes); - } - - /** - * The total number of bytes in use by the file - * @param totalBytes the new total number of bytes - */ - public synchronized void setTotalBytes(long totalBytes) { - this.totalBytes = totalBytes; - setDirty(); - } - - /** - * The total number of bytes in use by the file - * @return the total number of bytes - */ - public synchronized long getTotalBytes() { - return totalBytes; - } - } - - - /** - * BTreeFilerPageHeader - */ - - private final class BTreeFilerPageHeader extends BTreePageHeader { - private long created = 0; - private long modified = 0; - private long lifetime = 0; - private long expiration = 0; - - public BTreeFilerPageHeader() {} - - public BTreeFilerPageHeader(DataInputStream dis) throws IOException { - super(dis); - } - - @Override - public synchronized void read(DataInputStream dis) throws IOException { - super.read(dis); - - if (getStatus() == UNUSED) { - return; - } - - created = dis.readLong(); - modified = dis.readLong(); - lifetime = dis.readLong(); - expiration = dis.readLong(); - } - - @Override - public synchronized void write(DataOutputStream dos) throws IOException { - super.write(dos); - dos.writeLong(created); - dos.writeLong(modified); - dos.writeLong(lifetime); - dos.writeLong(expiration); - } - - @Override - public synchronized void setRecordLen(int recordLen) { - fileHeader.setTotalBytes((fileHeader.totalBytes - getRecordLen()) + recordLen); - super.setRecordLen(recordLen); - } - - /** - * UNIX-time when this record was created - * @param created creation time - */ - public synchronized void setCreated(long created) { - this.created = created; - setDirty(); - } - - /** - * UNIX-time when this record was created - * @return creation time - */ - public synchronized long getCreated() { - return created; - } - - /** - * UNIX-time when this record was last modified - * @param modified modified time - */ - public synchronized void setModified(long modified) { - this.modified = modified; - setDirty(); - } - - /** - * UNIX-time when this record was last modified - * @return modified time - */ - public synchronized long getModified() { - return modified; - } - - /** - * JXTA-lifetime this record's lifetime - * @param lifetime the new record lifetime - */ - public synchronized void setLifetime(long lifetime) { - this.lifetime = lifetime; - setDirty(); - } - - /** - * JXTA-lifetime this record's lifetime - * @return the record lifetime - */ - public synchronized long getLifetime() { - return lifetime; - } - - /** - * JXTA-expiration this record's expiration - * @param expiration the record expiration time - */ - public synchronized void setExpiration(long expiration) { - this.expiration = expiration; - setDirty(); - } - - /** - * JXTA-expiration this record's expiration - * @return the record expiration time - */ - public synchronized long getExpiration() { - return expiration; - } - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeNotFoundException.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeNotFoundException.java deleted file mode 100644 index c4cb5200..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/BTreeNotFoundException.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.filer; - -import net.jxta.impl.xindice.core.FaultCodes; - -/** - * A BTreeNotFoundException is thrown by the BTree if a Value - * can't be found in the BTree. - */ -public final class BTreeNotFoundException extends BTreeException { - public BTreeNotFoundException() { - super(FaultCodes.IDX_VALUE_NOT_FOUND); - } - - public BTreeNotFoundException(String message) { - super(FaultCodes.IDX_VALUE_NOT_FOUND, message); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/Filer.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/Filer.java deleted file mode 100644 index f36fa2b4..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/Filer.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.filer; - -import net.jxta.impl.xindice.core.DBException; -import net.jxta.impl.xindice.core.DBObject; -import net.jxta.impl.xindice.core.data.Key; -import net.jxta.impl.xindice.core.data.Record; -import net.jxta.impl.xindice.core.data.RecordSet; -import net.jxta.impl.xindice.core.data.Value; -import net.jxta.impl.xindice.util.Named; - -/** - * Filer is the low-level file management interface for Xindice. A Filer object - * is implemented in order to provide a data source to the Xindice Collection - * class. Filers are developed to perform transparent storage and retrieval to - * and from heterogenous data sources (such as FTP, HTTP, RDBMS, etc...) - */ -public interface Filer extends Named, DBObject { - - /** - * readRecord returns a Record from the Filer based on the specified - * Key. - * - * @param key The Record's Key - * @return The returned Record - * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs - */ - Record readRecord(Key key) throws DBException; - - /** - * readRecord returns a Record from the Filer at the specified - * position. The Record's Key will be set to null. - * - * @param pos The Record's position - * @return The returned Record - * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs - */ - Record readRecord(long pos) throws DBException; - - /** - * writeRecord writes a Value to the Filer based on the specified Key. - * - * @param key The Record's Key - * @param value The Record's Value - * @return 0 if the Record could not be written, the starting - * offset of the Record otherwise (used for indexing) - * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs - */ - long writeRecord(Key key, Value value) throws DBException; - - /** - * deleteRecord removes a Record from the Filer based on the - * specified Key. - * - * @param key The Record's Key - * @return Whether or not the Record was deleted - * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs - */ - boolean deleteRecord(Key key) throws DBException; - - /** - * getRecordCount returns the number of Records in the Filer. - * - * @return The Record count - * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs - */ - long getRecordCount() throws DBException; - - /** - * getRecordSet returns a RecordSet object for the current Filer. - * - * @return The Filer Enumerator - * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs - */ - RecordSet getRecordSet() throws DBException; - - /** - * flush forcefully flushes any unwritten buffers to disk. - * @throws net.jxta.impl.xindice.core.DBException if a db exception occurs - */ - void flush() throws DBException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/FilerException.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/FilerException.java deleted file mode 100644 index 5b7b0e95..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/FilerException.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.filer; - -import net.jxta.impl.xindice.core.DBException; - -/** - * A FilerException is thrown by a Filer if an exception occurs - * in the managing of the Filer. - */ -public class FilerException extends DBException { - public FilerException(int faultCode) { - super(faultCode); - } - - public FilerException(int faultCode, String message) { - super(faultCode, message); - } - - public FilerException(int faultCode, String message, Throwable cause) { - super(faultCode, message, cause); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/MemFiler.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/MemFiler.java deleted file mode 100644 index 0f4c887e..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/MemFiler.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.filer; - -import net.jxta.impl.xindice.core.DBException; -import net.jxta.impl.xindice.core.FaultCodes; -import net.jxta.impl.xindice.core.data.Key; -import net.jxta.impl.xindice.core.data.Value; -import net.jxta.impl.xindice.core.data.Record; -import net.jxta.impl.xindice.core.data.RecordSet; - -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -/** - * MemFiler is an In-Memory Filer implementation for Xindice. MemFiler can be - * used for temporary collections and caching. It's basically a layering on - * top of HashMap. - */ -public final class MemFiler implements Filer { - private Map hashTable = null; - private Map posTable = null; - private boolean opened = false; - private boolean readOnly = false; - private long position = 0; - public MemFiler() { - hashTable = Collections.synchronizedMap(new HashMap()); - posTable = Collections.synchronizedMap(new HashMap()); - } - - public MemFiler(Map hashTable, boolean readOnly) { - this.hashTable = hashTable; - this.readOnly = readOnly; - } - - public MemFiler(Map hashTable) { - this(hashTable, false); - } - - public void setLocation(File root, String location) {} - - public String getName() { - return "MemFiler"; - } - - private void checkOpened() throws DBException { - if (!opened) { - throw new FilerException(FaultCodes.COL_COLLECTION_CLOSED, "Filer is closed"); - } - } - - private void checkReadOnly() throws DBException { - if (readOnly) { - throw new FilerException(FaultCodes.COL_COLLECTION_READ_ONLY, "Filer is read-only"); - } - } - - public boolean create() { - hashTable.clear(); - return true; - } - - public boolean open() { - opened = true; - return opened; - } - - public boolean isOpened() { - return opened; - } - - public boolean exists() { - return true; - } - - public boolean drop() { - hashTable.clear(); - opened = false; - return !opened; - } - - public boolean close() { - opened = false; - return !opened; - } - - public void flush() {} - - public Record readRecord(Key key) throws DBException { - if (key == null || key.getLength() == 0) { - return null; - } - checkOpened(); - return hashTable.get(key); - } - - public Record readRecord(long pos) throws DBException { - if (pos < 0) { - return null; - } - checkOpened(); - Key key = posTable.get(pos); - - return hashTable.get(key); - } - - public long writeRecord(Key key, Value value) throws DBException { - if (key == null || key.getLength() == 0) { - throw new FilerException(FaultCodes.DBE_CANNOT_CREATE, "Invalid key: '" + key + "'"); - } - if (value == null) { - throw new FilerException(FaultCodes.DBE_CANNOT_CREATE, "Invalid null value"); - } - checkOpened(); - checkReadOnly(); - hashTable.put(key, new Record(key, value)); - posTable.put(position, key); - long result = position; - - position++; - return result; - } - - public boolean deleteRecord(Key key) throws DBException { - if (key == null || key.getLength() == 0) { - return false; - } - checkOpened(); - checkReadOnly(); - return hashTable.remove(key) != null; - } - - public long getRecordCount() throws DBException { - checkOpened(); - return hashTable.size(); - } - - public RecordSet getRecordSet() throws DBException { - checkOpened(); - return new MemRecordSet(); - } - - /** - * MemRecordSet - */ - - private class MemRecordSet implements RecordSet { - private Iterator it = hashTable.values().iterator(); - - public synchronized boolean hasMoreRecords() throws DBException { - return it.hasNext(); - } - - public synchronized Record getNextRecord() throws DBException { - checkOpened(); - return it.next(); - } - - public synchronized Value getNextValue() throws DBException { - checkOpened(); - return (it.next()).getValue(); - } - - public synchronized Key getNextKey() { - return (it.next()).getKey(); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/Paged.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/Paged.java deleted file mode 100644 index bd3c4839..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/Paged.java +++ /dev/null @@ -1,1501 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.filer; - -import net.jxta.impl.xindice.core.DBException; -import net.jxta.impl.xindice.core.FaultCodes; -import net.jxta.impl.xindice.core.data.Key; -import net.jxta.impl.xindice.core.data.Value; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.RandomAccessFile; -import java.lang.ref.WeakReference; -import java.util.Collection; -import java.util.EmptyStackException; -import java.util.HashMap; -import java.util.Map; -import java.util.Stack; -import java.util.WeakHashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Paged is a paged file implementation that is foundation for both the - * BTree class and the HashFiler. It provides flexible paged I/O and - * page caching functionality. - *

            - * Page has folowing configuration attributes: - *

              - *
            • pagesize: Size of the page used by the paged file. - * Default page size is 4096 bytes. This parameter can be set only - * before paged file is created. Once it is created, this parameter - * can not be changed.
            • - *
            • maxkeysize: Maximum allowed size of the key. - * Default maximum key size is 256 bytes.
            • - *
            • max-descriptors: Defines maximum amount of - * simultaneously opened file descriptors this paged file can have. - * Several descriptors are needed to provide multithreaded access - * to the underlying file. Too large number will limit amount of - * collections you can open. Default value is 16 - * (DEFAULT_DESCRIPTORS_MAX).
            • - *
            - *

            - *
            FIXME: Currently it seems that maxkeysize is not used anywhere. - *
            TODO: Introduce Paged interface, implementations. - */ -public abstract class Paged { - - /** - * Logger - */ - private final static Logger LOG = Logger.getLogger(Paged.class.getName()); - - /** - * The maximum number of pages that will be held in the dirty cache. - * Once number reaches the limit, pages are flushed to disk. - */ - private static final int MAX_DIRTY_SIZE = 128; - - // The maximum number of open random access files we can have - private static final int DEFAULT_DESCRIPTORS_MAX = 16; - - /** - * Unused page status - */ - protected static final byte UNUSED = 0; - - /** - * Overflow page status - */ - protected static final byte OVERFLOW = 126; - - /** - * Deleted page status - */ - protected static final byte DELETED = 127; - - /** - * Page ID of non-existent page - */ - protected static final int NO_PAGE = -1; - - /** - * flag whether to sync DB on every write or not. - */ - protected boolean sync = true; - - // TODO: This is not a cache right now, but a way to assure that only one page instance at most exists in memory at all times. - /** - * Cache of recently read pages. - *

            - * Cache contains weak references to the Page objects, keys are page numbers (Long objects). - * Access synchronized by this map itself. - */ - private final Map> pages = new WeakHashMap>(); - - /** - * Cache of modified pages waiting to be written out. - * Access is synchronized by the {@link #dirtyLock}. - */ - private Map dirty = new HashMap(); - - /** - * Lock for synchronizing access to the {@link #dirty} map. - */ - private final Object dirtyLock = new Object(); - - /** - * Random access file descriptors cache. - * Access to it and to {@link #descriptorsCount} is synchronized by itself. - */ - private final Stack descriptors = new Stack(); - - /** - * The number of random access file objects that exist, either in the - * cache {@link #descriptors}, or currently in use. - */ - private int descriptorsCount; - - /** - * The maximum number of random access file objects that can be opened - * by this paged instance. - */ - private int descriptorsMax; - - /** - * Whether the file is opened or not. - */ - private boolean opened; - - /** - * The underlying file where the Paged object stores its pages. - */ - private File file; - - /** - * Header of this Paged - */ - private final FileHeader fileHeader; - - public Paged() { - descriptorsMax = DEFAULT_DESCRIPTORS_MAX; - fileHeader = createFileHeader(); - } - - public Paged(File file) { - this(); - setFile(file); - } - - /** - * setFile sets the file object for this Paged. - * - * @param file The File - */ - protected final void setFile(final File file) { - this.file = file; - } - - /** - * getFile returns the file object for this Paged. - * - * @return The File - */ - protected final File getFile() { - return file; - } - - /** - * Obtain RandomAccessFile ('descriptor') object out of the pool. - * If no descriptors available, and maximum amount already allocated, - * the call will block. - * @return the file - * @throws java.io.IOException if an io error occurs - */ - protected final RandomAccessFile getDescriptor() throws IOException { - synchronized (descriptors) { - // If there are descriptors in the cache return one. - if (!descriptors.empty()) { - return descriptors.pop(); - } - // Otherwise we need to get one some other way. - - // First try to create a new one if there's room - if (descriptorsCount < descriptorsMax) { - descriptorsCount++; - return new RandomAccessFile(file, "rw"); - } - - // Otherwise we have to wait for one to be released by another thread. - while (true) { - try { - descriptors.wait(); - return descriptors.pop(); - } catch (InterruptedException e) {// Ignore, and continue to wait - } catch (EmptyStackException e) {// Ignore, and continue to wait - } - } - } - } - - /** - * Puts a RandomAccessFile ('descriptor') back into the descriptor pool. - * @param raf the file to add - */ - protected final void putDescriptor(RandomAccessFile raf) { - if (raf != null) { - synchronized (descriptors) { - descriptors.push(raf); - descriptors.notify(); - } - } - } - - /** - * Closes a RandomAccessFile ('descriptor') and removes it from the pool. - * @param raf the file to close - */ - protected final void closeDescriptor(RandomAccessFile raf) { - if (raf != null) { - try { - raf.close(); - } catch (IOException e) {// Ignore close exception - } - - // Synchronization is necessary as decrement operation is not atomic - synchronized (descriptors) { - descriptorsCount--; - } - } - } - - /** - * getPage returns the page specified by pageNum. - * - * @param pageNum The Page number - * @return The requested Page - * @throws IOException if an Exception occurs - */ - protected final Page getPage(long pageNum) throws IOException { - final Long lp = pageNum; - Page page; - - synchronized (this) { - // Check if it's in the dirty cache - // No need to synchronize on dirtyLock thanks to atomic assignment - page = dirty.get(lp); - - // if not check if it's already loaded in the page cache - if (page == null) { - WeakReference ref = pages.get(lp); - - if (ref != null) { - page = ref.get(); - } - } - - // if still not found we need to create it and add it to the page cache. - if (page == null) { - page = new Page(lp); - pages.put(page.pageNum, new WeakReference(page)); - } - } - - // Load the page from disk if necessary - page.read(); - return page; - } - - /** - * readValue reads the multi-Paged Value starting at the specified - * Page. - * - * @param page The starting Page - * @return The Value - * @throws IOException if an Exception occurs - */ - protected final Value readValue(Page page) throws IOException { - final PageHeader sph = page.getPageHeader(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(sph.getRecordLen()); - - // Loop until we've read all the pages into memory. - Page p = page; - - while (true) { - PageHeader ph = p.getPageHeader(); - - // Add the contents of the page onto the stream - p.streamTo(bos); - - // Continue following the list of pages until we get to the end. - long nextPage = ph.getNextPage(); - - if (nextPage == NO_PAGE) { - break; - } - p = getPage(nextPage); - } - - // Return a Value with the collected contents of all pages. - return new Value(bos.toByteArray()); - } - - /** - * readValue reads the multi-Paged Value starting at the specified - * page number. - * - * @param page The starting page number - * @return The Value - * @throws IOException if an Exception occurs - */ - protected final Value readValue(long page) throws IOException { - return readValue(getPage(page)); - } - - /** - * writeValue writes the multi-Paged Value starting at the specified - * Page. - * - * @param page The starting Page - * @param value The Value to write - * @throws IOException if an Exception occurs - */ - protected final void writeValue(Page page, Value value) throws IOException { - if (value == null) { - throw new IOException("Can't write a null value"); - } - - InputStream is = value.getInputStream(); - - // Write as much as we can onto the primary page. - PageHeader hdr = page.getPageHeader(); - - hdr.setRecordLen(value.getLength()); - page.streamFrom(is); - - // Write out the rest of the value onto any needed overflow pages - while (is.available() > 0) { - Page lpage = page; - PageHeader lhdr = hdr; - - // Find an overflow page to use - long np = lhdr.getNextPage(); - - if (np != NO_PAGE) { - // Use an existing page. - page = getPage(np); - } else { - // Create a new overflow page - page = getFreePage(); - lhdr.setNextPage(page.getPageNum()); - } - - // Mark the page as an overflow page. - hdr = page.getPageHeader(); - hdr.setStatus(OVERFLOW); - - // Write some more of the value to the overflow page. - page.streamFrom(is); - lpage.write(); - } - - // Cleanup any unused overflow pages. i.e. the value is smaller then the - // last time it was written. - long np = hdr.getNextPage(); - - if (np != NO_PAGE) { - unlinkPages(np); - } - - hdr.setNextPage(NO_PAGE); - page.write(); - } - - /** - * writeValue writes the multi-Paged Value starting at the specified - * page number. - * - * @param page The starting page number - * @param value The Value to write - * @throws IOException if an Exception occurs - */ - protected final void writeValue(long page, Value value) throws IOException { - writeValue(getPage(page), value); - } - - /** - * unlinkPages unlinks a set of pages starting at the specified Page. - * - * @param page The starting Page to unlink - * @throws IOException if an Exception occurs - */ - protected final void unlinkPages(Page page) throws IOException { - // Handle the page if it's in primary space by setting its status to - // DELETED and freeing any overflow pages linked to it. - if (page.pageNum < fileHeader.pageCount) { - long nextPage = page.header.nextPage; - - page.header.setStatus(DELETED); - page.header.setNextPage(NO_PAGE); - page.write(); - - // See if there are any chained pages from the page that was just removed - if (nextPage == NO_PAGE) { - page = null; - } else { - page = getPage(nextPage); - } - } - - // Add any overflow pages to the list of free pages. - if (page != null) { - // Get the first and last page in the chain. - long firstPage = page.pageNum; - - while (page.header.nextPage != NO_PAGE) { - page = getPage(page.header.nextPage); - } - long lastPage = page.pageNum; - - // Free the chain - synchronized (fileHeader) { - // If there are already some free pages, add the start of the chain - // to the list of free pages. - if (fileHeader.lastFreePage != NO_PAGE) { - Page p = getPage(fileHeader.lastFreePage); - - p.header.setNextPage(firstPage); - p.write(); - } - - // Otherwise set the chain as the list of free pages. - if (fileHeader.firstFreePage == NO_PAGE) { - fileHeader.setFirstFreePage(firstPage); - } - - // Add a reference to the end of the chain. - fileHeader.setLastFreePage(lastPage); - } - } - } - - /** - * unlinkPages unlinks a set of pages starting at the specified - * page number. - * - * @param pageNum The starting page number to unlink - * @throws IOException if an Exception occurs - */ - protected final void unlinkPages(long pageNum) throws IOException { - unlinkPages(getPage(pageNum)); - } - - /** - * getFreePage returns the first free Page from secondary storage. - * If no Pages are available, the file is grown as appropriate. - * - * @return The next free Page - * @throws IOException if an Exception occurs - */ - protected final Page getFreePage() throws IOException { - Page p = null; - - // Synchronize read and write to the fileHeader.firstFreePage - synchronized (fileHeader) { - if (fileHeader.firstFreePage != NO_PAGE) { - // Steal a deleted page - p = getPage(fileHeader.firstFreePage); - fileHeader.setFirstFreePage(p.getPageHeader().nextPage); - if (fileHeader.firstFreePage == NO_PAGE) { - fileHeader.setLastFreePage(NO_PAGE); - } - } - } - - if (p == null) { - // No deleted pages, grow the file - p = getPage(fileHeader.incTotalCount()); - } - - // Initialize The Page Header (Cleanly) - p.header.setNextPage(NO_PAGE); - p.header.setStatus(UNUSED); - return p; - } - - /** - * @throws DBException COL_COLLECTION_CLOSED if paged file is closed - */ - protected final void checkOpened() throws DBException { - if (!opened) { - throw new FilerException(FaultCodes.COL_COLLECTION_CLOSED, "Filer is closed"); - } - } - - /** - * getFileHeader returns the FileHeader - * - * @return The FileHeader - */ - public FileHeader getFileHeader() { - return fileHeader; - } - - public boolean exists() { - return file.exists(); - } - - public boolean create() throws DBException { - try { - createFile(); - fileHeader.write(); - flush(); - return true; - } catch (Exception e) { - throw new FilerException(FaultCodes.GEN_CRITICAL_ERROR, "Error creating " + file.getName(), e); - } - } - - private void createFile() throws IOException { - RandomAccessFile raf = null; - - try { - raf = getDescriptor(); - long o = fileHeader.headerSize + (fileHeader.pageCount + 1) * fileHeader.pageSize - 1; - - raf.seek(o); - raf.write(0); - } finally { - putDescriptor(raf); - } - } - - public boolean open() throws DBException { - RandomAccessFile raf = null; - - try { - if (exists()) { - raf = getDescriptor(); - fileHeader.read(); - opened = true; - } else { - opened = false; - } - return opened; - } catch (Exception e) { - throw new FilerException(FaultCodes.GEN_CRITICAL_ERROR, "Error opening " + file.getName(), e); - } finally { - putDescriptor(raf); - } - } - - public synchronized boolean close() throws DBException { - if (isOpened()) { - try { - // First of all, mark as closed to prevent operations - opened = false; - flush(); - - synchronized (descriptors) { - final int total = descriptorsCount; - - // Close descriptors in cache - while (!descriptors.empty()) { - closeDescriptor(descriptors.pop()); - } - // Attempt to close descriptors in use. Max wait time = 0.5s * MAX_DESCRIPTORS - int n = descriptorsCount; - - while (descriptorsCount > 0 && n > 0) { - try { - descriptors.wait(500); - } catch (InterruptedException woken) { - Thread.interrupted(); - } - - if (descriptors.isEmpty()) { - n--; - } else { - closeDescriptor(descriptors.pop()); - } - } - if (descriptorsCount > 0) { - LOG.fine(descriptorsCount + " out of " + total + " files were not closed during close."); - } - } - } catch (Exception e) { - // Failed to close, leave open - opened = true; - throw new FilerException(FaultCodes.GEN_CRITICAL_ERROR, "Error closing " + file.getName(), e); - } - } - return true; - } - - public boolean isOpened() { - return opened; - } - - public boolean drop() throws DBException { - try { - close(); - return !exists() || getFile().delete(); - } catch (Exception e) { - throw new FilerException(FaultCodes.COL_CANNOT_DROP, "Can't drop " + file.getName(), e); - } - } - - void addDirty(Page page) throws IOException { - synchronized (dirtyLock) { - dirty.put(page.pageNum, page); - if (dirty.size() > MAX_DIRTY_SIZE) { - try { - // Too many dirty pages... flush them - flush(); - } catch (Exception e) { - throw new IOException(e.getMessage()); - } - } - } - } - - public void flush() throws DBException { - // This method is not synchronized - - // Error flag/counter - int error = 0; - - // Obtain collection of dirty pages - Collection pages; - - synchronized (dirtyLock) { - pages = dirty.values(); - dirty = new HashMap(); - } - - // Flush dirty pages - for (Object page : pages) { - Page p = (Page) page; - - try { - p.flush(); - } catch (Exception e) { - LOG.log(Level.WARNING, "Exception while flushing page", e); - error++; - } - } - - // Flush header - if (fileHeader.dirty) { - try { - fileHeader.write(); - } catch (Exception e) { - LOG.log(Level.WARNING, "Exception while flushing file header", e); - error++; - } - } - - if (error != 0) { - throw new FilerException(FaultCodes.GEN_CRITICAL_ERROR, "Error performing flush! Failed to flush " + error + " pages!"); - } - } - - /** - * createFileHeader must be implemented by a Paged implementation - * in order to create an appropriate subclass instance of a FileHeader. - * - * @return a new FileHeader - */ - public abstract FileHeader createFileHeader(); - - /** - * createFileHeader must be implemented by a Paged implementation - * in order to create an appropriate subclass instance of a FileHeader. - * - * @param read If true, reads the FileHeader from disk - * @return a new FileHeader - * @throws IOException if an exception occurs - */ - public abstract FileHeader createFileHeader(boolean read) throws IOException; - - /** - * createFileHeader must be implemented by a Paged implementation - * in order to create an appropriate subclass instance of a FileHeader. - * - * @param pageCount The number of pages to allocate for primary storage - * @return a new FileHeader - */ - public abstract FileHeader createFileHeader(long pageCount); - - /** - * createFileHeader must be implemented by a Paged implementation - * in order to create an appropriate subclass instance of a FileHeader. - * - * @param pageCount The number of pages to allocate for primary storage - * @param pageSize The size of a Page (should be a multiple of a FS block) - * @return a new FileHeader - */ - public abstract FileHeader createFileHeader(long pageCount, int pageSize); - - /** - * createPageHeader must be implemented by a Paged implementation - * in order to create an appropriate subclass instance of a PageHeader. - * - * @return a new PageHeader - */ - public abstract PageHeader createPageHeader(); - - // These are a bunch of utility methods for subclasses - - public static Value[] insertArrayValue(Value[] vals, Value val, int idx) { - Value[] newVals = new Value[vals.length + 1]; - - if (idx > 0) { - System.arraycopy(vals, 0, newVals, 0, idx); - } - newVals[idx] = val; - if (idx < vals.length) { - System.arraycopy(vals, idx, newVals, idx + 1, vals.length - idx); - } - return newVals; - } - - public static Value[] deleteArrayValue(Value[] vals, int idx) { - Value[] newVals = new Value[vals.length - 1]; - - if (idx > 0) { - System.arraycopy(vals, 0, newVals, 0, idx); - } - if (idx < newVals.length) { - System.arraycopy(vals, idx + 1, newVals, idx, newVals.length - idx); - } - return newVals; - } - - public static long[] insertArrayLong(long[] vals, long val, int idx) { - long[] newVals = new long[vals.length + 1]; - - if (idx > 0) { - System.arraycopy(vals, 0, newVals, 0, idx); - } - newVals[idx] = val; - if (idx < vals.length) { - System.arraycopy(vals, idx, newVals, idx + 1, vals.length - idx); - } - return newVals; - } - - public static long[] deleteArrayLong(long[] vals, int idx) { - long[] newVals = new long[vals.length - 1]; - - if (idx > 0) { - System.arraycopy(vals, 0, newVals, 0, idx); - } - if (idx < newVals.length) { - System.arraycopy(vals, idx + 1, newVals, idx, newVals.length - idx); - } - return newVals; - } - - public static int[] insertArrayInt(int[] vals, int val, int idx) { - int[] newVals = new int[vals.length + 1]; - - if (idx > 0) { - System.arraycopy(vals, 0, newVals, 0, idx); - } - newVals[idx] = val; - if (idx < vals.length) { - System.arraycopy(vals, idx, newVals, idx + 1, vals.length - idx); - } - return newVals; - } - - public static int[] deleteArrayInt(int[] vals, int idx) { - int[] newVals = new int[vals.length - 1]; - - if (idx > 0) { - System.arraycopy(vals, 0, newVals, 0, idx); - } - if (idx < newVals.length) { - System.arraycopy(vals, idx + 1, newVals, idx, newVals.length - idx); - } - return newVals; - } - - public static short[] insertArrayShort(short[] vals, short val, int idx) { - short[] newVals = new short[vals.length + 1]; - - if (idx > 0) { - System.arraycopy(vals, 0, newVals, 0, idx); - } - newVals[idx] = val; - if (idx < vals.length) { - System.arraycopy(vals, idx, newVals, idx + 1, vals.length - idx); - } - - return newVals; - } - - public static short[] deleteArrayShort(short[] vals, int idx) { - short[] newVals = new short[vals.length - 1]; - - if (idx > 0) { - System.arraycopy(vals, 0, newVals, 0, idx); - } - if (idx < newVals.length) { - System.arraycopy(vals, idx + 1, newVals, idx, newVals.length - idx); - } - - return newVals; - } - - /** - * Paged file's header - */ - public abstract class FileHeader { - private boolean dirty = false; - private int workSize; - - private short headerSize; - private int pageSize; - private long pageCount; - private long totalCount; - private long firstFreePage = -1; - private long lastFreePage = -1; - private byte pageHeaderSize = 64; - private short maxKeySize = 256; - private long recordCount; - - public FileHeader() { - this(1024); - } - - public FileHeader(long pageCount) { - this(pageCount, 4096); - } - - public FileHeader(long pageCount, int pageSize) { - this.pageSize = pageSize; - this.pageCount = pageCount; - totalCount = pageCount; - headerSize = (short) 4096; - calculateWorkSize(); - } - - public FileHeader(boolean read) throws IOException { - if (read) { - read(); - } - } - - public synchronized final void read() throws IOException { - RandomAccessFile raf = null; - - try { - raf = getDescriptor(); - raf.seek(0); - read(raf); - calculateWorkSize(); - } finally { - putDescriptor(raf); - } - } - - public synchronized void read(RandomAccessFile raf) throws IOException { - headerSize = raf.readShort(); - pageSize = raf.readInt(); - pageCount = raf.readLong(); - totalCount = raf.readLong(); - firstFreePage = raf.readLong(); - lastFreePage = raf.readLong(); - pageHeaderSize = raf.readByte(); - maxKeySize = raf.readShort(); - recordCount = raf.readLong(); - } - - public synchronized final void write() throws IOException { - if (!dirty) { - return; - } - - RandomAccessFile raf = null; - - try { - raf = getDescriptor(); - raf.seek(0); - write(raf); - dirty = false; - } finally { - putDescriptor(raf); - } - } - - public synchronized void write(RandomAccessFile raf) throws IOException { - raf.writeShort(headerSize); - raf.writeInt(pageSize); - raf.writeLong(pageCount); - raf.writeLong(totalCount); - raf.writeLong(firstFreePage); - raf.writeLong(lastFreePage); - raf.writeByte(pageHeaderSize); - raf.writeShort(maxKeySize); - raf.writeLong(recordCount); - } - - public synchronized final void setDirty() { - dirty = true; - } - - public synchronized final boolean isDirty() { - return dirty; - } - - /** - * The size of the FileHeader. Usually 1 OS Page. - * This method should be called only while initializing Paged, not during normal processing. - * @param headerSize the new header size - */ - public synchronized final void setHeaderSize(short headerSize) { - this.headerSize = headerSize; - dirty = true; - } - - /** - * The size of the FileHeader. Usually 1 OS Page - * @return the header size - */ - public synchronized final short getHeaderSize() { - return headerSize; - } - - /** - * The size of a page. Usually a multiple of a FS block. - * This method should be called only while initializing Paged, not during normal processing. - * @param pageSize the new page size - */ - public synchronized final void setPageSize(int pageSize) { - this.pageSize = pageSize; - calculateWorkSize(); - dirty = true; - } - - /** - * The size of a page. Usually a multiple of a FS block - * @return the page size - */ - public synchronized final int getPageSize() { - return pageSize; - } - - /** - * The number of pages in primary storage. - * This method should be called only while initializing Paged, not during normal processing. - * @param pageCount the new page count - */ - public synchronized final void setPageCount(long pageCount) { - this.pageCount = pageCount; - dirty = true; - } - - /** - * The number of pages in primary storage - * @return the page count - */ - public synchronized final long getPageCount() { - return pageCount; - } - - /** - * The number of total pages in the file. - * This method should be called only while initializing Paged, not during normal processing. - * @param totalCount the new total count - */ - public synchronized final void setTotalCount(long totalCount) { - this.totalCount = totalCount; - dirty = true; - } - - public synchronized final long incTotalCount() { - dirty = true; - return this.totalCount++; - } - - /** - * The number of total pages in the file - * @return the total count - */ - public synchronized final long getTotalCount() { - return totalCount; - } - - /** - * The first free page in unused secondary space - * @param firstFreePage the new first free page - */ - public synchronized final void setFirstFreePage(long firstFreePage) { - this.firstFreePage = firstFreePage; - dirty = true; - } - - /** - * The first free page in unused secondary space - * @return the first free page - */ - public synchronized final long getFirstFreePage() { - return firstFreePage; - } - - /** - * The last free page in unused secondary space - * @param lastFreePage sets the last free page - */ - public synchronized final void setLastFreePage(long lastFreePage) { - this.lastFreePage = lastFreePage; - dirty = true; - } - - /** - * The last free page in unused secondary space - * @return the last free page - */ - public synchronized final long getLastFreePage() { - return lastFreePage; - } - - /** - * Set the size of a page header. - *

            - * Normally, 64 is sufficient. - * @param pageHeaderSize the new page header size - */ - public synchronized final void setPageHeaderSize(byte pageHeaderSize) { - this.pageHeaderSize = pageHeaderSize; - calculateWorkSize(); - dirty = true; - } - - /** - * Get the size of a page header. - *

            - * Normally, 64 is sufficient - * @return the page header size - */ - public synchronized final byte getPageHeaderSize() { - return pageHeaderSize; - } - - /** - * Set the maximum number of bytes a key can be. - *

            - * Normally, 256 is good - * @param maxKeySize the new max key size - */ - public synchronized final void setMaxKeySize(short maxKeySize) { - this.maxKeySize = maxKeySize; - dirty = true; - } - - /** - * Get the maximum number of bytes. - *

            - * Normally, 256 is good. - * @return max key size - */ - public synchronized final short getMaxKeySize() { - return maxKeySize; - } - - /** - * Increment the number of records being managed by the file - */ - public synchronized final void incRecordCount() { - recordCount++; - dirty = true; - } - - /** - * Decrement the number of records being managed by the file - */ - public synchronized final void decRecordCount() { - recordCount--; - dirty = true; - } - - /** - * The number of records being managed by the file (not pages) - * @return the record count - */ - public synchronized final long getRecordCount() { - return recordCount; - } - - private synchronized void calculateWorkSize() { - workSize = pageSize - pageHeaderSize; - } - - public synchronized final int getWorkSize() { - return workSize; - } - } - - - /** - * PageHeader - */ - - public abstract class PageHeader implements Streamable { - private boolean dirty = false; - private byte status = UNUSED; - private int keyLen = 0; - private int keyHash = 0; - private int dataLen = 0; - private int recordLen = 0; - private long nextPage = -1; - - public PageHeader() {} - - public PageHeader(DataInputStream dis) throws IOException { - read(dis); - } - - public synchronized void read(DataInputStream dis) throws IOException { - status = dis.readByte(); - dirty = false; - if (status == UNUSED) { - return; - } - - keyLen = dis.readInt(); - if (keyLen < 0) { - // hack for win98/ME - see issue 564 - keyLen = 0; - } - keyHash = dis.readInt(); - dataLen = dis.readInt(); - recordLen = dis.readInt(); - nextPage = dis.readLong(); - } - - public synchronized void write(DataOutputStream dos) throws IOException { - dirty = false; - dos.writeByte(status); - dos.writeInt(keyLen); - dos.writeInt(keyHash); - dos.writeInt(dataLen); - dos.writeInt(recordLen); - dos.writeLong(nextPage); - } - - public synchronized final boolean isDirty() { - return dirty; - } - - public synchronized final void setDirty() { - dirty = true; - } - - /** - * The status of this page (UNUSED, RECORD, DELETED, etc...) - * @param status the new status - */ - public synchronized final void setStatus(byte status) { - this.status = status; - dirty = true; - } - - /** - * The status of this page (UNUSED, RECORD, DELETED, etc...) - * @return the status - */ - public synchronized final byte getStatus() { - return status; - } - - public synchronized final void setKey(Key key) { - // setKey WIPES OUT the Page data - setRecordLen(0); - dataLen = 0; - keyHash = key.getHash(); - keyLen = key.getLength(); - dirty = true; - } - - /** - * The length of the Key - * @param keyLen the new key length - */ - public synchronized final void setKeyLen(int keyLen) { - this.keyLen = keyLen; - dirty = true; - } - - /** - * The length of the Key - * @return the key length - */ - public synchronized final int getKeyLen() { - return keyLen; - } - - /** - * The hashed value of the Key for quick comparisons - * @param keyHash sets the key hash - */ - public synchronized final void setKeyHash(int keyHash) { - this.keyHash = keyHash; - dirty = true; - } - - /** - * The hashed value of the Key for quick comparisons - * @return the key hash - */ - public synchronized final int getKeyHash() { - return keyHash; - } - - /** - * The length of the Data - * @param dataLen sets the data length - */ - public synchronized final void setDataLen(int dataLen) { - this.dataLen = dataLen; - dirty = true; - } - - /** - * The length of the Data - * @return the data length - */ - public synchronized final int getDataLen() { - return dataLen; - } - - /** - * The length of the Record's value - * @param recordLen sets the record length - */ - public synchronized void setRecordLen(int recordLen) { - this.recordLen = recordLen; - dirty = true; - } - - /** - * The length of the Record's value - * @return record length - */ - public synchronized final int getRecordLen() { - return recordLen; - } - - /** - * The next page for this Record (if overflowed) - * @param nextPage next page - */ - public synchronized final void setNextPage(long nextPage) { - this.nextPage = nextPage; - dirty = true; - } - - /** - * The next page for this Record (if overflowed) - * @return next page - */ - public synchronized final long getNextPage() { - return nextPage; - } - } - - - /** - * Paged file's page - */ - public final class Page implements Comparable { - - /** - * This page number - */ - private final Long pageNum; - - /** - * The Header for this Page - */ - private final PageHeader header; - - /** - * The offset into the file that this page starts - */ - private final long offset; - - /** - * The data for this page. Null if page is not loaded. - */ - private byte[] data; - - /** - * The position (relative) of the Key in the data array - */ - private int keyPos; - - /** - * The position (relative) of the Data in the data array - */ - private int dataPos; - - public Page(Long pageNum) { - this.header = createPageHeader(); - this.pageNum = pageNum; - this.offset = fileHeader.headerSize + (pageNum * fileHeader.pageSize); - } - - /** - * Reads a page into the memory, once. Subsequent calls are ignored. - * @throws java.io.IOException if an io error occurs - */ - public synchronized void read() throws IOException { - if (data == null) { - RandomAccessFile raf = null; - - try { - byte[] data = new byte[fileHeader.pageSize]; - - raf = getDescriptor(); - raf.seek(this.offset); - raf.read(data); - - // Read in the header - ByteArrayInputStream bis = new ByteArrayInputStream(data); - - this.header.read(new DataInputStream(bis)); - - this.keyPos = fileHeader.pageHeaderSize; - this.dataPos = this.keyPos + this.header.keyLen; - - // Successfully read all the data - this.data = data; - } finally { - putDescriptor(raf); - } - } - } - - /** - * Writes out the header into the this.data, and adds a page to the set of - * dirty pages. - * @throws java.io.IOException if an io error occurs - */ - public void write() throws IOException { - // Write out the header into the this.data - synchronized (this) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(fileHeader.getPageHeaderSize()); - - header.write(new DataOutputStream(bos)); - byte[] b = bos.toByteArray(); - - System.arraycopy(b, 0, data, 0, b.length); - } - - // Add to the list of dirty pages - Paged.this.addDirty(this); - } - - /** - * Flushes content of the dirty page into the file - * @throws java.io.IOException if an io error occurs - */ - public synchronized void flush() throws IOException { - RandomAccessFile raf = null; - - try { - raf = getDescriptor(); - if (this.offset >= raf.length()) { - // Grow the file - long o = (fileHeader.headerSize + ((fileHeader.totalCount * 3) / 2) * fileHeader.pageSize) - + (fileHeader.pageSize - 1); - - raf.seek(o); - raf.writeByte(0); - } - raf.seek(this.offset); - raf.write(this.data); - if (sync) { - raf.getFD().sync(); - } - } finally { - putDescriptor(raf); - } - } - - // No synchronization - pageNum is final - public Long getPageNum() { - return this.pageNum; - } - - // No synchronization - header is final - public PageHeader getPageHeader() { - return this.header; - } - - public synchronized void setKey(Key key) { - header.setKey(key); - // Insert the key into the data array. - key.copyTo(this.data, this.keyPos); - - // Set the start of data to skip over the key. - this.dataPos = this.keyPos + header.keyLen; - } - - public synchronized Key getKey() { - if (header.keyLen > 0) { - return new Key(this.data, this.keyPos, header.keyLen); - } else { - return null; - } - } - - public synchronized void streamTo(OutputStream os) throws IOException { - if (header.dataLen > 0) { - os.write(this.data, this.dataPos, header.dataLen); - } - } - - public synchronized void streamFrom(InputStream is) throws IOException { - int avail = is.available(); - - header.dataLen = fileHeader.workSize - header.keyLen; - if (avail < header.dataLen) { - header.dataLen = avail; - } - if (header.dataLen > 0) { - is.read(this.data, this.keyPos + header.keyLen, header.dataLen); - } - } - - // No synchronization: pageNum is final. - public int compareTo(Page o) { - return (int) (this.pageNum - o.pageNum); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/Streamable.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/Streamable.java deleted file mode 100644 index 6541bb1f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/filer/Streamable.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package net.jxta.impl.xindice.core.filer; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; - -/** - * Streamable is an interface implemented by objects used by Filers and - * Indexers in order to serialize objects to and from IO streams. - */ -public interface Streamable { - - /** - * read reads the object state from the stream. - * - * @param is The DataInputStream - * @throws IOException if an IOException occurs - */ - public void read(DataInputStream is) throws IOException; - - /** - * write writes the object state to the stream. - * - * @param os The DataOutputStream - * @throws IOException if an IOException occurs - */ - public void write(DataOutputStream os) throws IOException; -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/indexer/IndexQuery.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/indexer/IndexQuery.java deleted file mode 100644 index 059a9456..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/indexer/IndexQuery.java +++ /dev/null @@ -1,275 +0,0 @@ -package net.jxta.impl.xindice.core.indexer; - - -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - - */ - -import net.jxta.impl.xindice.core.data.*; -import java.util.*; - - -/** - * IndexQuery represents the most primitive form of index querying. - * Instances of this object should be created by QueryResolvers and - * cached in Query instances. - */ - -public class IndexQuery { - // No Operator - public static final int ANY = 0; // Any And All Matches - - // Singleton Operators - public static final int EQ = 1; // Equal To - public static final int NEQ = -1; // Not Equal To - public static final int GT = 2; // Greater Than - public static final int LEQ = -2; // Less Than Or Equal To - public static final int LT = 3; // Less Than - public static final int GEQ = -3; // Greater Than Or Equal To - - // Range Operators - public static final int BW = 4; // Between (Inclusive) - public static final int NBW = -4; // Not Between (Inclusive) - public static final int BWX = 5; // Between (Exclusive) - public static final int NBWX = -5; // Not Between (Exclusive) - - // Set Operators - public static final int IN = 6; // In The Set - public static final int NIN = -6; // Not In The Set - - // Other operators - public static final int SW = 7; // Starts-with - public static final int NSW = -7; // Not Starts-with - - public static final int EW = 8; // Ends-with - public static final int NEW = -8; // Not Ends-with - - protected int op; - protected Value[] vals; - - public IndexQuery() { - op = ANY; - } - - public IndexQuery(int op, Value[] vals) { - this.op = op; - this.vals = vals; - } - - public IndexQuery(Value[] vals) { - this(IN, vals); - } - - public IndexQuery(int op, Value val1) { - this.op = op; - if (op == SW || op == NSW) { - byte[] b = new byte[val1.getLength() + 1]; - - System.arraycopy(val1.getData(), 0, b, 0, b.length - 1); - b[b.length - 1] = 127; // TODO: Must fix this - Value val2 = new Value(b); - - vals = new Value[] { val1, val2 }; - } else { - vals = new Value[] { val1 }; - } - } - - public IndexQuery(Value val1) { - this(EQ, val1); - } - - public IndexQuery(int op, Value val1, Value val2) { - this.op = op; - vals = new Value[] { val1, val2 }; - } - - public IndexQuery(Value val1, Value val2) { - this(IN, val1, val2); - } - - public IndexQuery(int op, String val1) { - this(op, new Value(val1)); - } - - public IndexQuery(String val1) { - this(new Value(val1)); - } - - public IndexQuery(int op, String val1, String val2) { - this(op, new Value(val1), new Value(val2)); - } - - public IndexQuery(String val1, String val2) { - this(new Value(val1), new Value(val2)); - } - - /** - * getOperator returns the operator associated with this query. - * - * @return The operator - */ - public int getOperator() { - return op; - } - - /** - * getValue returns one of the Values associated with this query. - * - * @param index The Value index - * @return The request Value - */ - public final Value getValue(int index) { - return vals[index]; - } - - /** - * getValues returns the Values associated with this query. - * - * @return The Value set - */ - public Value[] getValues() { - return vals; - } - - /** - * getLength returns the length of the Value set associated with - * this query. - * - * @return The Value set length - */ - public final int getLength() { - return vals.length; - } - - /** - * testValue tests the specified value for validity against this - * IndexQuery. The helper classes in org.apache.xindice.core.indexer.helpers - * should be used for optimized performance. - * - * @param value The Value to compare - * @return Whether or not the value matches - */ - public boolean testValue(Value value) { - switch (op) { - // No Comparison (Any) - case ANY: - return true; - - // Singleton Comparisons - case EQ: - return value.equals(vals[0]); - - case NEQ: - return !value.equals(vals[0]); - - case GT: - return value.compareTo(vals[0]) > 0; - - case LEQ: - return value.compareTo(vals[0]) <= 0; - - case LT: - return value.compareTo(vals[0]) < 0; - - case GEQ: - return value.compareTo(vals[0]) >= 0; - - // Range Comparisons - case BW: - return value.compareTo(vals[0]) >= 0 && value.compareTo(vals[1]) <= 0; - - case NBW: - return value.compareTo(vals[0]) <= 0 || value.compareTo(vals[1]) >= 0; - - case BWX: - return value.compareTo(vals[0]) > 0 && value.compareTo(vals[1]) < 0; - - case NBWX: - return value.compareTo(vals[0]) < 0 || value.compareTo(vals[1]) > 0; - - // Set Comparisons - case IN: - case NIN: - return Arrays.binarySearch(vals, value) >= 0 ? op == IN : op == NIN; - - // Other comparisons - case SW: - case NSW: - return value.startsWith(vals[0]) ? op == SW : op == NSW; - - case EW: - case NEW: - return value.endsWith(vals[0]) ? op == EW : op == NEW; - - } - return false; - } - - /** - * testValue tests the specified value for validity against this - * IndexQuery. The helper classes in org.apache.xindice.core.indexer.helpers - * should be used for optimized performance. - * - * @param value The Value to compare - * @return Whether or not the value matches - */ - public final boolean testValue(String value) { - return testValue(new Value(value)); - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/indexer/Indexer.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/indexer/Indexer.java deleted file mode 100644 index d0f4d5d0..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/indexer/Indexer.java +++ /dev/null @@ -1,99 +0,0 @@ -package net.jxta.impl.xindice.core.indexer; - - -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - - */ - -import net.jxta.impl.xindice.core.*; -import net.jxta.impl.xindice.core.data.*; - - -/** - * Indexer is the abstract indexing interface for Xindice. An Indexer - * object is implemented in order to retrieve and manage indexes. - *

            - * Any number of Indexer instances may be associated with a single - * Collection. The type of Indexer utilized by a query depends on - * the 'Style' of Indexer and the type of QueryResolver that is being - * used to performt he query. Currently, Xindice only internally - * supports one kind of Indexer: 'XPath'. - */ - -public interface Indexer extends DBObject { - - /** - * remove removes all references to the specified Key from the Indexer. - * - * @param key The Object ID - */ - void remove(Key key) throws DBException; - - /** - * add adds a Document to the Indexer. - * - * @param key The Object ID - * @param pos record position - */ - void add(Key key, long pos) throws DBException; - - /** - * flush forcefully flushes any unwritten buffers to disk. - */ - void flush() throws DBException; -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/indexer/NameIndexer.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/indexer/NameIndexer.java deleted file mode 100644 index 6af7fe3f..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/core/indexer/NameIndexer.java +++ /dev/null @@ -1,113 +0,0 @@ -package net.jxta.impl.xindice.core.indexer; - - -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - - */ - -import net.jxta.impl.xindice.core.DBException; -import net.jxta.impl.xindice.core.data.Key; -import net.jxta.impl.xindice.core.filer.BTree; -import net.jxta.impl.xindice.core.filer.BTreeCorruptException; - -import java.io.File; -import java.io.IOException; - - -/** - * NameIndexer is a basic implementation of the Indexer interface. - * It is used for maintaining element and element@attribute unique - * indexes. - */ - -public final class NameIndexer extends BTree implements Indexer { - - private static final short PAGESIZE = 4096; - // TODO: MAXKEYSIZE might need tuning - private static final short MAXKEYSIZE = 256; - - private FileHeader fileHeader; - - public NameIndexer() { - super(); - fileHeader = getFileHeader(); - fileHeader.setPageSize(PAGESIZE); - fileHeader.setMaxKeySize(MAXKEYSIZE); - } - - public void setLocation(String dir, String file) { - setFile(new File(dir, file + ".idx")); - } - - public synchronized void remove(Key key) throws DBException { - try { - removeValue(key); - } catch (IOException e) { - throw new BTreeCorruptException("Corruption detected on remove"); - } - } - - public synchronized void add(Key key, long pos) throws DBException { - try { - addValue(key, pos); - flush(); - } catch (IOException e) { - throw new BTreeCorruptException("Corruption detected on add"); - } - } -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/util/Named.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/util/Named.java deleted file mode 100644 index 17be80a6..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/util/Named.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.jxta.impl.xindice.util; - - -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - - */ - -/** - * Named identifies an object as having a contextually important Name. - */ - -public interface Named { - - /** - * getName retrieves the contextually important name of the object - * - * @return The object's name - */ - String getName(); -} - diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/util/XindiceException.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/util/XindiceException.java deleted file mode 100644 index 8fe76822..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/util/XindiceException.java +++ /dev/null @@ -1,86 +0,0 @@ -package net.jxta.impl.xindice.util; - - -/* - * The Apache Software License, Version 1.1 - * - * - * Copyright (c) 1999 The Apache Software Foundation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * 2. Redistributions 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. - * - * 3. The end-user documentation included with the redistribution, - * if any, must include the following acknowledgment: - * "This product includes software developed by the - * Apache Software Foundation (http://www.apache.org/)." - * Alternately, this acknowledgment may appear in the software itself, - * if and wherever such third-party acknowledgments normally appear. - * - * 4. The names "Xindice" and "Apache Software Foundation" must - * not be used to endorse or promote products derived from this - * software without prior written permission. For written - * permission, please contact apache@apache.org. - * - * 5. Products derived from this software may not be called "Apache", - * nor may "Apache" appear in their name, without prior written - * permission of the Apache Software Foundation. - * - * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR - * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF - * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT - * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation and was - * originally based on software copyright (c) 1999-2001, The dbXML - * Group, L.L.C., http://www.dbxmlgroup.com. For more - * information on the Apache Software Foundation, please see - * . - * - - */ - -import java.io.*; - - -/** - * A XindiceException is the base class for all Xindice related - * Exceptions. - */ - -public class XindiceException extends Exception { - - public XindiceException() {} - - public XindiceException(String message) { - super(message); - } - - public XindiceException(String message, Throwable wrapped) { - super(message); - initCause(wrapped); - } - - public Throwable getWrappedThrowable() { - return getCause(); - } -} diff --git a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/util/XindiceRuntimeException.java b/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/util/XindiceRuntimeException.java deleted file mode 100644 index cdddff9c..00000000 --- a/p2pproxy/dependencies-src/jxse-src-2.5/impl/src/net/jxta/impl/xindice/util/XindiceRuntimeException.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * CVS $Id$ - * CVS XindiceRuntimeException.java,v 1.5 2004/02/08 02:59:39 vgritsenko Exp $ - */ - -package net.jxta.impl.xindice.util; - - -import java.io.PrintStream; -import java.io.PrintWriter; - - -/** - * A XindiceRuntimeException is the base class for all Xindice related RuntimeExceptions. - * - * @version CVS $Revision$, $Date$ - */ -public class XindiceRuntimeException extends RuntimeException { - protected Throwable cause; - - public XindiceRuntimeException() {} - - public XindiceRuntimeException(String message) { - super(message); - } - - public XindiceRuntimeException(Throwable cause) { - super(); - this.cause = cause; - } - - public XindiceRuntimeException(String message, Throwable cause) { - super(message); - this.cause = cause; - } - - @Override - public void printStackTrace() { - printStackTrace(System.err); - } - - @Override - public void printStackTrace(PrintStream s) { - super.printStackTrace(s); - if (this.cause != null) { - s.print("Caused by: "); - this.cause.printStackTrace(s); - } - } - - @Override - public void printStackTrace(PrintWriter s) { - super.printStackTrace(s); - if (this.cause != null) { - s.print("Caused by: "); - this.cause.printStackTrace(s); - } - } - - @Override - public Throwable getCause() { - return cause; - } -} diff --git a/p2pproxy/dependencies/MJSIP.COPYRIGHT.txt b/p2pproxy/dependencies/MJSIP.COPYRIGHT.txt deleted file mode 100644 index 9aa8e354..00000000 --- a/p2pproxy/dependencies/MJSIP.COPYRIGHT.txt +++ /dev/null @@ -1,22 +0,0 @@ -MjSip - http://www.mjsip.org - -Copyright (C) 2005 by Luca Veltri - University of Parma - Italy. -__________________________________________________ - - -MjSip is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -MjSip is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with MjSip; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - -PLEASE READ CAREFULLY THE LICENSE DOCUMENT RECEIVED ALONG WITH THIS LIBRARY. \ No newline at end of file diff --git a/p2pproxy/dependencies/bcprov-jdk14.jar b/p2pproxy/dependencies/bcprov-jdk14.jar deleted file mode 100644 index b27a8109..00000000 Binary files a/p2pproxy/dependencies/bcprov-jdk14.jar and /dev/null differ diff --git a/p2pproxy/dependencies/bouncycastle-LICENSE.txt b/p2pproxy/dependencies/bouncycastle-LICENSE.txt deleted file mode 100644 index e8a967c3..00000000 --- a/p2pproxy/dependencies/bouncycastle-LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -License - -Copyright (c) 2000 - 2004 The Legion Of The Bouncy Castle -(http://www.bouncycastle.org) - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/p2pproxy/dependencies/javax.servlet.jar b/p2pproxy/dependencies/javax.servlet.jar deleted file mode 100644 index d2dee6f9..00000000 Binary files a/p2pproxy/dependencies/javax.servlet.jar and /dev/null differ diff --git a/p2pproxy/dependencies/jstun-0.7.0.jar b/p2pproxy/dependencies/jstun-0.7.0.jar deleted file mode 100644 index 4d220efe..00000000 Binary files a/p2pproxy/dependencies/jstun-0.7.0.jar and /dev/null differ diff --git a/p2pproxy/dependencies/junit-4.3.1.jar b/p2pproxy/dependencies/junit-4.3.1.jar deleted file mode 100644 index ff5d1888..00000000 Binary files a/p2pproxy/dependencies/junit-4.3.1.jar and /dev/null differ diff --git a/p2pproxy/dependencies/jxta_license.html b/p2pproxy/dependencies/jxta_license.html deleted file mode 100644 index ceb0e5ce..00000000 --- a/p2pproxy/dependencies/jxta_license.html +++ /dev/null @@ -1,248 +0,0 @@ - - - - - - - - - - - - - - - - - Content - - - - - - - - - - - - - - -

            - - - - - - - - - - - - - - - -
            - -
            - - - - - - - - - - - - - - - - - - - - - - -
            The Sun Project JXTA(TM) Software License (Based on the Apache Software License Version 1.1)
            - - - - - -


            -Copyright (c) 2001-2004 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:

            - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

            - -2. Redistributions 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.

            - -3. The end-user documentation included with the redistribution, if any, must -include the following acknowledgment: "This product includes software -developed by Sun Microsystems, Inc. for JXTA(TM) technology." Alternately, this -acknowledgment may appear in the software itself, if and wherever such -third-party acknowledgments normally appear.

            - -4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must -not be used to endorse or promote products derived from this software without -prior written permission. For written permission, please contact Project JXTA -at http://www.jxta.org.

            - -5. Products derived from this software may not be called "JXTA", nor may "JXTA" -appear in their name, without prior written permission of Sun.

            - -THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL SUN MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

            -JXTA is a registered trademark of Sun Microsystems, Inc. in the United States and other countries.

            -
            -

            Please see the license - information page for instructions on use of the license in source - files.

            -

            This software consists of voluntary contributions made by many individuals - on behalf of Project JXTA. For more information on Project JXTA, please - see http://www.jxta.org.
            -
            - This license is based on the BSD license adopted by the Apache Foundation. -

            -
            -
            -
            - - - - - - - diff --git a/p2pproxy/dependencies/log4j.LICENSE b/p2pproxy/dependencies/log4j.LICENSE deleted file mode 100644 index 6279e520..00000000 --- a/p2pproxy/dependencies/log4j.LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 1999-2005 The Apache Software Foundation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/p2pproxy/dependencies/log4j.jar b/p2pproxy/dependencies/log4j.jar deleted file mode 100644 index dde99721..00000000 Binary files a/p2pproxy/dependencies/log4j.jar and /dev/null differ diff --git a/p2pproxy/dependencies/org.mortbay.jetty.jar b/p2pproxy/dependencies/org.mortbay.jetty.jar deleted file mode 100644 index db8d0811..00000000 Binary files a/p2pproxy/dependencies/org.mortbay.jetty.jar and /dev/null differ diff --git a/p2pproxy/dependencies/sip.jar b/p2pproxy/dependencies/sip.jar deleted file mode 100644 index a8e98841..00000000 Binary files a/p2pproxy/dependencies/sip.jar and /dev/null differ diff --git a/p2pproxy/launcher/.cdtproject b/p2pproxy/launcher/.cdtproject deleted file mode 100644 index a080fffa..00000000 --- a/p2pproxy/launcher/.cdtproject +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/p2pproxy/launcher/.cproject b/p2pproxy/launcher/.cproject deleted file mode 100644 index a6611c76..00000000 --- a/p2pproxy/launcher/.cproject +++ /dev/null @@ -1,848 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/p2pproxy/launcher/.project b/p2pproxy/launcher/.project deleted file mode 100644 index cf9890a0..00000000 --- a/p2pproxy/launcher/.project +++ /dev/null @@ -1,81 +0,0 @@ - - - p2pproxy-launcher - - - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - org.eclipse.cdt.make.core.fullBuildTarget - all - - - ?name? - - - - org.eclipse.cdt.make.core.enableAutoBuild - false - - - org.eclipse.cdt.make.core.buildLocation - ${workspace_loc:/p2pproxy-launcher/Debug} - - - org.eclipse.cdt.make.core.enableFullBuild - true - - - org.eclipse.cdt.make.core.enableCleanBuild - true - - - org.eclipse.cdt.make.core.cleanBuildTarget - clean - - - org.eclipse.cdt.make.core.append_environment - true - - - org.eclipse.cdt.make.core.contents - org.eclipse.cdt.make.core.activeConfigSettings - - - org.eclipse.cdt.make.core.useDefaultBuildCmd - true - - - org.eclipse.cdt.make.core.buildArguments - - - - org.eclipse.cdt.make.core.buildCommand - make - - - org.eclipse.cdt.make.core.autoBuildTarget - all - - - org.eclipse.cdt.make.core.stopOnError - true - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - - diff --git a/p2pproxy/launcher/.settings/org.eclipse.cdt.core.prefs b/p2pproxy/launcher/.settings/org.eclipse.cdt.core.prefs deleted file mode 100644 index 488bd5f7..00000000 --- a/p2pproxy/launcher/.settings/org.eclipse.cdt.core.prefs +++ /dev/null @@ -1,3 +0,0 @@ -#Wed Sep 24 10:53:31 CEST 2008 -eclipse.preferences.version=1 -environment/project/cdt.managedbuild.config.gnu.exe.debug.312796505=\n\n diff --git a/p2pproxy/launcher/Debug/makefile b/p2pproxy/launcher/Debug/makefile deleted file mode 100644 index 9685c760..00000000 --- a/p2pproxy/launcher/Debug/makefile +++ /dev/null @@ -1,44 +0,0 @@ -################################################################################ -# Automatically-generated file. Do not edit! -################################################################################ - --include ../makefile.init - -RM := rm -rf - -# All of the sources participating in the build are defined here --include sources.mk --include subdir.mk --include src/subdir.mk --include objects.mk - -ifneq ($(MAKECMDGOALS),clean) -ifneq ($(strip $(C_DEPS)),) --include $(C_DEPS) -endif -endif - --include ../makefile.defs - -# Add inputs and outputs from these tool invocations to the build variables - -# All Target -all: p2pproxy-launcher - -# Tool invocations -p2pproxy-launcher: $(OBJS) $(USER_OBJS) - @echo 'Building target: $@' - @echo 'Invoking: GCC C Linker' - gcc -L/usr/lib/jvm/java-6-openjdk/jre/lib/amd64 -L/usr/lib/jvm/java-6-openjdk/jre/lib/i386 -L/usr/lib/jvm/java-6-openjdk/jre/lib/amd64/server -L/usr/lib/jvm/java-6-openjdk/jre/lib/i386/server -o"p2pproxy-launcher" $(OBJS) $(USER_OBJS) $(LIBS) - @echo 'Finished building target: $@' - @echo ' ' - -# Other Targets -clean: - -$(RM) $(OBJS)$(EXECUTABLES)$(C_DEPS) p2pproxy-launcher - -@echo ' ' - -.PHONY: all clean dependents -.SECONDARY: - --include ../makefile.targets diff --git a/p2pproxy/launcher/Debug/objects.mk b/p2pproxy/launcher/Debug/objects.mk deleted file mode 100644 index bb7a3d53..00000000 --- a/p2pproxy/launcher/Debug/objects.mk +++ /dev/null @@ -1,7 +0,0 @@ -################################################################################ -# Automatically-generated file. Do not edit! -################################################################################ - -LIBS := -ljvm - -USER_OBJS := diff --git a/p2pproxy/launcher/Debug/sources.mk b/p2pproxy/launcher/Debug/sources.mk deleted file mode 100644 index 1b13571a..00000000 --- a/p2pproxy/launcher/Debug/sources.mk +++ /dev/null @@ -1,17 +0,0 @@ -################################################################################ -# Automatically-generated file. Do not edit! -################################################################################ - -C_SRCS := -O_SRCS := -ASM_SRCS := -S_SRCS := -OBJ_SRCS := -OBJS := -EXECUTABLES := -C_DEPS := - -# Every subdirectory with source files must be described here -SUBDIRS := \ -src \ - diff --git a/p2pproxy/launcher/Debug/src/launcher-tester.d b/p2pproxy/launcher/Debug/src/launcher-tester.d deleted file mode 100644 index f3d7000d..00000000 --- a/p2pproxy/launcher/Debug/src/launcher-tester.d +++ /dev/null @@ -1,4 +0,0 @@ -src/launcher-tester.d src/launcher-tester.o: ../src/launcher-tester.c \ - ../src/p2pproxy.h - -../src/p2pproxy.h: diff --git a/p2pproxy/launcher/Debug/src/p2pproxy.d b/p2pproxy/launcher/Debug/src/p2pproxy.d deleted file mode 100644 index a6f15d48..00000000 --- a/p2pproxy/launcher/Debug/src/p2pproxy.d +++ /dev/null @@ -1,9 +0,0 @@ -src/p2pproxy.d src/p2pproxy.o: ../src/p2pproxy.c \ - /usr/lib/jvm/java-6-openjdk/include/jni.h \ - /usr/lib/jvm/java-6-openjdk/include/jni_md.h ../src/p2pproxy.h - -/usr/lib/jvm/java-6-openjdk/include/jni.h: - -/usr/lib/jvm/java-6-openjdk/include/jni_md.h: - -../src/p2pproxy.h: diff --git a/p2pproxy/launcher/Debug/src/p2pproxy_wrap.d b/p2pproxy/launcher/Debug/src/p2pproxy_wrap.d deleted file mode 100644 index d3752241..00000000 --- a/p2pproxy/launcher/Debug/src/p2pproxy_wrap.d +++ /dev/null @@ -1,7 +0,0 @@ -src/p2pproxy_wrap.d src/p2pproxy_wrap.o: ../src/p2pproxy_wrap.c \ - /usr/lib/jvm/java-6-openjdk/include/jni.h \ - /usr/lib/jvm/java-6-openjdk/include/jni_md.h - -/usr/lib/jvm/java-6-openjdk/include/jni.h: - -/usr/lib/jvm/java-6-openjdk/include/jni_md.h: diff --git a/p2pproxy/launcher/Debug/src/subdir.mk b/p2pproxy/launcher/Debug/src/subdir.mk deleted file mode 100644 index 6246aeb1..00000000 --- a/p2pproxy/launcher/Debug/src/subdir.mk +++ /dev/null @@ -1,37 +0,0 @@ -################################################################################ -# Automatically-generated file. Do not edit! -################################################################################ - -# Add inputs and outputs from these tool invocations to the build variables -C_SRCS += \ -../src/launcher-tester.c \ -../src/p2pproxy.c \ -../src/p2pproxy_wrap.c - -OBJS += \ -./src/launcher-tester.o \ -./src/p2pproxy.o \ -./src/p2pproxy_wrap.o - -C_DEPS += \ -./src/launcher-tester.d \ -./src/p2pproxy.d \ -./src/p2pproxy_wrap.d - - -# Each subdirectory must supply rules for building sources it contributes -src/%.o: ../src/%.c - @echo 'Building file: $<' - @echo 'Invoking: GCC C Compiler' - gcc -I/usr/lib/jvm/java-6-openjdk/include -O0 -g3 -Wall -c -fmessage-length=0 -ansi -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o"$@" "$<" - @echo 'Finished building: $<' - @echo ' ' - -src/p2pproxy.o: ../src/p2pproxy.c - @echo 'Building file: $<' - @echo 'Invoking: GCC C Compiler' - gcc -I/usr/lib/jvm/java-6-openjdk/include -O2 -g -Wall -c -fmessage-length=0 -ansi -MMD -MP -MF"$(@:%.o=%.d)" -MT"src/p2pproxy.d" -o"$@" "$<" - @echo 'Finished building: $<' - @echo ' ' - - diff --git a/p2pproxy/launcher/Makefile.am b/p2pproxy/launcher/Makefile.am deleted file mode 100644 index 1bfdcf48..00000000 --- a/p2pproxy/launcher/Makefile.am +++ /dev/null @@ -1 +0,0 @@ -SUBDIRS=src diff --git a/p2pproxy/launcher/src/Makefile.am b/p2pproxy/launcher/src/Makefile.am deleted file mode 100644 index a47d2326..00000000 --- a/p2pproxy/launcher/src/Makefile.am +++ /dev/null @@ -1,24 +0,0 @@ -JAVA_LIBS=-L$(javadir)/jre/lib/amd64 -L$(javadir)/jre/lib/i386 \ - -L$(javadir)/jre/lib/amd64/server -L$(javadir)/jre/lib/i386/server -ljava - -JAVA_LDFLAGS=\ - -Wl,-rpath,$(javadir)/jre/lib/amd64 -Wl,-rpath,$(javadir)/jre/lib/i386 \ - -Wl,-rpath,$(javadir)/jre/lib/amd64/server -Wl,-rpath,$(javadir)/jre/lib/i386/server - -noinst_LTLIBRARIES=libfonisc.la - -libfonisc_la_SOURCES=p2pproxy.c p2pproxy.h - -libfonisc_la_LIBADD=$(JAVA_LIBS) - -libfonisc_la_LDFLAGS=$(JAVA_LDFLAGS) - -noinst_PROGRAMS=launcher-tester - -launcher_tester_SOURCES=launcher-tester.c - -launcher_tester_LDADD=libfonisc.la $(JAVA_LIBS) - -launcher_tester_LDFLAGS=$(JAVA_LDFLAGS) - -INCLUDES=-I$(javadir)/include -I$(javadir)/include/linux diff --git a/p2pproxy/launcher/src/launcher-tester.c b/p2pproxy/launcher/src/launcher-tester.c deleted file mode 100644 index 810010b5..00000000 --- a/p2pproxy/launcher/src/launcher-tester.c +++ /dev/null @@ -1,98 +0,0 @@ -#include "p2pproxy.h" -#include -#include - -static void * thread_starter(void *args){ - char* largs[] = {"-seeding-server","-sip", "5058"}; - p2pproxy_application_start(3,largs); - printf("exit from application \n"); - return NULL; -} - - -int main(int argc, char **argv) { - pthread_t th; - printf("starting p2pproxy tester \n"); - pthread_create(&th,NULL,thread_starter,NULL); - sleep(5); - - if (p2pproxy_application_get_state() == P2PPROXY_CONNECTED) { - printf("CONNECTED \n"); - } else { - printf("NOT CONNECTED \n"); - }; - - - /* account management */ - - if (p2pproxy_accountmgt_createAccount("sip:titi@p2p.linphone.org") != P2PPROXY_NO_ERROR) { - printf("cannot create account \n"); - } - - - if (p2pproxy_accountmgt_isValidAccount("sip:titi@p2p.linphone.org") != P2PPROXY_ACCOUNTMGT_USER_EXIST) { - printf("user not created \n"); - } - /* sip proxy */ - char string_buffer[256]; - if (p2pproxy_resourcemgt_lookup_sip_proxy(string_buffer,256,"p2p.linphone.org") != P2PPROXY_NO_ERROR) { - printf("cannot get proxy\n"); - } else { - printf("registrar is [%s]\n",string_buffer); - } - - if (p2pproxy_resourcemgt_revoke_sip_proxy(string_buffer) != P2PPROXY_NO_ERROR) { - printf("cannot fulsh proxy [%s]\n",string_buffer); - } - - if (p2pproxy_resourcemgt_lookup_sip_proxy(string_buffer,256,"toto.linphone.org") != P2PPROXY_RESOURCEMGT_SERVER_NOT_FOUND) { - printf("unexpected proxy [%s]\n",string_buffer); - } else { - printf("cannot find proxy\n"); - } - - /* media resource mgt */ - p2pproxy_resourcemgt_resource_list_t* resource_list; - resource_list = p2pproxy_resourcemgt_new_resource_list(); - if (resource_list == 0) { - printf("cannot allocate p2pproxy_resourcemgt_resource_list_t \n"); - } else { - - if (p2pproxy_resourcemgt_lookup_media_resource(resource_list,"p2p.linphone.org") != P2PPROXY_NO_ERROR) { - printf("cannot get media resource\n"); - } else { - int i; - for (i=0;isize;i++) { - printf("media resource is [%s]\n",resource_list->resource_uri[i]); - } - - } - - if (p2pproxy_resourcemgt_revoke_media_resource(resource_list->resource_uri[0]) != P2PPROXY_NO_ERROR) { - printf("cannot fulsh media resource [%s]\n",resource_list->resource_uri[0]); - } - - if (p2pproxy_resourcemgt_lookup_media_resource(resource_list,"p2p.linphone.org") != P2PPROXY_NO_ERROR) { - printf("cannot get media resource\n"); - } else { - int i; - for (i=0;isize;i++) { - printf("media resource is [%s]\n",resource_list->resource_uri[i]); - } - - } - p2pproxy_resourcemgt_delete_resource_list(resource_list); - } - - - - - if (p2pproxy_accountmgt_deleteAccount("sip:titi@p2p.linphone.org") != P2PPROXY_NO_ERROR) { - printf("cannot delete account \n"); - } - - - p2pproxy_application_stop(); - pthread_join(th,NULL); - return 0; -} diff --git a/p2pproxy/launcher/src/p2pproxy.c b/p2pproxy/launcher/src/p2pproxy.c deleted file mode 100644 index 05574c55..00000000 --- a/p2pproxy/launcher/src/p2pproxy.c +++ /dev/null @@ -1,268 +0,0 @@ -#include -#include -#include -#include -#include "p2pproxy.h" - -#ifndef P2PPROXY_JMX_PORT - #define P2PPROXY_JMX_PORT "5678" -#endif -#ifndef P2PPROXY_INSTALLDIR - #define P2PPROXY_INSTALLDIR "/usr/share/java/fonis" -#endif -#ifndef P2PPROXY_BUILDDIR - #define P2PPROXY_BUILDDIR "../antbuild/dist/p2pproxy_0.1" -#endif -#define NUMBER_OF_OPTION 7 -JavaVM *p2pproxy_application_jvm = 0; - -#define GET_JNI_ENV \ - jint lResult = 0 ;\ - JNIEnv *lJniEnv = 0;\ - jclass lMainClass = 0;\ - if (p2pproxy_application_jvm==0) return P2PPROXY_ERROR_APPLICATION_NOT_STARTED; \ - lResult = (*p2pproxy_application_jvm)->AttachCurrentThread(p2pproxy_application_jvm,(void**)&lJniEnv,NULL);\ - if (lResult != 0) { \ - fprintf(stderr,"cannot attach VM\n");\ - return P2PPROXY_ERROR;\ - }\ - lMainClass = (*lJniEnv)->FindClass(lJniEnv, "org/linphone/p2pproxy/core/P2pProxyMain");\ - if (lMainClass == 0) { \ - fprintf(stderr,"cannot load class org/linphone/p2pproxy/core/P2pProxyMain\n");\ - return P2PPROXY_ERROR; \ - } \ - - -int p2pproxy_application_start(int argc, char **argv) { - JNIEnv *lJniEnv = 0; - jclass lMainClass = 0; - JavaVMInitArgs args; - JavaVMOption options[NUMBER_OF_OPTION]; - jint res=-1; - jmethodID mainMethod; - jobjectArray applicationArgsList; - jstring applicationArg; - int i=0; - int optioncount=0; - - if (p2pproxy_application_jvm != 0) { - fprintf(stderr,"p2pproxy already started"); - return P2PPROXY_ERROR_APPLICATION_ALREADY_STARTED; - } - args.version = JNI_VERSION_1_4; - - /*options[optioncount++].optionString = "-verbose:jni";*/ - /*options[optioncount++].optionString = "-verbose:class";*/ - /*options[optioncount++].optionString = "-verbose:class";*/ - options[optioncount++].optionString = "-Djava.class.path="P2PPROXY_BUILDDIR"/p2pproxy.jar:"\ - P2PPROXY_INSTALLDIR"/p2pproxy.jar:"\ - P2PPROXY_BUILDDIR"/log4j.jar:"\ - P2PPROXY_INSTALLDIR"/log4j.jar"; - - - - options[optioncount++].optionString = "-Dcom.sun.management.jmxremote"; - options[optioncount++].optionString = "-Dcom.sun.management.jmxremote.port="P2PPROXY_JMX_PORT; - options[optioncount++].optionString = "-Dcom.sun.management.jmxremote.authenticate=false"; - options[optioncount++].optionString = "-Dcom.sun.management.jmxremote.ssl=false"; - options[optioncount++].optionString = "-Dorg.linphone.p2pproxy.install.dir="P2PPROXY_INSTALLDIR; - options[optioncount++].optionString = "-Dorg.linphone.p2pproxy.build.dir="P2PPROXY_BUILDDIR; - - args.nOptions = NUMBER_OF_OPTION; - args.options = options; - args.ignoreUnrecognized = JNI_FALSE; - - - res = JNI_CreateJavaVM(&p2pproxy_application_jvm, (void**)& lJniEnv, &args); - if (res < 0) { - fprintf(stderr,"cannot start p2pproxy vm [%i]",res); - return P2PPROXY_ERROR; - } - lMainClass = (*lJniEnv)->FindClass(lJniEnv, "org/linphone/p2pproxy/core/P2pProxyMain"); - - if (lMainClass == 0) { - fprintf(stderr,"cannot load class org/linphone/p2pproxy/core/P2pProxyMain\n"); - return P2PPROXY_ERROR; - } - mainMethod = (*lJniEnv)->GetStaticMethodID(lJniEnv, lMainClass, "main", "([Ljava/lang/String;)V"); - - applicationArgsList = (*lJniEnv)->NewObjectArray(lJniEnv, argc, (*lJniEnv)->FindClass(lJniEnv, "java/lang/String"), NULL); - - for (i=0;iNewStringUTF(lJniEnv, argv[i]); - (*lJniEnv)->SetObjectArrayElement(lJniEnv, applicationArgsList, i, applicationArg); - - } - - (*lJniEnv)->CallStaticVoidMethod(lJniEnv, lMainClass, mainMethod, applicationArgsList); - (*p2pproxy_application_jvm)->DestroyJavaVM(p2pproxy_application_jvm); - p2pproxy_application_jvm = 0; - return P2PPROXY_NO_ERROR; -} - - - -const char* p2pproxy_status_string(int status_code) { - return 0; -} - - -int p2pproxy_accountmgt_createAccount(const char* user_name) { - jmethodID createAccountMethod; - jstring applicationArg; - GET_JNI_ENV - createAccountMethod = (*lJniEnv)->GetStaticMethodID(lJniEnv, lMainClass, "createAccount", "(Ljava/lang/String;)I"); - applicationArg = (*lJniEnv)->NewStringUTF(lJniEnv, user_name); - lResult = (*lJniEnv)->CallStaticIntMethod(lJniEnv, lMainClass, createAccountMethod, applicationArg); - (*p2pproxy_application_jvm)->DetachCurrentThread(p2pproxy_application_jvm); - return lResult; -} - -int p2pproxy_accountmgt_isValidAccount(const char* user_name) { - jmethodID isValidAccountMethod; - jstring applicationArg; - GET_JNI_ENV - isValidAccountMethod = (*lJniEnv)->GetStaticMethodID(lJniEnv, lMainClass, "isValidAccount", "(Ljava/lang/String;)I"); - applicationArg = (*lJniEnv)->NewStringUTF(lJniEnv, user_name); - lResult = (*lJniEnv)->CallStaticIntMethod(lJniEnv, lMainClass, isValidAccountMethod, applicationArg); - (*p2pproxy_application_jvm)->DetachCurrentThread(p2pproxy_application_jvm); - return lResult; -} - -int p2pproxy_accountmgt_deleteAccount(const char* user_name) { - jmethodID deleteAccountMethod; - jstring applicationArg; - GET_JNI_ENV - deleteAccountMethod = (*lJniEnv)->GetStaticMethodID(lJniEnv, lMainClass, "deleteAccount", "(Ljava/lang/String;)I"); - applicationArg = (*lJniEnv)->NewStringUTF(lJniEnv, user_name); - lResult = (*lJniEnv)->CallStaticIntMethod(lJniEnv, lMainClass, deleteAccountMethod, applicationArg); - (*p2pproxy_application_jvm)->DetachCurrentThread(p2pproxy_application_jvm); - return lResult; -} - -int p2pproxy_resourcemgt_lookup_sip_proxy(char* proxy_uri,size_t size, const char* domain) { - jmethodID lLookupSipProxyUriMethod; - jstring lJStringResult; - const char* lString; - jboolean lIsCopy; - jstring applicationArg; - - GET_JNI_ENV - - - applicationArg = (*lJniEnv)->NewStringUTF(lJniEnv, domain); - lLookupSipProxyUriMethod = (*lJniEnv)->GetStaticMethodID(lJniEnv, lMainClass, "lookupSipProxyUri", "(Ljava/lang/String;)Ljava/lang/String;"); - lJStringResult = (*lJniEnv)->CallStaticObjectMethod(lJniEnv, lMainClass, lLookupSipProxyUriMethod, applicationArg); - if (lJStringResult == 0) { - return P2PPROXY_RESOURCEMGT_SERVER_NOT_FOUND; - } - lString = (*lJniEnv)->GetStringUTFChars(lJniEnv, lJStringResult, &lIsCopy); - memcpy(proxy_uri,lString,size); - (*lJniEnv)->ReleaseStringUTFChars(lJniEnv, lJStringResult, lString); - (*p2pproxy_application_jvm)->DetachCurrentThread(p2pproxy_application_jvm); - return P2PPROXY_NO_ERROR; -} - -int p2pproxy_resourcemgt_revoke_sip_proxy(const char* proxy_uri) { - jmethodID revokeProxyMethod; - jstring applicationArg; - GET_JNI_ENV - - applicationArg = (*lJniEnv)->NewStringUTF(lJniEnv, proxy_uri); - revokeProxyMethod = (*lJniEnv)->GetStaticMethodID(lJniEnv, lMainClass, "revokeSipProxy", "(Ljava/lang/String;)I"); - lResult = (*lJniEnv)->CallStaticIntMethod(lJniEnv, lMainClass, revokeProxyMethod,applicationArg); - (*p2pproxy_application_jvm)->DetachCurrentThread(p2pproxy_application_jvm); - return lResult; -} - -int p2pproxy_application_get_state() { - jmethodID stateMethod; - GET_JNI_ENV - stateMethod = (*lJniEnv)->GetStaticMethodID(lJniEnv, lMainClass, "getState", "()I"); - if (stateMethod==NULL) { - lResult=P2PPROXY_ERROR_APPLICATION_NOT_STARTED; - goto end; - } - lResult = (*lJniEnv)->CallStaticIntMethod(lJniEnv, lMainClass, stateMethod); - goto end; - end: - (*p2pproxy_application_jvm)->DetachCurrentThread(p2pproxy_application_jvm); - return lResult; - -} - -int p2pproxy_application_stop() { - jmethodID stopMethod = 0; - GET_JNI_ENV - - stopMethod = (*lJniEnv)->GetStaticMethodID(lJniEnv, lMainClass, "stop", "()V"); - (*lJniEnv)->CallStaticVoidMethod(lJniEnv, lMainClass, stopMethod); - (*p2pproxy_application_jvm)->DetachCurrentThread(p2pproxy_application_jvm); - return 0; -} - - -p2pproxy_resourcemgt_resource_list_t* p2pproxy_resourcemgt_new_resource_list() { - p2pproxy_resourcemgt_resource_list_t* resource_list = malloc(sizeof (p2pproxy_resourcemgt_resource_list_t)); - resource_list->size = 0; - return resource_list; -} - -void p2pproxy_resourcemgt_delete_resource_list(p2pproxy_resourcemgt_resource_list_t* resource_list) { - int i; - if (resource_list == 0 ) { - return; - } - for (i=0;isize;i++) { - free(resource_list->resource_uri[i]); - } - resource_list->size = 0; - free(resource_list); -} - -int p2pproxy_resourcemgt_lookup_media_resource(p2pproxy_resourcemgt_resource_list_t* resource_list, const char* domain) { - jmethodID lLookupMediaResourceMethod; - jarray lJStringResults; - jstring lResourceInstance; - const char* lString; - jboolean lIsCopy; - jstring applicationArg; - int i; - jsize lStringSize; - jsize lArraySize; - - GET_JNI_ENV - - - applicationArg = (*lJniEnv)->NewStringUTF(lJniEnv, domain); - lLookupMediaResourceMethod = (*lJniEnv)->GetStaticMethodID(lJniEnv, lMainClass, "lookupMediaServerAddress", "(Ljava/lang/String;)[Ljava/lang/String;"); - lJStringResults = (*lJniEnv)->CallStaticObjectMethod(lJniEnv, lMainClass, lLookupMediaResourceMethod, applicationArg); - if (lJStringResults == 0) { - return P2PPROXY_RESOURCEMGT_SERVER_NOT_FOUND; - } - - lArraySize = (*lJniEnv)->GetArrayLength(lJniEnv, lJStringResults); - for (i=0;iGetObjectArrayElement(lJniEnv,lJStringResults, i); - lString = (*lJniEnv)->GetStringUTFChars(lJniEnv, lResourceInstance, &lIsCopy); - lStringSize = (*lJniEnv)->GetStringLength(lJniEnv, lResourceInstance); - resource_list->resource_uri[i] = malloc(lStringSize); - strcpy(resource_list->resource_uri[i],lString); - resource_list->size=i; - (*lJniEnv)->ReleaseStringUTFChars(lJniEnv, lResourceInstance, lString); - } - - (*p2pproxy_application_jvm)->DetachCurrentThread(p2pproxy_application_jvm); - return P2PPROXY_NO_ERROR; -} -int p2pproxy_resourcemgt_revoke_media_resource(const char* resource_uri) { - jmethodID revokeMediaResourceMethod; - jstring applicationArg; - GET_JNI_ENV - - applicationArg = (*lJniEnv)->NewStringUTF(lJniEnv, resource_uri); - revokeMediaResourceMethod = (*lJniEnv)->GetStaticMethodID(lJniEnv, lMainClass, "revokeMediaServer", "(Ljava/lang/String;)I"); - lResult = (*lJniEnv)->CallStaticIntMethod(lJniEnv, lMainClass, revokeMediaResourceMethod,applicationArg); - (*p2pproxy_application_jvm)->DetachCurrentThread(p2pproxy_application_jvm); - return lResult; -} diff --git a/p2pproxy/launcher/src/p2pproxy.h b/p2pproxy/launcher/src/p2pproxy.h deleted file mode 100644 index 158f014d..00000000 --- a/p2pproxy/launcher/src/p2pproxy.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -p2pproxy.h - sip proxy. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef P2PPROXY_LAUNCHER_H_ -#define P2PPROXY_LAUNCHER_H_ - -#include -#ifdef SWIG -%module P2pProxylauncher -%javaconst(1); -%include "p2pproxy.h" -#endif /*SWIG*/ -#define P2PPROXY_EWOULDBLOCK 4 -#define P2PPROXY_ACCOUNTMGT_USER_EXIST 1 -#define P2PPROXY_ACCOUNTMGT_USER_NOT_EXIST 0 -#define P2PPROXY_RESOURCEMGT_SERVER_NOT_FOUND 3 -/* state code*/ -#define P2PPROXY_CONNECTED 2 -#define P2PPROXY_NOT_CONNECTED 1 -/* status code*/ -#define P2PPROXY_NO_ERROR 0 -/*error codes*/ -#define P2PPROXY_ERROR -1 -#define P2PPROXY_ERROR_APPLICATION_NOT_STARTED -2 -#define P2PPROXY_ERROR_APPLICATION_ALREADY_STARTED -3 -#define P2PPROXY_ERROR_ACCOUNTMGT_USER_ALREADY_EXIST -4 -#define P2PPROXY_ERROR_ACCOUNTMGT_BAD_SIP_URI -5 -#define P2PPROXY_ERROR_RESOURCEMGT_SERVER_NOT_FOUND -6 - -#ifndef SWIG -/** - * start p2pproxy application - * blocking call - * @param argc number of argument - * @param argv arguments - * @return status code - * - */ -int p2pproxy_application_start(int argc, char **argv); - -/** - * return status - * @return P2PPROXY_CONNECTED, P2PPROXY_NOT_ERROR - * - */ -int p2pproxy_application_get_state(void); - -/** - * stop p2pproxy application - * - */ -int p2pproxy_application_stop(void); - -/** - * return the status string corresponding to the status code - */ -/*const char* p2pproxy_status_string(int status_code);*/ - -/************************/ -/***account management***/ -/************************/ - -/** -* create an account with the given name (must be unique) -* @param user_name user sip uri (sip:joe@p2p.linphone.org) -* -* @return P2PPROXY_NO_ERROR, P2PPROXY_ERROR_APPLICATIONNOTSTARTED, P2PPROXY_ERROR_ACCOUNTMGT_USERALREADYEXIST, P2PPROXY_ERROR_ACCOUNTMGT_BADSIPURI -*/ -int p2pproxy_accountmgt_createAccount(const char* user_name); -/** -* check if a user name has been already created -* @param user_name user sip uri (sip:joe@p2p.linphone.org) -* @return P2PPROXY_ACCOUNTMGT_USEREXIST, P2PPROXY_ACCOUNTMGT_USERNOTEXIST , P2PPROXY_ERROR_APPLICATIONNOTSTARTED -*/ -int p2pproxy_accountmgt_isValidAccount(const char* user_name); - -/** -* delete an account with the given name -* @param user_name user sip uri (sip:joe@p2p.linphone.org) -* @return P2PPROXY_NO_ERROR, P2PPROXY_ERROR_APPLICATIONNOTSTARTED -*/ -int p2pproxy_accountmgt_deleteAccount(const char* user_name); - -/****************************/ -/***resource management******/ -/****************************/ -/** - * Structure to store resource list, must be instanciated by - * p2pproxy_resourcemgt_new_resource_list and deleted by p2pproxy_resourcemgt_delete_resource_list. - * - */ -#define P2PPROXY_MAX_RESOURCE_LIST_SIZE 10 -typedef struct p2pproxy_resourcemgt_resource_list { - char* resource_uri[P2PPROXY_MAX_RESOURCE_LIST_SIZE]; /* uri list*/ - unsigned char size; /*number of element in the list*/ -} p2pproxy_resourcemgt_resource_list_t; - -/** - * Instanciate a p2pproxy_resourcemgt_resource_list - */ -p2pproxy_resourcemgt_resource_list_t* p2pproxy_resourcemgt_new_resource_list(void); -/** - * delete a p2pproxy_resourcemgt_resource_list - */ -void p2pproxy_resourcemgt_delete_resource_list(p2pproxy_resourcemgt_resource_list_t* resource_list); - -/** -* access a proxy registrar sip addreess for a given domaine name -* @param [out] proxy_uri buffer allocated by the user -* @param [in] size buffer size -* @param [in] domaine name -* @return status code P2PPROXY_NO_ERROR, P2PPROXY_ERROR_RESOURCELOCATOR_SERVER_NOT_FOUND -*/ -int p2pproxy_resourcemgt_lookup_sip_proxy(char* proxy_uri,size_t size, const char* domain) ; -/** -* access a media ressource addresses for a given domaine name -* @param [out] p2pproxy_resourcemgt_resource_list_t allocated by the user (size = 0) -* @param [in] domaine name -* @return status code P2PPROXY_NO_ERROR, P2PPROXY_ERROR_RESOURCELOCATOR_SERVER_NOT_FOUND -*/ -int p2pproxy_resourcemgt_lookup_media_resource(p2pproxy_resourcemgt_resource_list_t* resource_list, const char* domain) ; -/* - * notify the library at a given proxy is no longuer reachable -* @param [in] proxy sip uri -* @return status code P2PPROXY_NO_ERROR -*/ -int p2pproxy_resourcemgt_revoke_sip_proxy(const char* proxy_uri); - -/* - * notify the library at a given Media resoure is no longuer reachable -* @param [in] media resource uri (udp://hostname:port) -* @return status code P2PPROXY_NO_ERROR -*/ -int p2pproxy_resourcemgt_revoke_media_resource(const char* resource_uri); - -#endif /*SWIG*/ - -#endif /*P2PPROXY_LAUNCHER_H_*/ diff --git a/p2pproxy/log4j.properties b/p2pproxy/log4j.properties deleted file mode 100644 index 43ab871a..00000000 --- a/p2pproxy/log4j.properties +++ /dev/null @@ -1,82 +0,0 @@ -### Configuration file for log4j. For more details, see log4j's site: -### -### http://jakarta.apache.org/log4j/ - -### Set root loger level and its appender -log4j.rootLogger=ERROR, A1, R - -### Create an appender named A1 to log to console -log4j.appender.A1=org.apache.log4j.ConsoleAppender -log4j.appender.A1.Target=System.out -#log4j.appender.A1.Threshold=WARN -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -## the following conversion pattern produces: -## connectToRendezVous -log4j.appender.A1.layout.ConversionPattern=<%-5p %d{ISO8601} %c{1}::%M:%L> %x %m\n - -log4j.appender.R.Threshold=TRACE -log4j.appender.R=org.apache.log4j.RollingFileAppender -log4j.appender.R.File=${org.linphone.p2pproxy.home}/logs/p2pproxy.log -log4j.appender.R.MaxFileSize=1000KB -# Keep one backup file -log4j.appender.R.MaxBackupIndex=1 -log4j.appender.R.layout=org.apache.log4j.PatternLayout -log4j.appender.R.layout.ConversionPattern=<%-5p %d{ISO8601} %c{1}::%M:%L> %x %m\n - - -#java.util.logging -handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler -java.util.logging.FileHandler.limit = 50000 -java.util.logging.FileHandler.count = 1 -java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter - -# Limit the message that are printed on the console to INFO and above -java.util.logging.ConsoleHandler.level = FINEST -java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter -# Facility specific properties. -# Provides extra control for each logger. -# -# For example, set the net.jxta.impi.pipe.PipeResolver logger to only log SEVERE -# messages: -#net.jxta.level = FINEST - - -#net.jxta.impl.peergroup.AutomaticConfigurator.level=INFO -#net.jxta.impl.peergroup.ConfigDialog.level=INFO -#net.jxta.impl.peergroup.DefaultConfigurator.level=INFO -#net.jxta.impl.peergroup.NullConfigurator.level=INFO - -### per-package filtering examples: - #net.jxta.level=WARN -# net.jxta.impl.peergroup.level=INFO -#net.jxta.impl.rendezvous.edge.level=FINEST -# net.jxta.impl.endpoint.relay.level=FINEST -#net.jxta.impl.endpoint.WireFormatMessageBinary.level=FINEST -#net.jxta.impl.discovery.level=FINEST -#net.jxta.impl.cm.level=FINEST -# net.jxta.impl.resolver.level=FINEST -# net.jxta.impl.endpoint.level=FINEST -# net.jxta.impl.endpoint.relay.level=FINEST -#net.jxta.impl.endpoint.relay.RelayClient.level=FINEST - #net.jxta.impl.endpoint.tcp.level=FINEST -#net.jxta.impl.endpoint.servlethttp.level=INFO -#net.jxta.impl.endpoint.servlethttp.HttpClientMessenger.level=FINEST -# net.jxta.impl.endpoint.router.EndpointRouter.level=WARNING -# net.jxta.impl.endpoint.EndpointServiceImpl.level=FINEST - #net.jxta.impl.pipe.level=FINEST -#net.jxta.socket.level=FINEST -#net.jxta.impl.util.pipe.reliable.level=FINEST -#net.jxta.impl.util.RdvAdvSeedingManager.level=FINEST - -#net.jxta.impl.endpoint.router.level=INFO -#net.jxta.platform.level=FINEST - -log4j.logger.org.linphone.p2pproxy=INFO -#log4j.logger.net.jxta.impl.rendezvous.rpv=WARN -log4j.logger.org.linphone.p2pproxy.core.JxtaNetworkManager=DEBUG -log4j.logger.org.linphone.p2pproxy.core.P2pProxyAccountManagementImpl=DEBUG - -log4j.logger.org.linphone.p2pproxy.api.P2pProxyInstance=INFO -#log4j.logger.org.linphone.p2pproxy.test.utils=INFO -log4j.logger.org.linphone.p2pproxy.test=DEBUG -#log4j.logger.org.linphone.p2pproxy.core.rdvautoconfig=DEBUG diff --git a/p2pproxy/plugin-src/Makefile.am b/p2pproxy/plugin-src/Makefile.am deleted file mode 100644 index 5b8495a2..00000000 --- a/p2pproxy/plugin-src/Makefile.am +++ /dev/null @@ -1,19 +0,0 @@ -#plugin to enable fonis into linphone - -JAVA_LDFLAGS=\ - -Wl,-rpath,$(javadir)/jre/lib/amd64 -Wl,-rpath,$(javadir)/jre/lib/i386 \ - -Wl,-rpath,$(javadir)/jre/lib/amd64/server -Wl,-rpath,$(javadir)/jre/lib/i386/server - -pluginsdir=$(LINPHONE_PLUGINS_DIR) - -plugins_LTLIBRARIES=libfonisprovider.la - -libfonisprovider_la_SOURCES=fonis.c - -libfonisprovider_la_LIBADD=$(top_builddir)/launcher/src/libfonisc.la - -libfonisprovider_la_LDFLAGS=$(JAVA_LDFLAGS) - -AM_CFLAGS= $(LIBLINPHONE_CFLAGS) - -INCLUDES=-I$(top_srcdir)/launcher/src \ No newline at end of file diff --git a/p2pproxy/plugin-src/fonis.c b/p2pproxy/plugin-src/fonis.c deleted file mode 100644 index 7faccef9..00000000 --- a/p2pproxy/plugin-src/fonis.c +++ /dev/null @@ -1,178 +0,0 @@ -/* -linphone -Copyright (C) 2000 Simon MORLAT (simon.morlat@linphone.org) - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ - - -#include "linphonecore.h" - -#include "p2pproxy.h" - -typedef struct _FonisContext{ - int toto; -}FonisContext; - -static ms_thread_t fonis_thread; - - -static void *fonis_thread_func(void *arg){ - char *argv[]={"-edge-only","-sip", "5058",NULL}; - if (p2pproxy_application_start(3,argv)!=0){ - ms_error("Fail to start fonis thread !"); - } - return NULL; -} - -static bool_t fonis_init(void){ - static bool_t initd=FALSE; - if (!initd){ - ms_thread_create(&fonis_thread,NULL,fonis_thread_func,NULL); - initd=TRUE; - while( p2pproxy_application_get_state()==P2PPROXY_ERROR_APPLICATION_NOT_STARTED){ - usleep(200000); - ms_message("Waiting for p2pproxy to start"); - } - } - return TRUE; -} - -static bool_t fonis_check_connected(SipSetupContext *ctx){ - int retries; - LinphoneCore *lc=linphone_proxy_config_get_core(sip_setup_context_get_proxy_config(ctx)); - for(retries=0;retries<1200;retries++){ - if (p2pproxy_application_get_state()==P2PPROXY_CONNECTED){ - if (retries>0) linphone_core_stop_waiting(lc); - return TRUE; - } - if (retries==0){ - ms_message("Waiting for p2pproxy to connect to the network..."); - linphone_core_start_waiting(lc,"Trying to connect to the fonis network..."); - }else linphone_core_update_progress(lc,NULL,-1); - } - linphone_core_stop_waiting(lc); - return FALSE; -} - -static int fonis_test_account(SipSetupContext *ctx, const char *uri){ - int ret; - LinphoneCore *lc=linphone_proxy_config_get_core(sip_setup_context_get_proxy_config(ctx)); - if (!fonis_check_connected(ctx)) return -1; - linphone_core_start_waiting(lc,"Checking..."); - ret=(p2pproxy_accountmgt_isValidAccount(uri)==P2PPROXY_ACCOUNTMGT_USER_EXIST) ? 1 : 0; - linphone_core_update_progress(lc,NULL,1); - linphone_core_stop_waiting(lc); - return ret; -} - -static int fonis_create_account(SipSetupContext *ctx, const char *uri, const char *passwd){ - int err; - LinphoneCore *lc=linphone_proxy_config_get_core(sip_setup_context_get_proxy_config(ctx)); - if (!fonis_check_connected(ctx)) return -1; - linphone_core_start_waiting(lc,"Creating account..."); - err=p2pproxy_accountmgt_createAccount(uri); - ms_message("Account creation result for %s: %i",uri,err); - linphone_core_update_progress(lc,NULL,1); - linphone_core_stop_waiting(lc); - if (err<0) return -1; - return 0; -} - -static int fonis_login_account(SipSetupContext * ctx,const char *uri, const char *passwd){ - if (!fonis_check_connected(ctx)) return -1; - if (p2pproxy_accountmgt_isValidAccount(uri)==P2PPROXY_ACCOUNTMGT_USER_EXIST) { - return 0; - } - else return -1; -} - -static int fonis_get_proxy(SipSetupContext *ctx, const char *domain, char *proxy, size_t sz){ - int err; - if (!fonis_check_connected(ctx)) return -1; - err=p2pproxy_resourcemgt_lookup_sip_proxy(proxy,sz,(char*)domain); - if (err==0) return 0; - else return -1; -} - -static int fonis_get_stun_servers(SipSetupContext *ctx, char *stun1, char *stun2, size_t size){ - FonisContext *fc=(FonisContext*)ctx->data; - int ret=-1; - p2pproxy_resourcemgt_resource_list_t* l=p2pproxy_resourcemgt_new_resource_list(); - if (p2pproxy_resourcemgt_lookup_media_resource(l,ctx->domain)==0){ - if (l->size>0) strncpy(stun1,l->resource_uri[0],size); - if (l->size>1) strncpy(stun2,l->resource_uri[1],size); - ret=0; - } - p2pproxy_resourcemgt_delete_resource_list(l); - return ret; -} - -static int fonis_get_relay(SipSetupContext *ctx, char *relay, size_t size){ - FonisContext *fc=(FonisContext*)ctx->data; - int ret=-1; - p2pproxy_resourcemgt_resource_list_t* l=p2pproxy_resourcemgt_new_resource_list(); - if (p2pproxy_resourcemgt_lookup_media_resource(l,ctx->domain)==0){ - if (l->size>0) strncpy(relay,l->resource_uri[0],size); - ret=0; - } - p2pproxy_resourcemgt_delete_resource_list(l); - return ret; -} - -static void fonis_exit(){ - p2pproxy_application_stop(); -} - -static const char *fonis_get_notice(SipSetupContext *ssctx){ - return "WARNING: experimental feature !" -"FONIS stands for Free Overlay Network for Instant SIP.\n" -"Based on SIP and Peer to Peer technologies, it allows people to find each other through the help of a virtual network." -"Once you and your friends are registered, you'll be able to call each other simply by entering your friend's username in " -"linphone's sip uri box." -"Read more information about FONIS at http://www.fonis.org"; -} - -static const char *fonis_domains[]={ - "p2p.linphone.org", - NULL -}; - -static const char ** fonis_get_domains(SipSetupContext *ssctx){ - return fonis_domains; -} - - - -static SipSetup fonis_sip_setup={ - .capabilities=SIP_SETUP_CAP_PROXY_PROVIDER|SIP_SETUP_CAP_STUN_PROVIDER| - SIP_SETUP_CAP_RELAY_PROVIDER|SIP_SETUP_CAP_ACCOUNT_MANAGER, - .name="fonis", - .init=fonis_init, - .account_exists=fonis_test_account, - .create_account=fonis_create_account, - .login_account=fonis_login_account, - .get_proxy=fonis_get_proxy, - .get_stun_servers=fonis_get_stun_servers, - .get_relay=fonis_get_relay, - .exit=fonis_exit, - .get_notice=fonis_get_notice, - .get_domains=fonis_get_domains -}; - -void libfonisprovider_init(void){ - sip_setup_register(&fonis_sip_setup); -} - diff --git a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyException.java b/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyException.java deleted file mode 100644 index 15a02309..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyException.java +++ /dev/null @@ -1,45 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -P2pProxyException.java -Generic purpose Exception for P2pProxyMain. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.api; - -@SuppressWarnings("serial") -public class P2pProxyException extends Exception { - - public P2pProxyException() { - super(); - // TODO Auto-generated constructor stub - } - - public P2pProxyException(String arg0, Throwable arg1) { - super(arg0, arg1); - // TODO Auto-generated constructor stub - } - - public P2pProxyException(String arg0) { - super(arg0); - // TODO Auto-generated constructor stub - } - - public P2pProxyException(Throwable arg0) { - super(arg0); - // TODO Auto-generated constructor stub - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyInstance.java b/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyInstance.java deleted file mode 100644 index f325156b..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyInstance.java +++ /dev/null @@ -1,76 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -P2pProxyInstance.java -- - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.api; - -import org.zoolu.sip.provider.SipProvider; - -public interface P2pProxyInstance { - public static int BASE_HTTP = 30700; - public static int BASE_TCP = 9701; - - public enum Mode {relay, edge, auto,seeding_server}; - /** - * @return Returns the Mode. - */ - public abstract Mode getMode(); - - /** - * @param aModet. - */ - public abstract void setMode(Mode aMode); - - /** - * @return Returns the mIndex. - */ - public abstract int getIndex(); - - /** - * @param index The mIndex to set. - */ - public abstract void setIndex(int index); - - public abstract void start() throws Exception; - public abstract void stop() throws Exception; - - public abstract boolean isStarted() throws P2pProxyException; - - public abstract SipProvider getSipClientProvider(); - - public abstract String getSipClientName(); - - public int getNumberOfconnectedPeers(); - - public Object getOpaqueNetworkManager(); - - public void setPrivateHostAdress(String anAddress); - - public void setPublicHostAdress(String anAddress); - - public abstract P2pProxyNetworkProbe getManager(); - - public abstract P2pProxyRtpRelayManagement getRtpRelayManager(); - - public void setRelayCapacity(int aCapacity); - - public void setProperty(String key,String value) throws P2pProxyException; - - public int getAdvertisementDiscoveryTimeout(); - -} \ No newline at end of file diff --git a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyManagement.java b/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyManagement.java deleted file mode 100644 index 2ebeb322..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyManagement.java +++ /dev/null @@ -1,33 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyManagement.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.api; - - -public interface P2pProxyManagement extends P2pProxyNetworkProbe,P2pProxyResourceManagement { - - /** - * test if according both to local peer capabilities and supeer peer election polity this peer should become a super peer - * - * @return - */ - public boolean shouldIBehaveAsAnRdv() throws P2pProxyException; - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyNetworkProbe.java b/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyNetworkProbe.java deleted file mode 100644 index c2732430..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyNetworkProbe.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - p2pproxy - Copyright (C) 2007 Jehan Monnier () - - P2pProxyNetworkProbe.java - . - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.api; - -import java.net.InetAddress; -import java.net.InetSocketAddress; - - - - -public interface P2pProxyNetworkProbe { - public enum Protocol {tcp,udp}; - /** - * request the rdv server for the edge IP address - * @return - * @throws P2pProxyException - */ - public abstract InetAddress getPublicIpAddress() throws P2pProxyException; - - /** - * Ask the network to test if the given ip,port, protocol is reachable from the network - * @param aSocketAddress - * @param aProtocol - * @return true if reachable - * @throws P2pProxyException - */ - public abstract boolean probeSocket(InetSocketAddress aSocketAddress, - Protocol aProtocol) throws P2pProxyException; - -} \ No newline at end of file diff --git a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyNotReadyException.java b/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyNotReadyException.java deleted file mode 100644 index 6ec39cc8..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyNotReadyException.java +++ /dev/null @@ -1,55 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyUserNotFoundException.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.api; - - -@SuppressWarnings("serial") -public class P2pProxyNotReadyException extends P2pProxyException { - - /** - * - */ - public P2pProxyNotReadyException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public P2pProxyNotReadyException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public P2pProxyNotReadyException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public P2pProxyNotReadyException(Throwable arg0) { - super(arg0); - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyResourceManagement.java b/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyResourceManagement.java deleted file mode 100644 index d8159d6c..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyResourceManagement.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -P2pProxySipProxyRegistrarManagement.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.api; - - - -public interface P2pProxyResourceManagement { - public final String DOMAINE="p2p.linphone.org"; - /** - * - * @return the SIP uris of an available sip proxy registrar for a given domaine - */ - public String[] lookupSipProxiesUri(String aDomaine) throws P2pProxyException ; - - public void revokeSipProxy(String aProxy) throws P2pProxyException; - - public void revokeMediaServer(String aMediaServer) throws P2pProxyException; - /** - * return 2 adresses where to contact media server (stun/rtprelay) - */ - public String[] getMediaServerList() throws P2pProxyException; - - - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyRtpRelayManagement.java b/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyRtpRelayManagement.java deleted file mode 100644 index d2ee5b5a..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyRtpRelayManagement.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.linphone.p2pproxy.api; - -import java.net.InetSocketAddress; -import java.util.Map; - -import org.linphone.p2pproxy.core.media.rtprelay.MediaType; - -public interface P2pProxyRtpRelayManagement { - - /** - * - * @param aSource get list Socket address available for relay - */ - public Map getAddresses() throws P2pProxyException ; -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyUserAlreadyExistException.java b/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyUserAlreadyExistException.java deleted file mode 100644 index e3ba5ac6..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyUserAlreadyExistException.java +++ /dev/null @@ -1,58 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyUserAlreadyExistException.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.api; - -public class P2pProxyUserAlreadyExistException extends Exception { - - /** - * - */ - public P2pProxyUserAlreadyExistException() { - super(); - // TODO Auto-generated constructor stub - } - - /** - * @param arg0 - * @param arg1 - */ - public P2pProxyUserAlreadyExistException(String arg0, Throwable arg1) { - super(arg0, arg1); - // TODO Auto-generated constructor stub - } - - /** - * @param arg0 - */ - public P2pProxyUserAlreadyExistException(String arg0) { - super(arg0); - // TODO Auto-generated constructor stub - } - - /** - * @param arg0 - */ - public P2pProxyUserAlreadyExistException(Throwable arg0) { - super(arg0); - // TODO Auto-generated constructor stub - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyUserNotFoundException.java b/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyUserNotFoundException.java deleted file mode 100644 index f628e00e..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/api/P2pProxyUserNotFoundException.java +++ /dev/null @@ -1,55 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyUserNotFoundException.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.api; - - -@SuppressWarnings("serial") -public class P2pProxyUserNotFoundException extends P2pProxyException { - - /** - * - */ - public P2pProxyUserNotFoundException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public P2pProxyUserNotFoundException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public P2pProxyUserNotFoundException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public P2pProxyUserNotFoundException(Throwable arg0) { - super(arg0); - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/Configurator.java b/p2pproxy/src/org/linphone/p2pproxy/core/Configurator.java deleted file mode 100644 index 56950b0e..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/Configurator.java +++ /dev/null @@ -1,68 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -Configurator.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; -import java.util.InvalidPropertiesFormatException; -import java.util.Properties; -import java.util.Set; - -import org.apache.log4j.Logger; - -@SuppressWarnings("serial") -public class Configurator extends Properties { - private final static Logger mLog = Logger.getLogger(Configurator.class); - private final File mFile; - public Configurator (File aFile) throws InvalidPropertiesFormatException, FileNotFoundException, IOException { - super(); - mFile = aFile; - if (mFile.exists()) { - loadFromXML(new FileInputStream(mFile)); - } - } - /** - * save to disk - * @throws IOException - * @throws FileNotFoundException - */ - public void save() throws FileNotFoundException, IOException { - storeToXML(new FileOutputStream(mFile),new Date().toString()); - } - public Object setProperty(String key,String value) { - Object lReturn = super.setProperty(key, value); - try { - save(); - } catch (Exception e) { - mLog.error("enable to save prop ["+key+"] value ["+value+"]", e); - } - return lReturn; - } - public void serProperties(Properties aProperties) { - for (Object key :aProperties.keySet()){ - setProperty((String)key,aProperties.getProperty((String)key)); - } - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/EdgePeerServiceManager.java b/p2pproxy/src/org/linphone/p2pproxy/core/EdgePeerServiceManager.java deleted file mode 100644 index bc70b5de..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/EdgePeerServiceManager.java +++ /dev/null @@ -1,61 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -EdgePeerServiceManager.java - EdgePeer Service Manager. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - - -import java.net.SocketException; -import java.net.UnknownHostException; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.rdvautoconfig.AutoConfigService; - -// Referenced classes of package org.linphone.p2pproxy.core: -// ServiceProvider, JxtaNetworkManager, Configurator - -public class EdgePeerServiceManager extends P2pProxyManagementImpl -{ - private final AutoConfigService mAutoConfigService; - private final static Logger mLog = Logger.getLogger(EdgePeerServiceManager.class); - EdgePeerServiceManager(Configurator aConfigurator, JxtaNetworkManager aJxtaNetworkManager)throws SocketException, UnknownHostException - { - super(aConfigurator,aJxtaNetworkManager); - mAutoConfigService = new AutoConfigService(mConfigurator,mJxtaNetworkManager,this); - } - - public void start(long aTimeout) throws P2pProxyException - { - super.start(aTimeout); - mAutoConfigService.start(aTimeout); - } - - public void stop() { - super.stop(); - mAutoConfigService.stop(); - mLog.info("EdgePeerServiceManager stopped"); - } - - - public boolean shouldIBehaveAsAnRdv() throws P2pProxyException{ - return mAutoConfigService.canIBehaveAsASuperPeer(); - } - - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/GenericService.java b/p2pproxy/src/org/linphone/p2pproxy/core/GenericService.java deleted file mode 100644 index 186cd29b..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/GenericService.java +++ /dev/null @@ -1,157 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -RtpRelayService.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - -import java.io.IOException; -import java.net.Socket; -import java.net.URI; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.id.IDFactory; - -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleClassAdvertisement; -import net.jxta.protocol.ModuleSpecAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.socket.JxtaServerSocket; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; - - -public class GenericService implements Runnable,ServiceProvider { - public interface ServiceSocketHandlerFactory { - - public Runnable create(Socket aSocket) ; - - } - private final JxtaNetworkManager mJxtaNetworkManager; - private final Configurator mProperties; - private final String SERVICE_PIPE_ID; - private final static Logger mLog = Logger.getLogger(GenericService.class); - private final String ADV_NAME ; - private final String MODULE_CLASS_ID; - private final String MODULE_SPEC_ID; - private JxtaServerSocket mJxtaServerSocket; - private final String mServiceName; - private Thread mSocketServerThread ; - private final ExecutorService mPool; - private final ServiceSocketHandlerFactory mServiceSocketHandlerFactory; - private boolean mExist = false; - - public GenericService(Configurator lProperties,JxtaNetworkManager aJxtaNetworkManager,String aServiceName,ServiceSocketHandlerFactory aServiceSocketHandlerFactory) { - mJxtaNetworkManager = aJxtaNetworkManager; - mProperties = lProperties; - mServiceName = aServiceName.trim(); - SERVICE_PIPE_ID="org.linphone.p2pproxy."+mServiceName+".bidi-pipe.id"; - ADV_NAME = "JXTASPEC:LINPHONE-"+mServiceName; - MODULE_CLASS_ID="org.linphone.p2pproxy."+mServiceName+"Service.module-class.id"; - MODULE_SPEC_ID="org.linphone.p2pproxy."+mServiceName+"Service.module-spec.id"; - mSocketServerThread = new Thread(this,mServiceName+"Service server thread"); - mPool = Executors.newCachedThreadPool(); - mServiceSocketHandlerFactory = aServiceSocketHandlerFactory; - } - - public void start(long l) throws P2pProxyException { - try { - mLog.info("Start the RtpRelayService daemon"); - ModuleClassAdvertisement lModuleAdvertisement = (ModuleClassAdvertisement) AdvertisementFactory.newAdvertisement(ModuleClassAdvertisement.getAdvertisementType()); - - lModuleAdvertisement.setName("JXTAMOD:LINPHONE-"+mServiceName); - lModuleAdvertisement.setDescription("Service to provide " +mServiceName); - - ModuleClassID lModuleClassID; - // to avoid ID creation at each start - if (mProperties.getProperty(MODULE_CLASS_ID) == null) { - lModuleClassID = IDFactory.newModuleClassID(); - mProperties.setProperty(MODULE_CLASS_ID, lModuleClassID.toURI().toString()); - } else { - lModuleClassID = (ModuleClassID) IDFactory.fromURI(URI.create(mProperties.getProperty(MODULE_CLASS_ID))); - } - lModuleAdvertisement.setModuleClassID(lModuleClassID); - - // publish local only - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().publish(lModuleAdvertisement); - - ModuleSpecAdvertisement lModuleSpecAdvertisement = (ModuleSpecAdvertisement)AdvertisementFactory.newAdvertisement(ModuleSpecAdvertisement.getAdvertisementType()); - lModuleSpecAdvertisement.setName(ADV_NAME); - lModuleSpecAdvertisement.setVersion("Version 1.0"); - lModuleSpecAdvertisement.setCreator("linphone.org"); - // to avoid ID creation at each start - ModuleSpecID lModuleSpecId; - if (mProperties.getProperty(MODULE_SPEC_ID) == null) { - lModuleSpecId = IDFactory.newModuleSpecID(lModuleClassID); - mProperties.setProperty(MODULE_SPEC_ID, lModuleSpecId.toURI().toString()); - } else { - lModuleSpecId = (ModuleSpecID) IDFactory.fromURI(URI.create(mProperties.getProperty(MODULE_SPEC_ID))); - } - lModuleSpecAdvertisement.setModuleSpecID(lModuleSpecId); - lModuleSpecAdvertisement.setSpecURI("http://www.linphone.org/"+mServiceName.toLowerCase()); - - PipeAdvertisement lSocketAdvertisement = mJxtaNetworkManager.createPipeAdvertisement(SERVICE_PIPE_ID, mServiceName.toLowerCase()); - - lModuleSpecAdvertisement.setPipeAdvertisement(lSocketAdvertisement); - mJxtaServerSocket = new JxtaServerSocket(mJxtaNetworkManager.getPeerGroup(), lSocketAdvertisement, 10); - mJxtaServerSocket.setSoTimeout(0); - mSocketServerThread.start(); - //publish local only - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().publish(lModuleSpecAdvertisement); - mLog.info("Adv ["+lModuleSpecAdvertisement+"] published"); - } - catch(Exception e) - { - mLog.error("socket instance error", e); - } - } - public void stop(){ - try { - mJxtaServerSocket.close(); - } catch (IOException e) { - //nop - } - mExist = true; - } - public void run() { - while (mExist) { - try { - mLog.info("Waiting for connection on service ["+ADV_NAME+"]"); - Socket lSocket = mJxtaServerSocket.accept(); - // set reliable - if (lSocket != null) { - mLog.info("socket created"); - mPool.execute(mServiceSocketHandlerFactory.create(lSocket)); - } - } catch (Exception e) { - mLog.error("Server socket error",e); - } - } - - } - - /** - * @return Returns the aDV_NAME. - */ - public String getAdvName() { - return ADV_NAME; - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/GenericServiceClient.java b/p2pproxy/src/org/linphone/p2pproxy/core/GenericServiceClient.java deleted file mode 100644 index 21b7698d..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/GenericServiceClient.java +++ /dev/null @@ -1,121 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -PeerInfoServiceClient.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.SocketAddress; -import java.net.SocketTimeoutException; -import java.util.List; - -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.protocol.ModuleSpecAdvertisement; -import net.jxta.socket.JxtaSocket; -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyNetworkProbe; -import org.linphone.p2pproxy.core.Configurator; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.ServiceProvider; -import org.linphone.p2pproxy.core.JxtaNetworkManager.Mode; - - -public abstract class GenericServiceClient implements ServiceProvider{ - protected final JxtaNetworkManager mJxtaNetworkManager; - private final Configurator mProperties; - private final static Logger mLog = Logger.getLogger(GenericServiceClient.class); - protected JxtaSocket mJxtaSocket; - protected ObjectOutputStream mOut; - protected ObjectInputStream mIn; - boolean mStarted = false; - protected final int mSoTimout; - private final String mAdvertisementName; - - public GenericServiceClient(Configurator lProperties,JxtaNetworkManager aJxtaNetworkManager,String aAdvertisementName) { - mJxtaNetworkManager = aJxtaNetworkManager; - mProperties = lProperties; - mSoTimout = Integer.parseInt(lProperties.getProperty(JxtaNetworkManager.SO_TIMEOUT, "10000")); - mAdvertisementName = aAdvertisementName; - } - - public void start(long aTimeOut) throws P2pProxyException { - // 1 check if connected to a rdv - try { - - mStarted = true; - mLog.info(mAdvertisementName+" client started"); - } - catch(Exception e) { - throw new P2pProxyException(e); - } - - } - - - public void stop() { - try { - checkObject(); - mIn.close(); - mOut.close(); - mJxtaSocket.close(); - }catch (Exception e ) { - mLog.error("cannot "+mAdvertisementName+" client" , e); - } - mLog.info(mAdvertisementName+" client stopped"); - } - - protected void checkSocketConnection() throws IOException, P2pProxyException, InterruptedException { - //wo because close not sent - if (mJxtaSocket != null) mJxtaSocket.close(); - - if (mJxtaSocket == null ||mJxtaSocket.isClosed() || mJxtaSocket.isBound() == false) { - try { - mLog.info("Opening socket for ["+mAdvertisementName+"]"); - // try from local - mJxtaSocket = mJxtaNetworkManager.openSocket(null, mAdvertisementName, mSoTimout,true); - } catch (P2pProxyException e) { - //last chance - mLog.warn("cannot open socket ["+mAdvertisementName+"], trying from remote",e); - mJxtaSocket = mJxtaNetworkManager.openSocket(null, mAdvertisementName, mSoTimout,false); - } - if (mJxtaSocket == null) throw new P2pProxyException("Cannot start"+mAdvertisementName+" client because cannot bind jxta socket"); - mOut = new ObjectOutputStream(mJxtaSocket.getOutputStream()); - mIn = new ObjectInputStream(mJxtaSocket.getInputStream()); - //just to work-around socket establishment - mIn.readBoolean(); - } - - } - - protected void checkObject() throws P2pProxyException{ - if(!mStarted) throw new P2pProxyException(mAdvertisementName+" client not started"); - } - - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/GenericUdpSession.java b/p2pproxy/src/org/linphone/p2pproxy/core/GenericUdpSession.java deleted file mode 100644 index f5fab0ac..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/GenericUdpSession.java +++ /dev/null @@ -1,89 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -GenericUdpSession.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetSocketAddress; - -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - - - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.core.media.jxtaudpproxy.UdpSession; - -public class GenericUdpSession implements Runnable { - public interface MessageHandler { - public void onMessage(DatagramPacket lMessage); - } - private final static Logger mLog = Logger.getLogger(UdpSession.class); - private final DatagramSocket mLocalSocket; - private final Thread mLocalSocketThread; - - private final List mMessageHandlerList = new ArrayList(); - private boolean mExit = false; - public GenericUdpSession(InetSocketAddress aSocketAddress) throws SocketException, UnknownHostException { - mLocalSocket = new DatagramSocket(aSocketAddress); - mLocalSocketThread = new Thread(this,"udp session rtp ["+aSocketAddress+"]"); - mLocalSocketThread.start(); - } - public GenericUdpSession(InetSocketAddress aSocketAddress,MessageHandler aMessageHandler) throws SocketException, UnknownHostException { - this(aSocketAddress); - mMessageHandlerList.add(aMessageHandler); - } - public void run() { - - while (mExit != true) { - try { - byte[] lBuff = new byte[1500]; - DatagramPacket lDatagramPacket = new DatagramPacket(lBuff,lBuff.length); - mLocalSocket.receive(lDatagramPacket); - if (mLog.isInfoEnabled()) mLog.info(mLocalSocket.getLocalAddress().getHostAddress() + ":" + mLocalSocket.getLocalPort() + " datagram received from " + lDatagramPacket.getAddress().getHostAddress() + ":" + lDatagramPacket.getPort()); - for (MessageHandler lmMessageHandlerList : mMessageHandlerList) { - lmMessageHandlerList.onMessage(lDatagramPacket); - } - - }catch(Exception e) { - //nop - } - } - mLog.info("exit from thread ["+mLocalSocketThread+"]"); - - } - - public void close() { - mExit = true; - mLocalSocket.close(); - } - - public DatagramSocket getSocket() { - return mLocalSocket; - } - public void addMessageHandler(MessageHandler aMessageHandler) { - mMessageHandlerList.add(aMessageHandler); - } - - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/JxtaNetworkManager.java b/p2pproxy/src/org/linphone/p2pproxy/core/JxtaNetworkManager.java deleted file mode 100644 index 351fc9ce..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/JxtaNetworkManager.java +++ /dev/null @@ -1,411 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -JxtaNetworkManager.java -- connection to a jxta network. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - -import java.io.File; -import java.io.IOException; -import java.net.InetAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; - -import java.util.Enumeration; -import java.util.List; -import java.util.Properties; -import java.util.StringTokenizer; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -import javax.security.cert.CertificateException; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.sipproxy.NetworkResourceAdvertisement; -import org.linphone.p2pproxy.core.sipproxy.superpeers.P2pUserRegistrationAdvertisement; - - - -import net.jxta.discovery.DiscoveryEvent; -import net.jxta.discovery.DiscoveryListener; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.exception.JxtaException; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; -import net.jxta.peer.PeerID; -import net.jxta.peergroup.NetPeerGroupFactory; -import net.jxta.peergroup.PeerGroup; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.pipe.InputPipe; -import net.jxta.pipe.PipeID; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.pipe.PipeService; -import net.jxta.platform.NetworkConfigurator; -import net.jxta.protocol.ConfigParams; -import net.jxta.protocol.DiscoveryResponseMsg; -import net.jxta.protocol.ModuleSpecAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.rendezvous.RendezVousService; -import net.jxta.socket.JxtaSocket; - - -public class JxtaNetworkManager { - public enum Mode {relay, edge, auto,seeding_server}; - private PeerGroup mNetworkPeerGroup; - private RendezVousService mRendezVousService; - private final static Logger mLog = Logger.getLogger(JxtaNetworkManager.class); - public final static String RDV_CONNECT_TIMEOUT="org.linphone.p2pproxy.JxtaNetworkManager.rdv-connect.timout"; - public final static String ADV_DISCOVERY_TIMEOUT="org.linphone.p2pproxy.JxtaNetworkManager.adv-discovery.timout"; - public final static String MODE="org.linphone.p2pproxy.JxtaNetworkManager.mode"; - public final static String RELAY_CAPACITY="org.linphone.p2pproxy.JxtaNetworkManager.relay-capacity"; - public final static String SEEDING_RDV="org.linphone.p2pproxy.JxtaNetworkManager.seeding-rdv.url"; - public final static String SEEDING_RELAY="org.linphone.p2pproxy.JxtaNetworkManager.seeding-relay.url"; - public final static String TCP_LISTENING_PORT="org.linphone.p2pproxy.JxtaNetworkManager.tcp.port"; - public final static String HTTP_LISTENING_PORT="org.linphone.p2pproxy.JxtaNetworkManager.http.port"; - public final static String HTTP_LISTENING_PUBLIC_ADDRESS="org.linphone.p2pproxy.JxtaNetworkManager.http.listening.public.address"; - public final static String TCP_LISTENING_PUBLIC_ADDRESS="org.linphone.p2pproxy.JxtaNetworkManager.tcp.listening.public.address"; - public final static String SEEDING_RDV_URL="org.linphone.p2pproxy.JxtaNetworkManager.seeding-rdv.url-location"; - public final static String SEEDING_RELAY_URL="org.linphone.p2pproxy.JxtaNetworkManager.seeding-relay.url-location"; - - public final static String SO_TIMEOUT="org.linphone.p2pproxy.so-timout"; - public final static String ENABLE_HTTP_CLIENT="org.linphone.p2pproxy.JxtaNetworkManager.http.client.enable"; - public static int EDGE_MODE = NetworkConfigurator.TCP_CLIENT| NetworkConfigurator.RDV_CLIENT | NetworkConfigurator.RELAY_CLIENT; - public static int SUPER_PEER_MODE = NetworkConfigurator.RDV_RELAY_PROXY_NODE; - final private Properties mProperties; - private Mode mMode; - public static int ADV_DISCOVERY_TIMEOUT_INT = 15000; - static { - System.setProperty("net.jxta.impl.cm.index.rebuild", "true"); - } - /** - * @return Returns the mMode. - */ - public Mode getMode() { - return mMode; - } - /** - * Create a jxta connection from a given config directory - * and connect to a rendez vous perr - * @param aConfigDir a jxta config dir - * @param aRdvConnectionTimout time in ms to wait until a succesfull connection to a rdv peer - * @throws JxtaException - * @throws InterruptedException - * @throws P2pProxyException - * @throws IOException - * @throws URISyntaxException - * @throws CertificateException - */ - public JxtaNetworkManager(Configurator aProperties,File aConfigDir) throws JxtaException, InterruptedException, P2pProxyException, IOException, URISyntaxException, CertificateException { - super(); - // get configuration - //System.setProperty("JXTA_HOME", aConfigDir.getAbsolutePath()); - - NetworkConfigurator lNetworkConfigurator; - mProperties = aProperties; - // set mode - mMode = Mode.valueOf(aProperties.getProperty(MODE, Mode.edge.name())); - int lMode; - if (mMode == Mode.relay || mMode == Mode.seeding_server) { - lMode = SUPER_PEER_MODE; - } else { - lMode = EDGE_MODE; - } - if (aProperties.getProperty(ENABLE_HTTP_CLIENT) != null && Boolean.parseBoolean(aProperties.getProperty(ENABLE_HTTP_CLIENT)) == true) { - lMode = lMode | NetworkConfigurator.HTTP_CLIENT; - } - - lNetworkConfigurator = new NetworkConfigurator(lMode,aConfigDir.toURI()); - - if (!lNetworkConfigurator.exists()) { - lNetworkConfigurator.setPeerID(IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID)); - lNetworkConfigurator.setName(InetAddress.getLocalHost().toString()+" "+aProperties.getProperty(TCP_LISTENING_PORT)); - lNetworkConfigurator.setDescription("p2p proxy instance"); - lNetworkConfigurator.save(); - } else { - lNetworkConfigurator.load(); - } - //mode is alway taken from start line - lNetworkConfigurator.setMode(lMode); - // set sedding host - if (aProperties.getProperty(SEEDING_RDV) != null) { - StringTokenizer lSeedingRdvList = new StringTokenizer(aProperties.getProperty(SEEDING_RDV),"|" ); - while (lSeedingRdvList.hasMoreTokens()) { - lNetworkConfigurator.addSeedRendezvous(new URI(lSeedingRdvList.nextToken())); - } - } - if (aProperties.getProperty(SEEDING_RELAY) != null) { - StringTokenizer lSeedingRelayList = new StringTokenizer(aProperties.getProperty(SEEDING_RELAY),"|" ); - while (lSeedingRelayList.hasMoreTokens()) { - lNetworkConfigurator.addSeedRelay(new URI(lSeedingRelayList.nextToken())); - } - } - - - if (aProperties.getProperty(SEEDING_RDV_URL) != null) { - StringTokenizer lSeedingRdvList = new StringTokenizer(aProperties.getProperty(SEEDING_RDV_URL),"|" ); - while (lSeedingRdvList.hasMoreTokens()) { - lNetworkConfigurator.addRdvSeedingURI(new URI(lSeedingRdvList.nextToken())); - } - } else { - lNetworkConfigurator.addRdvSeedingURI("http://seeding.fonis.net/rdv"); - } - if (aProperties.getProperty(SEEDING_RELAY_URL) != null) { - StringTokenizer lSeedingRelayList = new StringTokenizer(aProperties.getProperty(SEEDING_RELAY_URL),"|" ); - while (lSeedingRelayList.hasMoreTokens()) { - lNetworkConfigurator.addRelaySeedingURI(new URI(lSeedingRelayList.nextToken())); - } - } else { - lNetworkConfigurator.addRelaySeedingURI("http://seeding.fonis.net/relay"); - } - - if (aProperties.getProperty(HTTP_LISTENING_PUBLIC_ADDRESS) != null) { - lNetworkConfigurator.setHttpPublicAddress(aProperties.getProperty(HTTP_LISTENING_PUBLIC_ADDRESS), true); - } - - // set listening ports - if (aProperties.getProperty(HTTP_LISTENING_PORT) != null) { - lNetworkConfigurator.setHttpPort(Integer.parseInt(aProperties.getProperty(HTTP_LISTENING_PORT))); - } - - if (aProperties.getProperty(TCP_LISTENING_PUBLIC_ADDRESS) != null) { - lNetworkConfigurator.setTcpPublicAddress(aProperties.getProperty(TCP_LISTENING_PUBLIC_ADDRESS), true); - lNetworkConfigurator.setTcpStartPort(-1); - lNetworkConfigurator.setTcpEndPort(-1); - } - - if (aProperties.getProperty(TCP_LISTENING_PORT) != null) { - lNetworkConfigurator.setTcpPort(Integer.parseInt(aProperties.getProperty(TCP_LISTENING_PORT))); - } - - // connect to rdv - int lRdvConnectionTimout = Integer.parseInt(aProperties.getProperty(RDV_CONNECT_TIMEOUT,"60000")); - init(lNetworkConfigurator,lRdvConnectionTimout,mMode); - - - } - /** - * @param aProperties use to store pipe ID - * @param aNetworkConfigurator jxya native config - * @param aConnectTimout rdv connection timeout - * @throws JxtaException - * @throws InterruptedException - * @throws P2pProxyException - * @throws IOException - * @throws URISyntaxException - * @throws CertificateException - */ - public JxtaNetworkManager(Configurator aProperties, NetworkConfigurator aNetworkConfigurator,int aConnectTimout,Mode aMode) throws JxtaException, InterruptedException, P2pProxyException, IOException, URISyntaxException, CertificateException { - mProperties = aProperties; - mMode = aMode; - init(aNetworkConfigurator,aConnectTimout,aMode); - } - private void init(NetworkConfigurator aNetworkConfigurator,int aConnectTimout, Mode aMode) throws JxtaException, InterruptedException, P2pProxyException, IOException, URISyntaxException, CertificateException { - // connect to rdv - if (mProperties.getProperty(ADV_DISCOVERY_TIMEOUT) != null) { - ADV_DISCOVERY_TIMEOUT_INT = Integer.parseInt(mProperties.getProperty(ADV_DISCOVERY_TIMEOUT)); - } - NetPeerGroupFactory lFactory = new NetPeerGroupFactory((ConfigParams) aNetworkConfigurator.getPlatformConfig(),aNetworkConfigurator.getHome().toURI()); - mNetworkPeerGroup = lFactory.getInterface(); - - // The following step is required and only need to be done once, - // without this step the AdvertisementFactory has no means of - // associating an advertisement name space with the proper object - // in this cast the AdvertisementTutorial - AdvertisementFactory.registerAdvertisementInstance(P2pUserProfileAdvertisement.getAdvertisementType(),new P2pUserProfileAdvertisement.Instantiator()); - AdvertisementFactory.registerAdvertisementInstance(P2pUserRegistrationAdvertisement.getAdvertisementType(),new P2pUserRegistrationAdvertisement.Instantiator()); - AdvertisementFactory.registerAdvertisementInstance(NetworkResourceAdvertisement.getAdvertisementType(),new NetworkResourceAdvertisement.Instantiator()); - - mRendezVousService = mNetworkPeerGroup.getRendezVousService(); - mLog.info("Node PeerID ["+mNetworkPeerGroup.getPeerID()+"]"); - if ( aMode == Mode.edge && isConnectedToRendezVous(aConnectTimout) == false) { - throw new P2pProxyException("Cannot connect to rdv in the last "+aConnectTimout+" ms"); - } - mLog.info("jxta info name ["+mNetworkPeerGroup+"] mode ["+aMode+"] "); - - } - public PeerGroup getPeerGroup() { - return mNetworkPeerGroup; - } - - public PipeAdvertisement createPipeAdvertisement(String aPipePropertyName,String aPipeName) throws IOException { - PipeID lpipeID = null; - if (mProperties.getProperty(aPipePropertyName) == null) { - lpipeID = IDFactory.newPipeID(PeerGroupID.defaultNetPeerGroupID); - mProperties.setProperty(aPipePropertyName, lpipeID.toURI().toString()); - - } else { - lpipeID = (PipeID) ID.create(URI.create(mProperties.getProperty(aPipePropertyName))); - } - //create advertisement - PipeAdvertisement lAdvertisement = (PipeAdvertisement)AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType()); - lAdvertisement.setPipeID(lpipeID); - lAdvertisement.setType(PipeService.UnicastType); - lAdvertisement.setName(aPipeName); - mLog.debug("aPipePropertyName pipe:"+lAdvertisement); - return lAdvertisement; - } - - public InputPipe createPipe(PipeAdvertisement aPipeAdvertisement,PipeMsgListener aListener) throws IOException { - //create pipe - return mNetworkPeerGroup.getPipeService().createInputPipe(aPipeAdvertisement, aListener); - } - /** - * @param aPipePropertyName name use to save/load this pipe ID in the configuration file - * @param aPipeName pipe name - * @return - * @throws IOException - */ - public InputPipe createPipe(String aPipePropertyName,String aPipeName,PipeMsgListener aListener) throws IOException { - return createPipe(createPipeAdvertisement(aPipePropertyName,aPipeName),aListener); - } - public Advertisement getAdvertisement(String aPeerId, String anAdvertisementName,boolean isTryFromLocal) throws InterruptedException, IOException, P2pProxyAdvertisementNotFoundException { - return getAdvertisementList(aPeerId, anAdvertisementName,isTryFromLocal).get(0); - } - - /** - * seach advervitisement indexed by attribute "Name" - * @param aPeerId - * @param anAdvertisementName - * @param isTryFromLocal - * @return - * @throws InterruptedException - * @throws IOException - * @throws P2pProxyAdvertisementNotFoundException - */ - public List getAdvertisementList(String aPeerId, String anAdvertisementName,boolean isTryFromLocal) throws InterruptedException, IOException, P2pProxyAdvertisementNotFoundException { - return getAdvertisementList(aPeerId, "Name",anAdvertisementName, isTryFromLocal); - } - - public List getAdvertisementList(String aPeerId, String anAttributeName,String anAttributeValue, boolean isTryFromLocal) throws InterruptedException, IOException, P2pProxyAdvertisementNotFoundException { - return getAdvertisementList(aPeerId, anAttributeName, anAttributeValue, isTryFromLocal, 1); - } - public List getAdvertisementList(String aPeerId, String anAttributeName,String anAttributeValue, boolean isTryFromLocal, int numberOfexpectedAdv) throws InterruptedException, IOException, P2pProxyAdvertisementNotFoundException { - DiscoveryService lDiscoveryService = getPeerGroup().getDiscoveryService(); - final Semaphore lSemaphore = new Semaphore(1-numberOfexpectedAdv); - final List lReturnList = new ArrayList(); - DiscoveryListener lDiscoveryListener = new DiscoveryListener() { - - public void discoveryEvent(DiscoveryEvent event) { - DiscoveryResponseMsg lRes = event.getResponse(); - int lOrigListSize = lReturnList.size(); - enumeration2List(lRes.getAdvertisements(), lReturnList); - lSemaphore.release(lReturnList.size()-lOrigListSize); - } - - }; - if (isTryFromLocal == true) { - mLog.info("looking for advertisement indexing with ["+ anAttributeName+"="+anAttributeValue+"]"); - Enumeration lEnumeration = lDiscoveryService.getLocalAdvertisements(DiscoveryService.ADV, anAttributeName,anAttributeValue); - enumeration2List(lEnumeration, lReturnList); - } - if (lReturnList.size() < numberOfexpectedAdv) { - mLog.info(lReturnList.size() +" of ["+numberOfexpectedAdv+"] advertisements found in local, trying remote..."); - lDiscoveryService.getRemoteAdvertisements(aPeerId, DiscoveryService.ADV, anAttributeName,anAttributeValue, 10,lDiscoveryListener); - if (lSemaphore.tryAcquire(ADV_DISCOVERY_TIMEOUT_INT,TimeUnit.MILLISECONDS) == false && lReturnList.isEmpty()) { - throw new P2pProxyAdvertisementNotFoundException( anAttributeName+"="+anAttributeValue+ " not found"); - } - lSemaphore.release(); - } - if (mLog.isInfoEnabled() && mLog.isDebugEnabled() == false) mLog.info(lReturnList.get(0).toString()); - for (Advertisement lAdvertisement :lReturnList) { - mLog.debug(lAdvertisement.toString()); - } - return lReturnList; - } - public JxtaSocket openSocket(String aPeerId, String anAdvertisementName,int aSocketTimout,boolean isTryFromLocal) throws InterruptedException, P2pProxyException, IOException { - List lModuleSpecAdvertisementList; - lModuleSpecAdvertisementList = (List) getAdvertisementList(aPeerId, anAdvertisementName, isTryFromLocal); - // reset just in case - JxtaSocket lJxtaSocket = null; - for (int i=0; i < lModuleSpecAdvertisementList.size(); i++) { - try { - lJxtaSocket = new JxtaSocket(getPeerGroup(), null, lModuleSpecAdvertisementList.get(i).getPipeAdvertisement(), aSocketTimout, true); - // ok, socket connected :-) - mLog.info("socket ["+lJxtaSocket+"] connected"); - break; - }catch (IOException e) { - mLog.warn("cannot open socket, for index ["+i+"] try next from ["+lModuleSpecAdvertisementList.size()+"]", e); - mLog.debug("bad adv "+lModuleSpecAdvertisementList.get(i).getPipeAdvertisement().toString()); - } - } - if (lJxtaSocket == null) { - throw new P2pProxyException("Cannot start peer info service because cannot bind jxta socket"); - } else { - return lJxtaSocket; - } - -} - /** - * check if connected to an rdv for aTimeout - * @param aTimeout - * @return true if connected else false - * @throws InterruptedException - */ - public boolean isConnectedToRendezVous(long aTimeout) throws InterruptedException{ - long lStartTime = System.currentTimeMillis(); - boolean lExit = false; - while(lExit == false) { - if (mRendezVousService.isConnectedToRendezVous() ) { - ID lRdvPeerId = (ID)getPeerGroup().getRendezVousService().getConnectedRendezVous().nextElement(); - mLog.info("Connected to rdv ["+lRdvPeerId+"]"); - lExit=true; - } else { - if (System.currentTimeMillis() - lStartTime > aTimeout) { - return false; - } - mLog.info("waiting to rdv connection"); - Thread.sleep(500); - } - - } - return true; - } - public void stop() { - mNetworkPeerGroup.stopApp(); - //mNetworkPeerGroup.unref(); - } - private List enumeration2List(Enumeration lEnumeration,List aList) { - if (aList == null) { - aList = new ArrayList(); - } - while (lEnumeration.hasMoreElements()) { - Advertisement lNewAdv = lEnumeration.nextElement(); - //1 check if already exist - for (Advertisement lAdv: aList) { - if (lAdv.equals(lNewAdv)) { - if (mLog.isInfoEnabled()) mLog.info("adv ["+lNewAdv.getID()+"]already gathered"); - if (mLog.isDebugEnabled()) mLog.debug(lNewAdv); - lNewAdv = null; - break; - } - } - - if (lNewAdv != null) { - aList.add((lNewAdv)) ; - } - } - return aList; - } -// private List getRdvPeers() { -// -// -// } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/MessageDispatcher.java b/p2pproxy/src/org/linphone/p2pproxy/core/MessageDispatcher.java deleted file mode 100644 index 21f40024..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/MessageDispatcher.java +++ /dev/null @@ -1,53 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -MessageDispatcher.java - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.log4j.Logger; - -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; - -/** - * - * @author jehan - * - */ -public class MessageDispatcher implements PipeMsgListener { - private final static Logger mLog = Logger.getLogger(MessageDispatcher.class); - - private List mPipeMsgListenerList = Collections.synchronizedList(new ArrayList()); - - public void pipeMsgEvent(PipeMsgEvent event) { - synchronized (this) { - mLog.debug("receiving event with message ["+event.getMessage()+"] propagating to ["+mPipeMsgListenerList.size()+"]"); - for (PipeMsgListener lPipeMsgListener:mPipeMsgListenerList) { - lPipeMsgListener.pipeMsgEvent(event); - } - } - } - public synchronized void addPipeMsgListener(PipeMsgListener aPipeMsgListener) { - mPipeMsgListenerList.add(aPipeMsgListener); - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyAccountManagement.java b/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyAccountManagement.java deleted file mode 100644 index 117fac45..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyAccountManagement.java +++ /dev/null @@ -1,120 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyAccountManagement.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - - -import java.io.IOException; -import java.util.List; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyUserNotFoundException; - -import org.linphone.p2pproxy.api.P2pProxyUserAlreadyExistException; - -public class P2pProxyAccountManagement implements ServiceProvider, P2pProxyAccountManagementMBean { - private final static Logger mLog = Logger.getLogger(P2pProxyAccountManagement.class); - protected final JxtaNetworkManager mJxtaNetworkManager; - - public P2pProxyAccountManagement() { - mJxtaNetworkManager = null; - } - /** - * @param jxtaNetworkManager - */ - public P2pProxyAccountManagement(final JxtaNetworkManager jxtaNetworkManager) { - super(); - mJxtaNetworkManager = jxtaNetworkManager; - } - - public void start(long aTimeOut) throws P2pProxyException { - mLog.info("P2pProxyAccountManagementMBean started"); - } - - public void stop() { - mLog.info("P2pProxyAccountManagementMBean stopped"); - } - - public void createAccount(String aUserName) throws P2pProxyException, P2pProxyUserAlreadyExistException { - // 1 check if already exist - if (isValidAccount(aUserName) == false) { - - // 2 creates and remote publish - P2pUserProfileAdvertisement lP2pUserProfileAdvertisement = (P2pUserProfileAdvertisement) AdvertisementFactory.newAdvertisement(P2pUserProfileAdvertisement.getAdvertisementType()); - - lP2pUserProfileAdvertisement.setID(IDFactory.newCodatID(mJxtaNetworkManager.getPeerGroup().getPeerGroupID())); - lP2pUserProfileAdvertisement.setUserName(aUserName); - try { - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().publish(lP2pUserProfileAdvertisement,DiscoveryService.INFINITE_LIFETIME,DiscoveryService.DEFAULT_EXPIRATION); - } catch (IOException e1) { - throw new P2pProxyException(e1); - } - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().remotePublish(lP2pUserProfileAdvertisement, DiscoveryService.NO_EXPIRATION); - mLog.debug("publishing P2pUserProfileAdvertisement :"+lP2pUserProfileAdvertisement); - } else { - throw new P2pProxyUserAlreadyExistException(aUserName); - } - - } - - public void deleteAccount(String aUserName) throws P2pProxyException, P2pProxyUserNotFoundException { - // 1 check if already exist - try { - List lAdvertisements = mJxtaNetworkManager.getAdvertisementList(null, P2pUserProfileAdvertisement.USER_NAME_TAG, aUserName, true); - if (lAdvertisements.isEmpty()) throw new P2pProxyUserNotFoundException (aUserName +" not found"); - - // 2 local and remote publish to 0 - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().flushAdvertisement(lAdvertisements.get(0)); - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().remotePublish(lAdvertisements.get(0), 0); - - } catch (P2pProxyAdvertisementNotFoundException e) { - throw e; - } catch (InterruptedException e) { - throw new P2pProxyException(e); - } catch (IOException e) { - throw new P2pProxyException(e); - } - - } - - public boolean isValidAccount(String aUserName) throws P2pProxyException { - boolean lStatus = false; - try { - if (mJxtaNetworkManager.getAdvertisementList(null, P2pUserProfileAdvertisement.USER_NAME_TAG, aUserName, true).size() >0 ) { - lStatus = true;; - } - } catch (P2pProxyAdvertisementNotFoundException e) { - lStatus = false; - }catch (Exception e) { - mLog.error("cannot check acount",e); - } - return lStatus; - } - - - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyAccountManagementMBean.java b/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyAccountManagementMBean.java deleted file mode 100644 index a36dc984..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyAccountManagementMBean.java +++ /dev/null @@ -1,49 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyAccountManagementMBean.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyUserAlreadyExistException; - -public interface P2pProxyAccountManagementMBean { - /** - * a create an account with the given name (must be unique) - * @param aUserName - * @exception P2pProxyUserAlreadyExistException - * @throws P2pProxyException - */ - public void createAccount(String aUserName) throws P2pProxyUserAlreadyExistException, P2pProxyException; - /** - * check if a user name has been already created - * @param aUserName - * @return true if the account has been successfully created - * @exception P2pProxyUserAlreadyExistException - * @throws P2pProxyException - */ - public boolean isValidAccount(String aUserName) throws P2pProxyException; - - /** - * delete an account with the given name (must be unique) - * @param aUserName - * @exception P2pProxyUserAlreadyExistException - */ - public void deleteAccount(String aUserName) throws P2pProxyException; - } diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyAdvertisementNotFoundException.java b/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyAdvertisementNotFoundException.java deleted file mode 100644 index d35cf3ff..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyAdvertisementNotFoundException.java +++ /dev/null @@ -1,57 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyAdvertisementNotFoundException.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - -import org.linphone.p2pproxy.api.P2pProxyException; - -@SuppressWarnings("serial") -public class P2pProxyAdvertisementNotFoundException extends P2pProxyException { - - /** - * - */ - public P2pProxyAdvertisementNotFoundException() { - super(); - } - - /** - * @param arg0 - * @param arg1 - */ - public P2pProxyAdvertisementNotFoundException(String arg0, Throwable arg1) { - super(arg0, arg1); - } - - /** - * @param arg0 - */ - public P2pProxyAdvertisementNotFoundException(String arg0) { - super(arg0); - } - - /** - * @param arg0 - */ - public P2pProxyAdvertisementNotFoundException(Throwable arg0) { - super(arg0); - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyInstanceImpl.java b/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyInstanceImpl.java deleted file mode 100644 index 9598ba21..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyInstanceImpl.java +++ /dev/null @@ -1,274 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyInstanceImpl.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - - -import java.io.File; -import java.net.InetAddress; -import java.net.URI; -import java.net.UnknownHostException; -import java.util.Enumeration; -import java.util.Properties; - -import net.jxta.id.IDFactory; -import net.jxta.peergroup.PeerGroupID; -import net.jxta.platform.NetworkConfigurator; -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyInstance; -import org.linphone.p2pproxy.api.P2pProxyManagement; -import org.linphone.p2pproxy.api.P2pProxyNetworkProbe; -import org.linphone.p2pproxy.api.P2pProxyRtpRelayManagement; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar; -import org.zoolu.net.SocketAddress; -import org.zoolu.sip.provider.SipProvider; - - -public class P2pProxyInstanceImpl implements P2pProxyInstance { - private final static Logger mLog = Logger.getLogger(P2pProxyInstance.class); - private static int BASE_PROXY_SIP_PORT = 6000; - private static int BASE_CLIENT_SIP_PORT = 8000; - int mIndex=0; - private Mode mMode = Mode.edge ; - boolean isStarted = false; - boolean isRevoked = false; - JxtaNetworkManager mJxtaNetworkManager; - SipProxyRegistrar mSipProxy; - SipProvider mProviderForSipClient; - String mSipClientName; - String mPrivateHostAddress; - String mPublicHostAddress ; - private ServiceProvider mServiceProvider; - private P2pProxyManagement mP2pProxyManagement; - private P2pProxyAccountManagementMBean mP2pProxyAccountManagement; - private int mRelayCapacity=4; - private Configurator mConfigurator; - private Properties startupProperties = new Properties(); - public P2pProxyInstanceImpl () { - - } - /* (non-Javadoc) - * @see org.linphone.p2pproxy.P2pProxyInstance#getIndex() - */ - public int getIndex() { - return mIndex; - } - /* (non-Javadoc) - * @see org.linphone.p2pproxy.P2pProxyInstance#setIndex(int) - */ - public void setIndex(int index) { - mIndex = index; - } - /* (non-Javadoc) - * @see org.linphone.p2pproxy.P2pProxyInstance#start() - */ - public void start() throws Exception{ - Thread lThread = new Thread() { - public void run() { - try { - File lJxtaDirectory = new File ("P2pNetwork-"+getMode()+"-"+mIndex); - if (lJxtaDirectory.exists() == false) lJxtaDirectory.mkdir(); - mConfigurator = new Configurator(new File (lJxtaDirectory.getAbsolutePath()+"/prop.xml")); - mConfigurator.serProperties(P2pProxyInstanceImpl.this.startupProperties); - mConfigurator.setProperty(JxtaNetworkManager.RELAY_CAPACITY, String.valueOf(mRelayCapacity)); - // setup jxta network - NetworkConfigurator lNetworkConfigurator; - // set mode - lNetworkConfigurator = new NetworkConfigurator(JxtaNetworkManager.EDGE_MODE,lJxtaDirectory.toURI()); - lNetworkConfigurator.setHome(lJxtaDirectory); - if (!lNetworkConfigurator.exists()) { - lNetworkConfigurator.setPeerID(IDFactory.newPeerID(PeerGroupID.defaultNetPeerGroupID)); - lNetworkConfigurator.setDescription("p2p proxy instance"); - lNetworkConfigurator.save(); - } else { - lNetworkConfigurator.load(); - } - // set sedding host - lNetworkConfigurator.addSeedRendezvous(new URI("tcp://"+getPublicHostAddress()+":"+BASE_TCP)); - lNetworkConfigurator.addSeedRelay(new URI("tcp://"+getPublicHostAddress()+":"+BASE_TCP)); - // set listening ports -// lNetworkConfigurator.setTcpInterfaceAddress(getPrivateHostAddress()); -// lNetworkConfigurator.setHttpInterfaceAddress(getPrivateHostAddress()); -// lNetworkConfigurator.setHttpPort(BASE_HTTP + mIndex); - lNetworkConfigurator.setTcpPort(BASE_TCP + mIndex); - - switch (mMode) { - case edge: - startEdge(mConfigurator,lNetworkConfigurator); - break; - case relay: - startRelay(mConfigurator,lNetworkConfigurator,false); - break; - case seeding_server: - startRelay(mConfigurator,lNetworkConfigurator,true); - break; - case auto: - //1 start edge - startEdge(mConfigurator,lNetworkConfigurator); - // check if peer mode required - if (mP2pProxyManagement.shouldIBehaveAsAnRdv() == true) { - String lPublicHttpAddress = mP2pProxyManagement.getPublicIpAddress().getHostAddress(); - - lNetworkConfigurator.setHttpPublicAddress(lPublicHttpAddress+":"+(BASE_HTTP + mIndex), true); - mServiceProvider.stop(); - mJxtaNetworkManager.stop(); - - startRelay(mConfigurator,lNetworkConfigurator,false); - // become relay - mMode = Mode.relay; - } else { - mMode = Mode.edge; - } - break; - default: - throw new Exception("unsupported mode ["+mMode+"]"); - } - mConfigurator.setProperty(SipProxyRegistrar.REGISTRAR_PORT,Integer.toString(BASE_PROXY_SIP_PORT+mIndex)); - // setup sip proxy - mP2pProxyAccountManagement = new P2pProxyAccountManagement(mJxtaNetworkManager); - mSipProxy = new SipProxyRegistrar(mConfigurator,mJxtaNetworkManager,mP2pProxyAccountManagement); - // setup sip client - mProviderForSipClient = new SipProvider(getPrivateHostAddress(),BASE_CLIENT_SIP_PORT+mIndex); - mProviderForSipClient.setOutboundProxy(new SocketAddress(getPrivateHostAddress(),BASE_PROXY_SIP_PORT+mIndex)); - mSipClientName="sip:user-"+mIndex+"@p2pproxy.linphone.org"; - - - mLog.info(P2pProxyInstanceImpl.this+" started "); - isStarted = true; - } catch (Exception e) { - mLog.error(P2pProxyInstanceImpl.this+" cannot be started",e); - isRevoked = true; - } - } - }; - lThread.start(); - } - public boolean isStarted() throws P2pProxyException{ - if (isRevoked == true) { - throw new P2pProxyException("cannot start " + this.toString() ); - } else { - return isStarted; - } - } - public SipProvider getSipClientProvider() { - return mProviderForSipClient; - } - - public String toString() { - return "p2p instance ["+mIndex+"] mode ["+mMode+"] sip port ["+BASE_PROXY_SIP_PORT+mIndex+"]"; - } - public String getSipClientName() { - return mSipClientName; - } - public void stop() throws Exception { - mProviderForSipClient.halt(); - //mSipProxy.halt(); - mJxtaNetworkManager.stop(); - } - public int getNumberOfconnectedPeers() { - Enumeration lConnectedPeers = mJxtaNetworkManager.getPeerGroup().getRendezVousService().getConnectedPeers(); - int lResult = 0; - while (lConnectedPeers.hasMoreElements()) { - lResult++; - lConnectedPeers.nextElement(); - } - return lResult; - } - public Object getOpaqueNetworkManager() { - return mJxtaNetworkManager; - } - - /** - * @return Returns the mHostAddress. - * @throws UnknownHostException - */ - public String getPrivateHostAddress() throws UnknownHostException { - if (mPrivateHostAddress == null) { - mPrivateHostAddress = InetAddress.getLocalHost().getHostAddress(); - } - return mPrivateHostAddress; - } - public String getPublicHostAddress() throws UnknownHostException { - if (mPublicHostAddress == null) { - mPublicHostAddress = InetAddress.getLocalHost().getHostAddress(); - } - return mPublicHostAddress; - } - - public void setPrivateHostAdress(String anAddress) { - mPrivateHostAddress = anAddress; - } - public void setPublicHostAdress(String anAddress) { - mPublicHostAddress = anAddress; - } - public P2pProxyNetworkProbe getManager() { - return (P2pProxyNetworkProbe)mServiceProvider; - } - public Mode getMode() { - return mMode; - } - public void setMode(Mode aMode) { - mMode = aMode; - } - private void startEdge(Configurator aProperties,NetworkConfigurator aNetworkConfigurator) throws Exception{ - // setup jxta - aNetworkConfigurator.setMode(JxtaNetworkManager.EDGE_MODE); - aNetworkConfigurator.setHttpEnabled(true); - aNetworkConfigurator.setHttpOutgoing(true); - - mJxtaNetworkManager = new JxtaNetworkManager(aProperties,aNetworkConfigurator,60000,JxtaNetworkManager.Mode.edge); - mServiceProvider = new EdgePeerServiceManager(aProperties, mJxtaNetworkManager); - mP2pProxyManagement = (P2pProxyManagement) mServiceProvider; - mServiceProvider.start(3000L); - } - - private void startRelay(Configurator aProperties,NetworkConfigurator aNetworkConfigurator,boolean isSeeding) throws Exception{ - // setup jxta - aNetworkConfigurator.setMode(JxtaNetworkManager.SUPER_PEER_MODE); - if (isSeeding == true) { - mJxtaNetworkManager = new JxtaNetworkManager(aProperties,aNetworkConfigurator,60000,JxtaNetworkManager.Mode.seeding_server); - mServiceProvider = new SeedingPeerServiceManager(aProperties, mJxtaNetworkManager,true); - mP2pProxyManagement = null; - } else { - mJxtaNetworkManager = new JxtaNetworkManager(aProperties,aNetworkConfigurator,60000,JxtaNetworkManager.Mode.relay); - mServiceProvider = new SuperPeerServiceManager(aProperties, mJxtaNetworkManager); - mP2pProxyManagement = (P2pProxyManagement) mServiceProvider; - } - mServiceProvider.start(3000L); - } - public void setRelayCapacity(int aCapacity) { - mRelayCapacity = aCapacity; - - } - public void setProperty(String key, String value) throws P2pProxyException { - if (mConfigurator == null) { - startupProperties.setProperty(key, value); - } else { - throw new P2pProxyException(" started"); - } - } - public int getAdvertisementDiscoveryTimeout() { - return JxtaNetworkManager.ADV_DISCOVERY_TIMEOUT_INT; - } - public P2pProxyRtpRelayManagement getRtpRelayManager() { - return (P2pProxyRtpRelayManagement)mServiceProvider; - } -} \ No newline at end of file diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyMain.java b/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyMain.java deleted file mode 100644 index 82f15fc3..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyMain.java +++ /dev/null @@ -1,520 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -P2pProxyMain.java - main class. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import java.lang.management.ManagementFactory; -import java.util.InvalidPropertiesFormatException; -import java.util.Properties; -import java.util.concurrent.Callable; -import java.util.concurrent.Future; - -import javax.management.ObjectName; - -import net.jxta.exception.JxtaException; -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyManagement; -import org.linphone.p2pproxy.api.P2pProxyNotReadyException; -import org.linphone.p2pproxy.api.P2pProxyResourceManagement; -import org.linphone.p2pproxy.api.P2pProxyUserAlreadyExistException; -import org.linphone.p2pproxy.core.media.MediaResourceService; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar; -import org.linphone.p2pproxy.core.utils.Excecutor; -import org.zoolu.sip.provider.SipStack; -import org.linphone.p2pproxy.launcher.P2pProxylauncherConstants; - -public class P2pProxyMain implements P2pProxyMainMBean { - private static Logger mLog = null; - private static JxtaNetworkManager mJxtaNetworkManager; - private static ServiceProvider mServiceProvider; - private static P2pProxyManagement mP2pProxyManagement; - private static SipProxyRegistrar mSipAndPipeListener; - private static P2pProxyAccountManagementMBean mP2pProxyAccountManagement; - private static P2pProxyResourceManagement mP2pProxySipProxyRegistrarManagement; - public final static String ACCOUNT_MGR_MBEAN_NAME="org.linphone.p2proxy:type=account-manager"; - public final static String PROXY_REG_MBEAN_NAME="org.linphone.p2proxy:type=proxy-registrar"; - public final static String MAIN_MBEAN_NAME="org.linphone.p2proxy:type=main"; - private static P2pProxyMain mP2pProxyMain = new P2pProxyMain(); - private static Configurator mConfigurator; - private static String mConfigHomeDir; - static private boolean mExit = false; - static private boolean isReady = false; - - - - static { -// System.setProperty("com.sun.management.jmxremote", "true"); -// System.setProperty("com.sun.management.jmxremote.port", "6789"); -// System.setProperty("com.sun.management.jmxremote.authenticate", "false"); -// System.setProperty("com.sun.management.jmxremote.ssl", "false"); - } - - /** - * @param args - * @throws P2pProxyException - * @throws InterruptedException - * @throws JxtaException - * @throws IOException - * @throws FileNotFoundException - * @throws InvalidPropertiesFormatException - */ - public static void main(String[] args) { - try { - mConfigHomeDir=System.getProperty("user.home")+"/.p2pproxy"; - int lsipPort=5040; - int lMediaPort=MediaResourceService.AUDIO_VIDEO_LOCAL_PORT_DEFAULT_VALUE; - int lP2pPort = 9701; - JxtaNetworkManager.Mode lMode = JxtaNetworkManager.Mode.auto; - // setup logging - - // get config dire first - for (int i=0; i < args.length; i=i+2) { - String argument = args[i]; - if (argument.equals("-jxta")) { - mConfigHomeDir = args[i + 1]; - File lFile = new File(mConfigHomeDir); - if (lFile.exists() == false) lFile.mkdir(); - - System.out.println("mConfigHomeDir detected[" + mConfigHomeDir + "]"); - } - } - System.setProperty("org.linphone.p2pproxy.home", mConfigHomeDir); - - - System.setProperty("net.jxta.logging.Logging", "FINEST"); - System.setProperty("net.jxta.level", "FINEST"); - - mP2pProxyMain.loadTraceConfigFile(); - - - - mLog.info("p2pproxy initilizing..."); - - File lPropertyFile = new File(mConfigHomeDir+"/p2pproxy.properties.xml"); - mConfigurator = new Configurator(lPropertyFile); - try { - ObjectName lObjectName = new ObjectName(MAIN_MBEAN_NAME); - ManagementFactory.getPlatformMBeanServer().registerMBean(mP2pProxyMain,lObjectName); - - - } catch (Exception e) { - mLog.warn("cannot register MBean",e); - } - - // get other params - for (int i=0; i < args.length; i=i+2) { - String argument = args[i]; - if (argument.equals("-jxta") || argument.equals("-home")) { - mConfigHomeDir = args[i + 1]; - //nop - } else if (argument.equals("-sip")) { - lsipPort = Integer.parseInt(args[i + 1]); - System.out.println("sipPort detected[" + lsipPort + "]"); - mConfigurator.setProperty(SipProxyRegistrar.REGISTRAR_PORT, Integer.toString(lsipPort)); - } else if (argument.equals("-media")) { - lMediaPort = Integer.parseInt(args[i + 1]); - System.out.println("media detected[" + lMediaPort + "]"); - mConfigurator.setProperty(MediaResourceService.AUDIO_VIDEO_LOCAL_PORT, Integer.toString(lMediaPort)); - } else if (argument.equals("-p2p")) { - lP2pPort = Integer.parseInt(args[i + 1]); - System.out.println("p2p port detected[" + lP2pPort + "]"); - mConfigurator.setProperty(JxtaNetworkManager.TCP_LISTENING_PORT, Integer.toString(lP2pPort)); - } else if (argument.equals("-relay")) { - lMode = JxtaNetworkManager.Mode.relay; - mConfigurator.setProperty(JxtaNetworkManager.MODE, lMode.name()); - System.out.println("relay mode detected"); - i--; - } else if (argument.equals("-edge-only")) { - lMode = JxtaNetworkManager.Mode.edge; - mConfigurator.setProperty(JxtaNetworkManager.MODE, lMode.name()); - System.out.println("edge only mode detected"); - i--; - }else if (argument.equals("-seeding-server")) { - lMode = JxtaNetworkManager.Mode.seeding_server; - mConfigurator.setProperty(JxtaNetworkManager.MODE, lMode.name()); - System.out.println("seeding-server detected"); - i--; - } else if (argument.equals("-auto-config")) { - lMode = JxtaNetworkManager.Mode.auto; - mConfigurator.setProperty(JxtaNetworkManager.MODE, lMode.name()); - System.out.println("auto-mode mode detected"); - i--; - } else if (argument.equals("-seeding-rdv")) { - mConfigurator.setProperty(JxtaNetworkManager.SEEDING_RDV, args[i + 1]); - System.out.println("seeding rdv detected[" + args[i + 1] + "]"); - } - else if (argument.equals("-seeding-relay")) { - mConfigurator.setProperty(JxtaNetworkManager.SEEDING_RELAY, args[i + 1]); - System.out.println("seeding relay detected[" + args[i + 1] + "]"); - } else if (argument.equals("-seeding")) { - mConfigurator.setProperty(JxtaNetworkManager.SEEDING_RDV, args[i + 1]); - mConfigurator.setProperty(JxtaNetworkManager.SEEDING_RELAY, args[i + 1]); - System.out.println("seeding detected[" + args[i + 1] + "]"); - } - else if (argument.equals("-public-address")) { - mConfigurator.setProperty(JxtaNetworkManager.HTTP_LISTENING_PUBLIC_ADDRESS,args[i + 1]+":9700"); - mConfigurator.setProperty(JxtaNetworkManager.TCP_LISTENING_PUBLIC_ADDRESS,args[i + 1]+":"+lP2pPort); - mConfigurator.setProperty(MediaResourceService.AUDIO_VIDEO_PUBLIC_URI,"udp://"+args[i + 1]+":"+lMediaPort); - mConfigurator.setProperty(SipProxyRegistrar.REGISTRAR_PUBLIC_ADDRESS,args[i + 1]); - System.out.println("public address detected[" + args[i + 1] + "]"); - } - else - { - System.out.println("Invalid option: " + args[i]); - usage(); - System.exit(1); - } - } - - File lJxtaDirectory = new File (mConfigHomeDir); - if (lJxtaDirectory.exists() == false) lJxtaDirectory.mkdir(); - - - switch (lMode) { - case edge: - startEdge(mConfigurator,lJxtaDirectory); - break; - case relay: - startRelay(mConfigurator,lJxtaDirectory); - break; - case seeding_server: - startSeeding(mConfigurator,lJxtaDirectory); - break; - case auto: - //1 start edge - startEdge(mConfigurator,lJxtaDirectory); - // check if peer mode required - if (mP2pProxyManagement.shouldIBehaveAsAnRdv() == true) { - String lPublicAddress = mP2pProxyManagement.getPublicIpAddress().getHostAddress(); - mConfigurator.setProperty(JxtaNetworkManager.HTTP_LISTENING_PUBLIC_ADDRESS, lPublicAddress+":9700"); - mConfigurator.setProperty(JxtaNetworkManager.TCP_LISTENING_PUBLIC_ADDRESS, lPublicAddress+":9701"); - mServiceProvider.stop(); - mJxtaNetworkManager.stop(); - startRelay(mConfigurator,lJxtaDirectory); - mJxtaNetworkManager.getPeerGroup().getRendezVousService().setAutoStart(true); - } - break; - default: - mLog.fatal("unsupported mode ["+lMode+"]"); - System.exit(1); - - } - - - //set management - try { - ObjectName lObjectName = new ObjectName(ACCOUNT_MGR_MBEAN_NAME); - ManagementFactory.getPlatformMBeanServer().registerMBean(mP2pProxyAccountManagement,lObjectName); - } catch (Exception e) { - mLog.warn("cannot register MBean",e); - } - - - mLog.warn("p2pproxy initilized"); - isReady = true; - while (mExit == false) { - Thread.sleep(1000); - } - if (mServiceProvider!= null) mServiceProvider.stop(); - if (mServiceProvider!= null) mServiceProvider.stop(); - if (mSipAndPipeListener!= null) mSipAndPipeListener.stop(); - if (mJxtaNetworkManager != null) mJxtaNetworkManager.stop(); - mLog.info("p2pproxy stopped"); - return; - - } catch (Exception e) { - mLog.fatal("error",e); - System.exit(1); - } - } - private static void startEdge(Configurator aProperties,File aConfigDir) throws Exception{ - // setup jxta - mJxtaNetworkManager = new JxtaNetworkManager(aProperties,aConfigDir); - mServiceProvider = new EdgePeerServiceManager(aProperties, mJxtaNetworkManager); - mP2pProxyManagement = (P2pProxyManagement) mServiceProvider; - mP2pProxySipProxyRegistrarManagement = (P2pProxyResourceManagement) mServiceProvider; - //setup account manager - mP2pProxyAccountManagement = new P2pProxyAccountManagement(mJxtaNetworkManager); - mServiceProvider.start(3000L); - } - - private static void startRelay(Configurator aProperties,File aConfigDir) throws Exception{ - // setup jxta - mJxtaNetworkManager = new JxtaNetworkManager(aProperties,aConfigDir); - mServiceProvider = new SuperPeerServiceManager(aProperties, mJxtaNetworkManager); - mP2pProxyManagement = (P2pProxyManagement) mServiceProvider; - mP2pProxySipProxyRegistrarManagement = (P2pProxyResourceManagement) mServiceProvider; - mServiceProvider.start(3000L); - //setup account manager - mP2pProxyAccountManagement = new P2pProxyAccountManagement(mJxtaNetworkManager); -// setup sip provider - SipStack.log_path = mConfigHomeDir+"/logs"; - mSipAndPipeListener = new SipProxyRegistrar(mConfigurator,mJxtaNetworkManager,mP2pProxyAccountManagement); - //set management - try { - ObjectName lObjectName = new ObjectName(PROXY_REG_MBEAN_NAME); - ManagementFactory.getPlatformMBeanServer().registerMBean(mSipAndPipeListener,lObjectName); - - } catch (Exception e) { - mLog.warn("cannot register MBean",e); - } - } - private static void startSeeding(Configurator aProperties,File aConfigDir) throws Exception{ - // setup jxta - mJxtaNetworkManager = new JxtaNetworkManager(aProperties,aConfigDir); - mServiceProvider = new SeedingPeerServiceManager(aProperties, mJxtaNetworkManager,true); - mP2pProxyManagement = null; - mP2pProxySipProxyRegistrarManagement = (P2pProxyResourceManagement) mServiceProvider; - mServiceProvider.start(3000L); - //setup account manager - mP2pProxyAccountManagement = new P2pProxyAccountManagement(mJxtaNetworkManager); - // setup sip provider - SipStack.log_path = mConfigHomeDir+"/logs"; - mSipAndPipeListener = new SipProxyRegistrar(mConfigurator,mJxtaNetworkManager,mP2pProxyAccountManagement); - //set management - try { - ObjectName lObjectName = new ObjectName(PROXY_REG_MBEAN_NAME); - ManagementFactory.getPlatformMBeanServer().registerMBean(mSipAndPipeListener,lObjectName); - - } catch (Exception e) { - mLog.warn("cannot register MBean",e); - } - } - private static void usage() { - System.out.println("p2pproxy"); - System.out.println("-home : directory where configuration/cache is located (including jxta cache.default is $HOME/.p2pproxy"); - System.out.println("-sip : udp proxy port, default 5060"); - System.out.println("-media : udp relay/stun port, default 16000"); - System.out.println("-p2p : p2p tcp port, default 9701"); - System.out.println("-relay : super peer mode"); - System.out.println("-edge-only : edge mode"); - System.out.println("-seeding-server : seeding server mode"); - System.out.println("-auto-config : automatically choose edge or relay (default mode)"); - System.out.println("-seeding : list of boostrap rdv separated by | (ex tcp://127.0.0.1:9701|http://127.0.0.2:9700)"); - System.out.println("-public-address : ip as exported to peers (ex myPublicAddress.no-ip.org)"); - } - -public void loadTraceConfigFile() throws P2pProxyException { - staticLoadTraceConfigFile(); - } -public static void staticLoadTraceConfigFile() throws P2pProxyException { - try { - InputStream lLog4jStream = null; - String lSearchDir; - //search build dir - lSearchDir = System.getProperty("org.linphone.p2pproxy.build.dir"); - File lFile = new File(lSearchDir+"/log4j.properties"); - if (lFile.exists() == false) { - lSearchDir = mConfigHomeDir; - lFile = new File(lSearchDir+"/log4j.properties"); - if (lFile.exists() == false) { - lSearchDir="."; - lFile = new File(lSearchDir+"/log4j.properties"); - if (lFile.exists() == false) { - lLog4jStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("log4j.properties"); - - } - } - } - if (lLog4jStream == null) { - lLog4jStream = new FileInputStream(lFile); - } - Properties llog4Properties = new Properties(); - llog4Properties.load(lLog4jStream); - PropertyConfigurator.configure(llog4Properties); - mLog = Logger.getLogger(P2pProxyMain.class); - // read java.util.logging properties - - llog4Properties.setProperty("java.util.logging.FileHandler.pattern",System.getProperty("org.linphone.p2pproxy.home")+"/logs/p2pproxy.log"); - File lLogConfigFile = new File(mConfigHomeDir.concat("log4j.properties")+".tmp"); - if (lLogConfigFile.exists() == false) { - lLogConfigFile.createNewFile(); - } - llog4Properties.store(new FileOutputStream(lLogConfigFile), "tmp"); - System.setProperty("java.util.logging.config.file",lLogConfigFile.getAbsolutePath()); - java.util.logging.LogManager.getLogManager().readConfiguration(); - } catch (Exception e) { - throw new P2pProxyException("enable to load traces",e); - } -} -private static boolean isReadyNoThrow() { - try { - isReady(); - return true; - } catch (P2pProxyNotReadyException e) { - return false; - } -} -private static void isReady() throws P2pProxyNotReadyException { - try { - if ((isReady == true && mJxtaNetworkManager.isConnectedToRendezVous(0) == true) - || - (isReady == true && mJxtaNetworkManager.getPeerGroup().getRendezVousService().isRendezVous())) { - //nop connected - } else { - if (mJxtaNetworkManager != null ) { - throw new P2pProxyNotReadyException("not connected to any rdv: status ["+mJxtaNetworkManager.getPeerGroup().getRendezVousService().getRendezVousStatus()+"]"); - } else { - throw new P2pProxyNotReadyException("initializing"); - } - } - } catch (InterruptedException e) { - throw new P2pProxyNotReadyException(e); - } -} -/* p2pproxy.h implementation*/ -private static int excecuteAction(Future aResult, Class> classTaskName) { - try { - if (aResult.isDone() == false) { - return P2pProxylauncherConstants.P2PPROXY_EWOULDBLOCK; - } else if (aResult == null) { - createAccountResult = Excecutor.pool.submit(classTaskName.newInstance()); - } else { - Future lResult = createAccountResult; - createAccountResult = null; - return lResult.get(); - } - return P2pProxylauncherConstants.P2PPROXY_ERROR; - } catch (Exception e) { - return P2pProxylauncherConstants.P2PPROXY_ERROR; - } -} - -static Future createAccountResult = null; -public synchronized static int createAccount(final String aUserName) { - class CreateAcountTask implements Callable { - public Integer call() throws Exception { - try { - mP2pProxyAccountManagement.createAccount(aUserName); - } catch (P2pProxyUserAlreadyExistException e) { - return P2pProxylauncherConstants.P2PPROXY_ACCOUNTMGT_USER_EXIST; - } catch (P2pProxyException e) { - return P2pProxylauncherConstants.P2PPROXY_ERROR; - } - return P2pProxylauncherConstants.P2PPROXY_NO_ERROR; - } - }; - return excecuteAction(createAccountResult,CreateAcountTask.class); -} - -static Future deleteAccountResult = null; -public static int deleteAccount(final String aUserName) { - class DeleteAccountTask implements Callable { - - public Integer call() throws Exception { - mP2pProxyAccountManagement.deleteAccount(aUserName); - return P2pProxylauncherConstants.P2PPROXY_NO_ERROR; - } - - }; - return excecuteAction(deleteAccountResult,DeleteAccountTask.class); -} - -static Future isValidAccountResult = null; -public static int isValidAccount(final String aUserName){ - class IsValidAccountResultTask implements Callable { - - public Integer call() throws Exception { - if (mP2pProxyAccountManagement.isValidAccount(aUserName)) { - return P2pProxylauncherConstants.P2PPROXY_ACCOUNTMGT_USER_EXIST; - } else { - return P2pProxylauncherConstants.P2PPROXY_ACCOUNTMGT_USER_NOT_EXIST; - } - } - - }; - return excecuteAction(isValidAccountResult,IsValidAccountResultTask.class); -} - -static Future lookupSipProxyUriResult = null; -public static String lookupSipProxyUri(final String aDomaine) { - try { - isReady(); - String[] lProxies = mP2pProxySipProxyRegistrarManagement.lookupSipProxiesUri(aDomaine); - if (lProxies.length != 0) { - return lProxies[0]; - } else { - return null; - } - } catch (Exception e) { - return null; - } -} - -public static String[] lookupSipProxiesUri(String aDomaine) { - try { - isReady(); - return mP2pProxySipProxyRegistrarManagement.lookupSipProxiesUri(aDomaine); - } catch (Exception e) { - return null; - } - } - -public static String[] lookupMediaServerAddress(String aDomaine) { - try { - isReady(); - return mP2pProxySipProxyRegistrarManagement.getMediaServerList(); - } catch (Exception e) { - mLog.error("cannot find media resource",e); - return null; - } -} - -public static int getState() { - try { - isReady(); - return P2pProxylauncherConstants.P2PPROXY_CONNECTED; - } catch (P2pProxyException e) { - //if (mLog != null) mLog.info("cannot get state",e); - return P2pProxylauncherConstants.P2PPROXY_NOT_CONNECTED; - } -} -public static int revokeSipProxy(String aProxy) { - try { - isReady(); - mP2pProxySipProxyRegistrarManagement.revokeSipProxy(aProxy); - return P2pProxylauncherConstants.P2PPROXY_NO_ERROR; - } catch (P2pProxyException e) { - return P2pProxylauncherConstants.P2PPROXY_NOT_CONNECTED; - } -} -public static int revokeMediaServer(String aServer) { - try { - isReady(); - mP2pProxySipProxyRegistrarManagement.revokeMediaServer(aServer); - return P2pProxylauncherConstants.P2PPROXY_NO_ERROR; - } catch (P2pProxyException e) { - return P2pProxylauncherConstants.P2PPROXY_NOT_CONNECTED; - } - } -public static void stop() { - mExit = true; - -} -} \ No newline at end of file diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyMainMBean.java b/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyMainMBean.java deleted file mode 100644 index 29bc46d5..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyMainMBean.java +++ /dev/null @@ -1,32 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyMainMBean.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - -import org.linphone.p2pproxy.api.P2pProxyException; - -public interface P2pProxyMainMBean { - - /** - * reload traces from file - * @throws P2pProxyException - */ - public void loadTraceConfigFile() throws P2pProxyException ; -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyManagementImpl.java b/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyManagementImpl.java deleted file mode 100644 index 6a508f3c..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyManagementImpl.java +++ /dev/null @@ -1,69 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -P2pProxyManagementImpl.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketException; -import java.net.UnknownHostException; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyManagement; - -import org.linphone.p2pproxy.core.rdvautoconfig.PeerInfoServiceClient; - -public abstract class P2pProxyManagementImpl extends P2pProxyResourceManagementImpl implements ServiceProvider,P2pProxyManagement { - protected final Configurator mConfigurator; - private final PeerInfoServiceClient mPeerInfoServiceClient; - private final static Logger mLog = Logger.getLogger(P2pProxyManagementImpl.class); - - P2pProxyManagementImpl(Configurator aConfigurator, JxtaNetworkManager aJxtaNetworkManager) throws SocketException, UnknownHostException - { - super(aJxtaNetworkManager); - mConfigurator = aConfigurator; - mPeerInfoServiceClient = new PeerInfoServiceClient(aConfigurator, aJxtaNetworkManager); - } - - public void start(long aTimeout) throws P2pProxyException - { - mPeerInfoServiceClient.start(aTimeout); - - } - - public void stop() { - mPeerInfoServiceClient.stop(); - mLog.info("P2pProxyManagementImpl stopped"); - } - - public InetAddress getPublicIpAddress() - throws P2pProxyException - { - return mPeerInfoServiceClient.getPublicIpAddress(); - } - - public boolean probeSocket(InetSocketAddress aSocketAddress, Protocol aProtocol) throws P2pProxyException { - return mPeerInfoServiceClient.probeSocket(aSocketAddress, aProtocol); - } - - - - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyResourceManagementImpl.java b/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyResourceManagementImpl.java deleted file mode 100644 index 9f5694d5..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/P2pProxyResourceManagementImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.linphone.p2pproxy.core; - -import java.util.List; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyResourceManagement; -import org.linphone.p2pproxy.core.media.MediaResourceService; -import org.linphone.p2pproxy.core.sipproxy.NetworkResourceAdvertisement; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar; - -public class P2pProxyResourceManagementImpl implements P2pProxyResourceManagement { - protected final JxtaNetworkManager mJxtaNetworkManager; - - private final static Logger mLog = Logger.getLogger(P2pProxyResourceManagementImpl.class); - P2pProxyResourceManagementImpl(JxtaNetworkManager aJxtaNetworkManager) { - mJxtaNetworkManager = aJxtaNetworkManager; - } - public String[] lookupSipProxiesUri(String aDomaine) throws P2pProxyException { - try { - if (!DOMAINE.equals(aDomaine)) { - //unknown domaine - return new String[0]; - } - List lSipProxyRegistrarAdvertisements = (List) (mJxtaNetworkManager.getAdvertisementList(null, "Name",SipProxyRegistrar.ADV_NAME, true,2)); - String[] lAddresses = new String[lSipProxyRegistrarAdvertisements.size()]; - for (int i=0;i lMediaResoureAdvertisements = (List) (mJxtaNetworkManager.getAdvertisementList(null, "Name",MediaResourceService.ADV_NAME, true,2)); - String[] lAddresses = new String[lMediaResoureAdvertisements.size()]; - for (int i=0;i lMediaResourceAdvertisement = (List) (mJxtaNetworkManager.getAdvertisementList(null,anAdvName, true)); - for (NetworkResourceAdvertisement lMediaResource:lMediaResourceAdvertisement) { - if (lMediaResource.getAddress().equals("udp://"+aResource)) { - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().flushAdvertisement(lMediaResource); - mLog.info(aResource +" revoked"); - } - - } - } catch (Exception e) { - throw new P2pProxyException(e); - } - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/P2pUserProfileAdvertisement.java b/p2pproxy/src/org/linphone/p2pproxy/core/P2pUserProfileAdvertisement.java deleted file mode 100644 index beda4b18..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/P2pUserProfileAdvertisement.java +++ /dev/null @@ -1,251 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pUserProfileAdvertisement.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core; - - -import java.io.Serializable; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - -import org.apache.log4j.Logger; - - - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attributable; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.TextElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; - -/** - * derivated from jxta Advertisement tutorial - *
            - * <?xml version="1.0"?>
            - * <!DOCTYPE jxta:System>
            - * <jxta:System xmlns:jxta="http://jxta.org">
            - *   <id>id</id>
            - *   <user-name>endpoint user name</name>
            - * </jxta:System>
            - * 
            - */ -public class P2pUserProfileAdvertisement extends ExtendableAdvertisement implements Comparable, Cloneable, Serializable { - /** - * Instantiator - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public String getAdvertisementType() { - return P2pUserProfileAdvertisement.getAdvertisementType(); - } - - /** - * Constructs an instance of Advertisement matching the - * type specified by the advertisementType parameter. - * - * @return The instance of Advertisement or null if it - * could not be created. - */ - public Advertisement newInstance() { - return new P2pUserProfileAdvertisement(); - } - - /** - * Constructs an instance of Advertisement matching the - * type specified by the advertisementType parameter. - * - * @param root Specifies a portion of a StructuredDocument which will - * be converted into an Advertisement. - * @return The instance of Advertisement or null if it - * could not be created. - */ - public Advertisement newInstance(net.jxta.document.Element root) { - return new P2pUserProfileAdvertisement(root); - } - } - private ID mId ;; - private String mName; - public final static String USER_NAME_TAG = "user-name"; - private final static String mIdTag = "ID"; - private final static String[] mIndexs = {USER_NAME_TAG}; - private final static Logger mLog = Logger.getLogger(P2pUserProfileAdvertisement.class); - /** - * - */ - public P2pUserProfileAdvertisement(Element root) { - - TextElement doc = (TextElement) root; - - if (!getAdvertisementType().equals(doc.getName())) { - throw new IllegalArgumentException("Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - initialize(doc); - - } - public P2pUserProfileAdvertisement() { - - // TODO Auto-generated constructor stub - } - /* (non-Javadoc) - * @see net.jxta.document.ExtendableAdvertisement#getDocument(net.jxta.document.MimeMediaType) - */ - @Override - public Document getDocument(MimeMediaType asMimeType) { - - StructuredDocument adv = StructuredDocumentFactory.newStructuredDocument(asMimeType, - getAdvertisementType()); - if (adv instanceof Attributable) { - ((Attributable) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - } - Element e; - e = adv.createElement(mIdTag, getID().toString()); - adv.appendChild(e); - e = adv.createElement(USER_NAME_TAG, getUserName().trim()); - adv.appendChild(e); - return adv; - } - - @Override - public ID getID() { - return mId; - } - - @Override - public String[] getIndexFields() { - return mIndexs; - } - public static String getAdvertisementType() { - return "jxta:p2p-proxy-user-profile"; - } - /* (non-Javadoc) - * @see net.jxta.document.Advertisement#toString() - */ - @Override - public String toString() { - // TODO Auto-generated method stub - return super.toString(); - } - public int compareTo(Object other) { - return getID().toString().compareTo(other.toString()); - } - /** - * Intialize a System advertisement from a portion of a structured document. - * - * @param root document root - */ - protected void initialize(Element root) { - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + - " only supports TextElement"); - } - TextElement doc = (TextElement) root; - if (!doc.getName().equals(getAdvertisementType())) { - throw new IllegalArgumentException("Could not construct : " - + getClass().getName() + "from doc containing a " + - doc.getName()); - } - Enumeration elements = doc.getChildren(); - while (elements.hasMoreElements()) { - TextElement elem = (TextElement) elements.nextElement(); - if (!handleElement(elem)) { - mLog.warn("Unhandleded element \'" + elem.getName() + "\' in " + doc.getName()); - } - } - } - /** - * Process an individual element from the document. - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - */ - protected boolean handleElement(TextElement elem) { - if (elem.getName().equals(mIdTag)) { - try { - URI id = new URI(elem.getTextValue()); - setID(IDFactory.fromURI(id)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("unknown ID format in advertisement: " + - elem.getTextValue()); - } - catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a known id type: " + - elem.getTextValue()); - } - return true; - } - if (elem.getName().equals(USER_NAME_TAG)) { - setUserName(elem.getTextValue()); - return true; - } - return false; - } - public void setID(ID id) { - mId = id; - } - @Override - public String getBaseAdvType() { - // TODO Auto-generated method stub - return null; - } - /** - * @return Returns the mName. - */ - public String getUserName() { - return mName; - } - /** - * @param name The mName to set. - */ - public void setUserName(String name) { - mName = name; - } - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - if (obj instanceof P2pUserProfileAdvertisement) { - P2pUserProfileAdvertisement adv = (P2pUserProfileAdvertisement) obj; - return getID().equals(adv.getID()); - } - - return false; - - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/SeedingPeerServiceManager.java b/p2pproxy/src/org/linphone/p2pproxy/core/SeedingPeerServiceManager.java deleted file mode 100644 index 364dd662..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/SeedingPeerServiceManager.java +++ /dev/null @@ -1,51 +0,0 @@ -// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. -// Jad home page: http://www.kpdus.com/jad.html -// Decompiler options: packimports(3) -// Source File Name: SuperPeerServiceManager.java - -package org.linphone.p2pproxy.core; - - - -import java.net.SocketException; -import java.net.UnknownHostException; -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.media.MediaResourceService; -import org.linphone.p2pproxy.core.rdvautoconfig.PeerInfoProviderService; - -public class SeedingPeerServiceManager extends P2pProxyResourceManagementImpl implements ServiceProvider { - protected final Configurator mConfigurator; - private final PeerInfoProviderService mPeerInfoProviderService; - private MediaResourceService mStunUdpRelayService = null; - - private final static Logger mLog = Logger.getLogger(SeedingPeerServiceManager.class); - SeedingPeerServiceManager(Configurator aConfigurator, JxtaNetworkManager aJxtaNetworkManager,boolean enableUdpRelay) throws SocketException, UnknownHostException { - super(aJxtaNetworkManager); - mConfigurator = aConfigurator; - mPeerInfoProviderService = new PeerInfoProviderService(aConfigurator, aJxtaNetworkManager); - if (enableUdpRelay == true) { - mStunUdpRelayService = new MediaResourceService(aConfigurator,aJxtaNetworkManager); - } - } - - public void start(long aTimeout) throws P2pProxyException { - mPeerInfoProviderService.start(aTimeout); - if (mStunUdpRelayService != null) { - mStunUdpRelayService.start(aTimeout); - } - mLog.info("SeedingPeerServiceManager started"); - } - - public void stop() { - mPeerInfoProviderService.stop(); - if (mStunUdpRelayService != null) { - mStunUdpRelayService.stop(); - } - mLog.info("SeedingPeerServiceManager stopped"); - } - - - - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/ServiceProvider.java b/p2pproxy/src/org/linphone/p2pproxy/core/ServiceProvider.java deleted file mode 100644 index b5a98292..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/ServiceProvider.java +++ /dev/null @@ -1,16 +0,0 @@ -// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. -// Jad home page: http://www.kpdus.com/jad.html -// Decompiler options: packimports(3) -// Source File Name: ServiceProvider.java - -package org.linphone.p2pproxy.core; - -import org.linphone.p2pproxy.api.P2pProxyException; - -public interface ServiceProvider -{ - - public abstract void start(long aTimeOut) throws P2pProxyException; - - public abstract void stop(); -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/SuperPeerServiceManager.java b/p2pproxy/src/org/linphone/p2pproxy/core/SuperPeerServiceManager.java deleted file mode 100644 index 9db1c993..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/SuperPeerServiceManager.java +++ /dev/null @@ -1,44 +0,0 @@ -// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. -// Jad home page: http://www.kpdus.com/jad.html -// Decompiler options: packimports(3) -// Source File Name: SuperPeerServiceManager.java - -package org.linphone.p2pproxy.core; - -import java.net.SocketException; -import java.net.UnknownHostException; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; - -import org.linphone.p2pproxy.core.rdvautoconfig.PeerInfoProviderService; - -// Referenced classes of package org.linphone.p2pproxy.core: -// EdgePeerServiceManager, Configurator, JxtaNetworkManager - -public class SuperPeerServiceManager extends P2pProxyManagementImpl { - private final static Logger mLog = Logger.getLogger(SuperPeerServiceManager.class); - private final PeerInfoProviderService mPeerInfoProviderService; - SuperPeerServiceManager(Configurator aConfigurator, JxtaNetworkManager aJxtaNetworkManager) throws P2pProxyException, SocketException, UnknownHostException - { - super(aConfigurator,aJxtaNetworkManager); - mPeerInfoProviderService = new PeerInfoProviderService(aConfigurator, aJxtaNetworkManager); - } - - public void start(long aTimeOut) throws P2pProxyException { - mPeerInfoProviderService.start(aTimeOut); - mLog.info("SuperPeerServiceManager started"); - } - - public void stop() { - super.stop(); - mPeerInfoProviderService.stop(); - mLog.info("SuperPeerServiceManager stopped"); - } - - - public boolean shouldIBehaveAsAnRdv() throws P2pProxyException{ - return false; - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/jxtaext/EndpointRegistry.java b/p2pproxy/src/org/linphone/p2pproxy/core/jxtaext/EndpointRegistry.java deleted file mode 100644 index 7240a216..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/jxtaext/EndpointRegistry.java +++ /dev/null @@ -1,63 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -EndpointRegistry.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.jxtaext; - -import java.net.InetAddress; -import java.util.HashMap; -import java.util.Map; - -public class EndpointRegistry { - final static private EndpointRegistry mInstance = new EndpointRegistry(); - final private Map mMap = new HashMap(); - private EndpointRegistry() { - } - - static public EndpointRegistry getInstance() { - return mInstance; - } - /** - * @param aKey peer Id as retyrned by EndpointAdress.getProtocolAddress() - * @return - */ - synchronized public boolean isPresent(String aKey) { - return mMap.containsKey(aKey); - } - /** - * @param aKey peer Id as retyrned by EndpointAdress.getProtocolAddress() - * @return IP address or null - */ - synchronized public InetAddress get(String aKey) { - return mMap.get(aKey); - } - /** - * @param a Key peer Id as retyrned by EndpointAdress.getProtocolAddress() - * @param aValue - */ - synchronized public void add(String aKey,InetAddress aValue) { - mMap.put(aKey, aValue) ; - } - /** - * @param aKey peer Id as retyrned by EndpointAdress.getProtocolAddress() - */ - synchronized public void remove(String aKey) { - mMap.remove(aKey) ; - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/jxtaext/NatedEndPointAddress.java b/p2pproxy/src/org/linphone/p2pproxy/core/jxtaext/NatedEndPointAddress.java deleted file mode 100644 index 62644422..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/jxtaext/NatedEndPointAddress.java +++ /dev/null @@ -1,52 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -NatedEndPointAddress.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.jxtaext; - - -import net.jxta.endpoint.EndpointAddress; - -public class NatedEndPointAddress extends EndpointAddress { - - String mRemoteHost; - /** - * @return Returns the mRemoteHost. - */ - public String getRemoteHost() { - return mRemoteHost; - } - - - /** - * @param protocol - * @param address - * @param service - * @param serviceParam - */ - public NatedEndPointAddress(String protocol, String address, String service, String serviceParam,String remoteHost) { - super(protocol, address, service, serviceParam); - // TODO Auto-generated constructor stub - } - - public String toString() { - return super.toString() + "remote host address ["+mRemoteHost+"]"; - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/MediaResourceService.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/MediaResourceService.java deleted file mode 100644 index 5a887112..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/MediaResourceService.java +++ /dev/null @@ -1,108 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -MediaResourceService.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.media; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketException; -import java.net.URI; -import java.net.UnknownHostException; -import java.util.Timer; -import java.util.TimerTask; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.id.IDFactory; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.Configurator; -import org.linphone.p2pproxy.core.GenericUdpSession; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.ServiceProvider; -import org.linphone.p2pproxy.core.media.rtprelay.RtpRelayServer; -import org.linphone.p2pproxy.core.media.rtprelay.RtpRelayServerConfig; -import org.linphone.p2pproxy.core.sipproxy.NetworkResourceAdvertisement; -import org.linphone.p2pproxy.core.stun.StunServer; - -public class MediaResourceService implements ServiceProvider { - private final static Logger mLog = Logger.getLogger(MediaResourceService.class); - public final static String AUDIO_VIDEO_LOCAL_PORT="org.linphone.p2pproxy.udp-media-relay.audio-video.port"; - public final static int AUDIO_VIDEO_LOCAL_PORT_DEFAULT_VALUE=16000; - public final static String AUDIO_VIDEO_PUBLIC_URI="org.linphone.p2pproxy.udp-media-relay.audio-video.public-uri"; - - private GenericUdpSession mUdpSessionForStunRtp; - private RtpRelayServer mRtpRelayServer; - private StunServer mSturServer; - private RtpRelayServerConfig mConfig; - private final JxtaNetworkManager mJxtaNetworkManager; - private NetworkResourceAdvertisement mStunRtpServerAdvertisement; - Timer mPublishTimer = new Timer("MediaResourceService publish timer"); - public final static String ADV_NAME = "p2p-proxy-stunrtp"; - private final int ADV_LIFE_TIME=6000000; - TimerTask mPublishTask; - public MediaResourceService(Configurator aConfigurator, JxtaNetworkManager aJxtaNetworkManager) throws SocketException, UnknownHostException { - - int lAudioVideoLocalPort = Integer.valueOf(aConfigurator.getProperty(MediaResourceService.AUDIO_VIDEO_LOCAL_PORT,String.valueOf(AUDIO_VIDEO_LOCAL_PORT_DEFAULT_VALUE))); - URI lAudioVideoPublicUri = URI.create(aConfigurator.getProperty(MediaResourceService.AUDIO_VIDEO_PUBLIC_URI,"udp://"+InetAddress.getLocalHost().getHostAddress()+":"+lAudioVideoLocalPort)); - mConfig = new RtpRelayServerConfig(new InetSocketAddress(lAudioVideoPublicUri.getHost(),lAudioVideoPublicUri.getPort()) - ,new InetSocketAddress(lAudioVideoLocalPort)); - mUdpSessionForStunRtp = new GenericUdpSession(new InetSocketAddress(lAudioVideoLocalPort)); - mRtpRelayServer = new RtpRelayServer(mUdpSessionForStunRtp.getSocket(),1000,1000); - mUdpSessionForStunRtp.addMessageHandler(mRtpRelayServer); - mSturServer = new StunServer(mUdpSessionForStunRtp.getSocket()); - mUdpSessionForStunRtp.addMessageHandler(mSturServer); - mJxtaNetworkManager = aJxtaNetworkManager; - } - - public void start(long timeOut) throws P2pProxyException { - mPublishTask = new TimerTask() { - - @Override - public void run() { - try { - mStunRtpServerAdvertisement = (NetworkResourceAdvertisement) AdvertisementFactory.newAdvertisement(NetworkResourceAdvertisement.getAdvertisementType()); - mStunRtpServerAdvertisement.setAddress("udp://"+mConfig.getAudioVideoPublicSocketAddress().getAddress().getHostAddress()+":"+mConfig.getAudioVideoPublicSocketAddress().getPort()); - mStunRtpServerAdvertisement.setID(IDFactory.newCodatID(mJxtaNetworkManager.getPeerGroup().getPeerGroupID(), Integer.toHexString(mStunRtpServerAdvertisement.getAddress().hashCode()).getBytes("US-ASCII"))); - mStunRtpServerAdvertisement.setName(ADV_NAME); - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().publish(mStunRtpServerAdvertisement,ADV_LIFE_TIME,ADV_LIFE_TIME/2); - mLog.info(mStunRtpServerAdvertisement + "published"); - - } catch (Exception e) { - mLog.error("Cannot publish StunRtpServerAdvertisement", e); - } - - } - - }; - mPublishTimer.scheduleAtFixedRate(mPublishTask, 0, ADV_LIFE_TIME - ADV_LIFE_TIME/10); - } - - public void stop() { - try { - mPublishTask.cancel(); - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().flushAdvertisement(mStunRtpServerAdvertisement); - mUdpSessionForStunRtp.close(); - } catch (Exception e) { - mLog.error("cannot stop MediaResourceService",e); - } - - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/MediaResoureUnreachableException.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/MediaResoureUnreachableException.java deleted file mode 100644 index a809879c..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/MediaResoureUnreachableException.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.linphone.p2pproxy.core.media; - -import org.linphone.p2pproxy.api.P2pProxyException; - -public class MediaResoureUnreachableException extends P2pProxyException { - - private String mRourceAddress; - public MediaResoureUnreachableException() { - super(); - // TODO Auto-generated constructor stub - } - - public MediaResoureUnreachableException(String arg0, Throwable arg1) { - super(arg0, arg1); - // TODO Auto-generated constructor stub - } - - public MediaResoureUnreachableException(String arg0) { - super(arg0); - // TODO Auto-generated constructor stub - } - - public MediaResoureUnreachableException(Throwable arg0) { - super(arg0); - // TODO Auto-generated constructor stub - } - public void setRourceAddress(String anAddress) { - mRourceAddress = anAddress; - } - public String getResourceAddress() { - return mRourceAddress; - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/RtpSession.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/RtpSession.java deleted file mode 100644 index fa71f738..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/RtpSession.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.linphone.p2pproxy.core.media.jxtaudpproxy; - -import java.net.InetSocketAddress; - -public interface RtpSession { - - public abstract void setRemoteAddress(InetSocketAddress aRemoteAddress); - -} \ No newline at end of file diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/RtpSessionImpl.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/RtpSessionImpl.java deleted file mode 100644 index 6f0b5ae3..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/RtpSessionImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -UdpSession.java - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.jxtaudpproxy; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.net.SocketException; -import java.net.UnknownHostException; - -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.socket.JxtaSocket; - - -public class RtpSessionImpl implements PipeMsgListener, RtpSession{ - UdpSession mRtpChannel = null; - UdpSession mRtcpChannel = null; - int mLocalRtpPort; - - public RtpSessionImpl(int portStart, String aDomaineName) throws IOException { - mLocalRtpPort = portStart; - while (mRtpChannel == null) { - try { - mRtpChannel = new UdpSession(mLocalRtpPort ,aDomaineName+"-RTP"); - mRtcpChannel = new UdpSession(mLocalRtpPort +1 ,aDomaineName+"-RCTP"); - }catch (Exception e) { - //nop already used - mLocalRtpPort += 2; - } - - } - } - /* (non-Javadoc) - * @see org.linphone.p2pproxy.core.jxtaudpproxy.RtpSession#setRemoteAddress(java.net.InetSocketAddress) - */ - public void setRemoteAddress( InetSocketAddress aRemoteAddress) { - mRtpChannel.setRemoteAddress(aRemoteAddress); - InetSocketAddress lRtcpInetSocketAddress = new InetSocketAddress(aRemoteAddress.getAddress(),aRemoteAddress.getPort() + 1); - mRtcpChannel.setRemoteAddress(lRtcpInetSocketAddress); - } - public void setRemotePipe(OutputPipe aRemotePipe) { - mRtpChannel.setRemotePipe(aRemotePipe); - mRtcpChannel.setRemotePipe(aRemotePipe); - } - public void close() { - mRtpChannel.close(); - mRtcpChannel.close(); - } - public int getPort() { - return mRtpChannel.getPort(); - } - public String toString() { - return "rtp ["+mRtpChannel+"] rtcp "+mRtcpChannel+"]"; - } - public void pipeMsgEvent(PipeMsgEvent event) { - mRtpChannel.pipeMsgEvent(event); - mRtcpChannel.pipeMsgEvent(event); - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/SdpProcessorImpl.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/SdpProcessorImpl.java deleted file mode 100644 index 36da0dc2..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/SdpProcessorImpl.java +++ /dev/null @@ -1,190 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -SdpProcessorImpl.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.jxtaudpproxy; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.Map; - -import net.jxta.pipe.OutputPipe; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.Configurator; - -import org.linphone.p2pproxy.core.sipproxy.SdpProcessor; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar.Registration; -import org.linphone.p2pproxy.core.sipproxy.peers.NetworkResources; -import org.zoolu.sdp.AttributeField; -import org.zoolu.sdp.ConnectionField; -import org.zoolu.sdp.MediaDescriptor; -import org.zoolu.sdp.MediaField; -import org.zoolu.sdp.SessionDescriptor; -import org.zoolu.sip.message.Message; - -public class SdpProcessorImpl implements SdpProcessor { - private final static Logger mLog = Logger.getLogger(SdpProcessorImpl.class); - private final Map mRegistrationTab; - private final Configurator mProperties; - public SdpProcessorImpl(Map aRegistrationTab,Configurator aProperties) { - mRegistrationTab = aRegistrationTab; - mProperties = aProperties;; - } - /* - * process SDP in mode relay - * rewrite sdp. - */ - public void processSdpBeforeSendingToSipUA( Message aMessage) throws P2pProxyException { - try { - //check if sdp present - if (aMessage.hasBody() && "application/sdp".equals(aMessage.getBodyType())) { - SessionDescriptor lOrigSessionDescriptor = new SessionDescriptor(aMessage.getBody()); - SessionDescriptor lNewSessionDescriptor = new SessionDescriptor(aMessage.getBody()); - lNewSessionDescriptor.removeMediaDescriptors(); - lNewSessionDescriptor.setConnection(null); - - String lUserName=""; - if (aMessage.isInvite()) { - lUserName = aMessage.getToHeader().getNameAddress().getAddress().toString(); - } else if (aMessage.isResponse()) { - lUserName = aMessage.getFromHeader().getNameAddress().getAddress().toString(); - } else if (aMessage.isAck()) { - lUserName = aMessage.getToHeader().getNameAddress().getAddress().toString(); - } else { - mLog.warn("strange, sdp in message ["+aMessage+"]"); - } - // build rtp session if required - NetworkResources lNetworkResources = buildRtpSessions(lOrigSessionDescriptor, lUserName); - - for (Object lMediaDescriptorObject :lOrigSessionDescriptor.getMediaDescriptors()) { - MediaDescriptor lMediaDescriptor = (MediaDescriptor)lMediaDescriptorObject; - RtpSessionImpl lRtpSession = lNetworkResources.getRtpSession(lMediaDescriptor.getMedia().getMedia()); - // create new media desc - ConnectionField lConnectionField = new ConnectionField("IP4",InetAddress.getLocalHost().getHostAddress()); - MediaField lOrigMediaField = lMediaDescriptor.getMedia(); - MediaField lNewMediaField = new MediaField(lOrigMediaField.getMedia() - , lRtpSession.getPort() //new port - , 0 - , lOrigMediaField.getTransport() - , lOrigMediaField.getFormatList()); - MediaDescriptor lNewMediaDescriptor = new MediaDescriptor(lNewMediaField,lConnectionField); - for (Object lAttributeField:lMediaDescriptor.getAttributes()) { - lNewMediaDescriptor.addAttribute((AttributeField) lAttributeField); - } - lNewSessionDescriptor.addMediaDescriptor(lNewMediaDescriptor); - - } - aMessage.setBody(lNewSessionDescriptor.toString()); - mLog.debug("new sdp:" +aMessage.getBody()); - - } - }catch (Exception e) { - throw new P2pProxyException(e); - } - - } - public void processSdpAfterSentToPipe( Message aMessage,OutputPipe lOutputPipe) throws P2pProxyException { - try { - if (aMessage.hasBody() && "application/sdp".equals(aMessage.getBodyType())) { - SessionDescriptor lOrigSessionDescriptor = new SessionDescriptor(aMessage.getBody()); - String lUserName=""; - if (aMessage.isInvite()) { - lUserName = aMessage.getFromHeader().getNameAddress().getAddress().toString(); - } else if (aMessage.isResponse()) { - lUserName = aMessage.getToHeader().getNameAddress().getAddress().toString(); - } else if (aMessage.isAck()) { - lUserName = aMessage.getFromHeader().getNameAddress().getAddress().toString(); - } else { - mLog.warn("strange, sdp in message ["+aMessage+"]"); - } - // build rtp session if required - NetworkResources lNetworkResources = buildRtpSessions(lOrigSessionDescriptor, lUserName,lOutputPipe); - - // check remote address - ConnectionField lConnectionField = lOrigSessionDescriptor.getConnection(); - //search from m blocs - for (Object lMediaDescriptorObject :lOrigSessionDescriptor.getMediaDescriptors()) { - MediaDescriptor lMediaDescriptor = (MediaDescriptor)lMediaDescriptorObject; - if (lConnectionField == null ) { - lConnectionField = lMediaDescriptor.getConnection(); - } - RtpSession lRtpSession = lNetworkResources.getRtpSession(lMediaDescriptor.getMedia().getMedia()); - InetAddress lInetAddress = InetAddress.getByName(lConnectionField.getAddress()); - InetSocketAddress lInetSocketAddress = new InetSocketAddress(lInetAddress,lMediaDescriptor.getMedia().getPort()); - lRtpSession.setRemoteAddress(lInetSocketAddress); - mLog.info("rtp session updated ["+lRtpSession+"]"); - } - // - - } - }catch (Exception e) { - throw new P2pProxyException(e); - } - - } - private NetworkResources buildRtpSessions(SessionDescriptor lSessionDescriptor , String aFrom) throws P2pProxyException { - return buildRtpSessions(lSessionDescriptor , aFrom,null); - } - private NetworkResources buildRtpSessions(SessionDescriptor lSessionDescriptor , String aFrom,OutputPipe aRemotePipe) throws P2pProxyException { - try { - // get Registration - Registration lRegistration = mRegistrationTab.get(aFrom); - - for (Object lMediaDescriptorObject :lSessionDescriptor.getMediaDescriptors()) { - MediaDescriptor lMediaDescriptor = (MediaDescriptor)lMediaDescriptorObject; - //1 check if port != 0 - if (lMediaDescriptor.getMedia().getPort() == 0) { - // nothing to change, offers rejected - break; - } - //3 open datagram socket - if (lMediaDescriptor.getMedia().getTransport().equalsIgnoreCase("RTP/AVP") == false) { - mLog.warn("enable to process non udp mlines ["+lMediaDescriptor.getMedia().getTransport()+"]"); - break; - } - - String lMLineName = lMediaDescriptor.getMedia().getMedia(); - RtpSessionImpl lRtpSession = null; - if (((NetworkResources) lRegistration.NetResources).hasRtpSession(lMLineName) == false) { - // first time, just create - int lPortStart = 15000; - lRtpSession = new RtpSessionImpl (lPortStart,lMLineName); - ((NetworkResources) lRegistration.NetResources).putRtpSession(lMLineName, lRtpSession); - } else { - lRtpSession = ((NetworkResources) lRegistration.NetResources).getRtpSession(lMLineName); - } - if (aRemotePipe != null) { - lRtpSession.setRemotePipe(aRemotePipe); - } - - } - return (NetworkResources) lRegistration.NetResources; - }catch (Exception e) { - throw new P2pProxyException(e); - } - - } - public void processSdpBeforeSendingToPipe(Message message) throws P2pProxyException { - // TODO Auto-generated method stub - - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/UdpSession.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/UdpSession.java deleted file mode 100644 index 312b8996..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/jxtaudpproxy/UdpSession.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.linphone.p2pproxy.core.media.jxtaudpproxy; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketException; -import java.net.UnknownHostException; -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.core.GenericUdpSession; - -import net.jxta.endpoint.ByteArrayMessageElement; -import net.jxta.endpoint.MessageElement; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; - -public class UdpSession implements GenericUdpSession.MessageHandler ,PipeMsgListener{ - private final static Logger mLog = Logger.getLogger(UdpSession.class); - private InetSocketAddress mRemoteAddress; - private OutputPipe mRemotePipe; - private boolean mExit = false; - private final String mMessageName; - private final GenericUdpSession mGenericUdpSession; - UdpSession(int aPort,String aMessageName) throws SocketException, UnknownHostException { - mMessageName = aMessageName; - mGenericUdpSession = new GenericUdpSession(new InetSocketAddress(aPort),this); - } - - - - public void pipeMsgEvent(PipeMsgEvent event) { - MessageElement lMessageElement = event.getMessage().getMessageElement(mMessageName); - if (lMessageElement == null) { - //nop, this is not for me - return; - } - //test if we have an address to forward to - if (mRemoteAddress == null) { - mLog.warn("no remote adress, message discarded"); - return; - } - byte[] lBuff = lMessageElement.getBytes(false); - DatagramPacket lDatagramPacket = new DatagramPacket(lBuff,(int) lMessageElement.getByteLength()); - lDatagramPacket.setSocketAddress(mRemoteAddress); - try { - mGenericUdpSession.getSocket().send(lDatagramPacket); - mLog.debug("message from ["+mMessageName+"] sent to ["+mRemoteAddress+"]"); - } catch (IOException e) { - mLog.error("cannot send message for session ["+this+"]" , e); - } - // - } - public void setRemoteAddress( InetSocketAddress aRemoteAddress) { - mRemoteAddress = aRemoteAddress; - } - public void setRemotePipe(OutputPipe aRemotePipe) { - mRemotePipe = aRemotePipe; - } - public void close() { - mExit = true; - mGenericUdpSession.close(); - } - - public String toString() { - return "name ["+mMessageName +"] udp dest ["+mRemoteAddress+"]"; - } - public int getPort() { - return mGenericUdpSession.getSocket().getPort(); - } - public void onMessage(DatagramPacket message) { - try { - // if destination is known just send - if (mRemotePipe != null) { - net.jxta.endpoint.Message lMessage = new net.jxta.endpoint.Message(); - ByteArrayMessageElement lByteArrayMessageElement = new ByteArrayMessageElement(mMessageName, null,message.getData(),0,message.getLength(), null); - lMessage.addMessageElement(mMessageName, lByteArrayMessageElement); - //send the message - mRemotePipe.send(lMessage); - mLog.debug("message from ["+message.getAddress()+":"+message.getPort()+"]sent to ["+mRemotePipe.getPipeID()+"]"); - } else { - mLog.warn("output pipe not set for ["+this+"], discarding message"); - } - }catch(Exception e) { - //nop - } - - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/AddressRequest.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/AddressRequest.java deleted file mode 100644 index 4bc2f3eb..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/AddressRequest.java +++ /dev/null @@ -1,32 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -RouteAddRequest.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.rtprelay; - -import java.io.Serializable; -import java.net.SocketAddress; - -public class AddressRequest implements Serializable { - private static final long serialVersionUID = 1L; - - public AddressRequest() { - - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/AddressResponse.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/AddressResponse.java deleted file mode 100644 index c4006979..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/AddressResponse.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -RouteAddResponse.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.rtprelay; - -import java.io.Serializable; -import java.net.InetSocketAddress; -import java.util.Map; - -public class AddressResponse implements Serializable { - private static final long serialVersionUID = 1L; - private final Map mAddressTable; - public AddressResponse(Map anAddressTable) { - mAddressTable = anAddressTable; - } - /** - * @return Returns the mMediaType. - */ - public Map getAddressTable() { - return mAddressTable; - } - - public String toString() { - StringBuffer lReturnString = new StringBuffer(); - for (MediaType lMediaType:mAddressTable.keySet()) { - lReturnString.append(mAddressTable.get(lMediaType)+" for type "+lMediaType+" :"); - } - return lReturnString.toString(); - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/IceSdpProcessorImpl.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/IceSdpProcessorImpl.java deleted file mode 100644 index 7a0b793d..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/IceSdpProcessorImpl.java +++ /dev/null @@ -1,222 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -SdpProcessorImpl.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.rtprelay; - -import java.net.InetSocketAddress; -import java.util.Map; -import java.util.StringTokenizer; - -import net.jxta.pipe.OutputPipe; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyRtpRelayManagement; -import org.linphone.p2pproxy.core.sipproxy.SdpProcessor; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar.Registration; -import org.zoolu.sdp.AttributeField; -import org.zoolu.sdp.ConnectionField; -import org.zoolu.sdp.MediaDescriptor; -import org.zoolu.sdp.MediaField; -import org.zoolu.sdp.SessionDescriptor; -import org.zoolu.sip.message.Message; - -/** - * rewrite SDP to insert an ICE aware rtp relay - * - * - */ -public class IceSdpProcessorImpl implements SdpProcessor { - private final String CANDIDATE_RELAY_NAME="relay"; - - class CandidateAttributeParser { - final private String mCandidateAttribute; - - final private String mfoundation; - final private String mComponentId; - final private String mTransport; - final private String mPriority; - final private String mConnectionAddress; - final private String mPort; - final private String mType; - - public CandidateAttributeParser(String aCandidateAttribute){ - mCandidateAttribute = aCandidateAttribute; - StringTokenizer st = new StringTokenizer(mCandidateAttribute); - mfoundation = st.nextToken(); - mComponentId = st.nextToken(); - mTransport = st.nextToken(); - mPriority = st.nextToken(); - mConnectionAddress = st.nextToken(); - mPort = st.nextToken(); - st.nextToken(); //skip typ - mType = st.nextToken();; - } - public CandidateAttributeParser(InetSocketAddress aRelayAddress){ - mfoundation = "3"; - mComponentId = "1"; - mTransport = "UDP"; - mPriority = "0"; - mConnectionAddress = aRelayAddress.getAddress().getHostAddress(); - mPort = String.valueOf(aRelayAddress.getPort()); - mType = CANDIDATE_RELAY_NAME; - mCandidateAttribute = toString(); - } - - InetSocketAddress getAddress() { - return new InetSocketAddress(mConnectionAddress,Integer.parseInt(mPort)); - } - public String toString() { - return mfoundation +" "+ mComponentId +" "+ mTransport +" "+ mPriority +" "+ mConnectionAddress +" "+ mPort +" typ " +mType; - } - } - - private final static Logger mLog = Logger.getLogger(IceSdpProcessorImpl.class); - private final Map mRegistrationTab; - private final P2pProxyRtpRelayManagement mP2pProxyRtpRelayManagement; - public IceSdpProcessorImpl(Map aRegistrationTab,P2pProxyRtpRelayManagement aP2pProxyRtpRelayManagement) { - mRegistrationTab = aRegistrationTab; - mP2pProxyRtpRelayManagement = aP2pProxyRtpRelayManagement; - - } - public void processSdpAfterSentToPipe(Message message, OutputPipe outputPipe) - throws P2pProxyException { - //nop - - } - - public void processSdpBeforeSendingToSipUA(Message aMessage) throws P2pProxyException { - String lUserName=""; - if (aMessage.isInvite()) { - lUserName = aMessage.getToHeader().getNameAddress().getAddress().toString(); - } else if (aMessage.isResponse()) { - lUserName = aMessage.getFromHeader().getNameAddress().getAddress().toString(); - } else if (aMessage.isAck()) { - lUserName = aMessage.getToHeader().getNameAddress().getAddress().toString(); - } else { - mLog.warn("strange, sdp in message ["+aMessage+"]"); - } - processSdp(aMessage,lUserName); - } - - public void processSdpBeforeSendingToPipe(Message aMessage) throws P2pProxyException { - String lUserName=""; - if (aMessage.isInvite()) { - lUserName = aMessage.getFromHeader().getNameAddress().getAddress().toString(); - } else if (aMessage.isResponse()) { - lUserName = aMessage.getToHeader().getNameAddress().getAddress().toString(); - } else if (aMessage.isAck()) { - lUserName = aMessage.getFromHeader().getNameAddress().getAddress().toString(); - } else { - mLog.warn("strange, sdp in message ["+aMessage+"]"); - } - processSdp(aMessage,lUserName); - } - - //check if already have relay candidate - //1 search for relay if not available - //2 rewrite c line /port - //3 add candidate - //4 if relay was available, clean relay - private void processSdp(Message aMessage, String aUserName) throws P2pProxyException { - //check if sdp present - if (aMessage.hasBody() && "application/sdp".equals(aMessage.getBodyType())) { - SessionDescriptor lOrigSessionDescriptor = new SessionDescriptor(aMessage.getBody()); - - SessionDescriptor lNewSessionDescriptor = new SessionDescriptor(aMessage.getBody()); - lNewSessionDescriptor.removeMediaDescriptors(); - lNewSessionDescriptor.setConnection(null); - - // get Registration - Registration lRegistration = mRegistrationTab.get(aUserName); - if (lRegistration == null) { - throw new P2pProxyException("unknown user ["+aUserName+"]"); - } - boolean lrelayCandidateDetected = false; - //check if already have relay candidate - for (Object lMediaDescriptorObject :lOrigSessionDescriptor.getMediaDescriptors()) { - MediaDescriptor lMediaDescriptor = (MediaDescriptor)lMediaDescriptorObject; - MediaType lMediaType = MediaType.parseString(lMediaDescriptor.getMedia().getMedia()); - String lRelayCandidateValue = getRelayCandidate(lMediaDescriptor); - - if (lRelayCandidateValue != null) { - if (lRegistration.RtpRelays.containsKey(lMediaType) == false) {// get relay address from from candidate - CandidateAttributeParser lCandidateAttributeParser = new CandidateAttributeParser(lRelayCandidateValue); - lRegistration.RtpRelays.put(lMediaType, lCandidateAttributeParser.getAddress()); - mLog.info("relay candidate detected, adding relay ["+lCandidateAttributeParser.getAddress()+" for ["+lMediaDescriptor.getMedia().getMedia()+"]"); - } else { - lRegistration.RtpRelays.remove(lMediaType); - mLog.info("relay candidate removing address "); - } - lrelayCandidateDetected = true; - } else { - InetSocketAddress lInetSocketAddress=null; - if (lRegistration.RtpRelays.containsKey(lMediaType) == false) { - //put relay candidate from network - lRegistration.RtpRelays = mP2pProxyRtpRelayManagement.getAddresses(); - lInetSocketAddress = lRegistration.RtpRelays.get(lMediaType); - } else { - lInetSocketAddress = lRegistration.RtpRelays.get(lMediaType); - lRegistration.RtpRelays.remove(lMediaType); - mLog.info("no relay candidate relay removing address "); - } - - // build candidate attribute - CandidateAttributeParser lCandidateAttributeParser = new CandidateAttributeParser(lInetSocketAddress ); - // create new media desc - ConnectionField lConnectionField = new ConnectionField("IP4",lInetSocketAddress.getAddress().getHostAddress()); - MediaField lOrigMediaField = lMediaDescriptor.getMedia(); - MediaField lNewMediaField = new MediaField(lOrigMediaField.getMedia() - , lInetSocketAddress.getPort() //new port - , 0 - , lOrigMediaField.getTransport() - , lOrigMediaField.getFormatList()); - MediaDescriptor lNewMediaDescriptor = new MediaDescriptor(lNewMediaField,lConnectionField); - for (Object lAttributeField:lMediaDescriptor.getAttributes()) { - lNewMediaDescriptor.addAttribute((AttributeField) lAttributeField); - } - // add relay candidate - AttributeField lAttributeField = new AttributeField("candidate", lCandidateAttributeParser.toString()); - lNewMediaDescriptor.addAttribute(lAttributeField); - lNewSessionDescriptor.addMediaDescriptor(lNewMediaDescriptor); - } - - } - if (lrelayCandidateDetected == false) { - //to work-around mjsip bug - lNewSessionDescriptor.setConnection(((MediaDescriptor)lNewSessionDescriptor.getMediaDescriptors().elementAt(0)).getConnection()); - aMessage.setBody(lNewSessionDescriptor.toString()); - mLog.debug("new sdp:" +aMessage.getBody()); - } - - } - } - - private String getRelayCandidate(MediaDescriptor aMediaDescriptor) { - //1 get candidate - for (Object lField:aMediaDescriptor.getAttributes()) { - AttributeField lAttributeField = (AttributeField)lField; - if (lAttributeField.getAttributeName().equalsIgnoreCase("candidate") && lAttributeField.getAttributeValue().contains(CANDIDATE_RELAY_NAME)) { - return lAttributeField.getAttributeValue(); - } - } - return null; - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/MediaType.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/MediaType.java deleted file mode 100644 index 3761b885..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/MediaType.java +++ /dev/null @@ -1,38 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -MediaType.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.rtprelay; - -import org.linphone.p2pproxy.api.P2pProxyException; - -public enum MediaType { - audio,video,any; - static MediaType parseString (String value) throws P2pProxyException{ - if ("audio".equals(value)) { - return audio; - } else if("video".equals(value)) { - return video; - } else if("any".equals(value)) { - return any; - } else { - throw new P2pProxyException("unknown media type ["+value+"]"); - } - } -} - diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RouteAddRequest.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RouteAddRequest.java deleted file mode 100644 index 7bf52c51..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RouteAddRequest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -RouteAddRequest.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.rtprelay; - -import java.io.Serializable; -import java.net.SocketAddress; - -public class RouteAddRequest implements Serializable { - private final SocketAddress mSource; - private final SocketAddress mDest; - private final MediaType mMediaType; - private static final long serialVersionUID = 1L; - public RouteAddRequest(SocketAddress aSource, SocketAddress aDest,MediaType aMediaType) { - mSource = aSource; - mDest = aDest; - mMediaType = aMediaType; - } - /** - * @return Returns the mSource. - */ - public SocketAddress getSource() { - return mSource; - } - /** - * @return Returns the mDest. - */ - public SocketAddress getDest() { - return mDest; - } - /** - * @return Returns the mMediaType. - */ - public MediaType getMediaType() { - return mMediaType; - } - public String toString() { - return "source ["+mSource+"] dest ["+mDest+"] type ["+mMediaType+"]"; - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RouteAddResponse.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RouteAddResponse.java deleted file mode 100644 index 106cf1b1..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RouteAddResponse.java +++ /dev/null @@ -1,50 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -RouteAddResponse.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.rtprelay; - -import java.io.Serializable; -import java.net.SocketAddress; - -public class RouteAddResponse implements Serializable { - private static final long serialVersionUID = 1L; - private final SocketAddress mSocketAddress; - private final MediaType mMediaType; - - public RouteAddResponse(SocketAddress aSocketAddress,MediaType aMediaType) { - mSocketAddress = aSocketAddress; - mMediaType =aMediaType; - } - public String toString() { - return "sdp adress ["+mSocketAddress+"] type ["+mMediaType+"]"; - } - /** - * @return Returns the mMediaType. - */ - public MediaType getMediaType() { - return mMediaType; - } - /** - * @return Returns the mSocketAddress. - */ - public SocketAddress getSocketAddress() { - return mSocketAddress; - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RoutingTable.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RoutingTable.java deleted file mode 100644 index c1afd50c..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RoutingTable.java +++ /dev/null @@ -1,60 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -RoutingTable.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.rtprelay; - - -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; - -public class RoutingTable implements RtpRoutingRules { - private final static Logger mLog = Logger.getLogger(RoutingTable.class); - static private RoutingTable mInstance = new RoutingTable(); - private final Map mTable = new HashMap(); - - private RoutingTable() { - - } - static public RoutingTable getInstance() { - return mInstance; - } - /** - * @param aSource - * @return null if not found - */ - public SocketAddress getRoute(SocketAddress aSource) { - return mTable.get(aSource); - } - public void addRoute(int anSsrc, InetSocketAddress source) { - mLog.info("route for ["+anSsrc+"] dest ["+source+"] added"); - - } - public SocketAddress getRoute(int anSsrc) throws P2pProxyException { - // TODO Auto-generated method stub - return null; - } - public void removeRoute(int anSsrc) { - mLog.info("route for ["+anSsrc+"] removed"); - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RtpRelayServer.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RtpRelayServer.java deleted file mode 100644 index 9f8fc1fa..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RtpRelayServer.java +++ /dev/null @@ -1,334 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -UdpSession.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.rtprelay; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.GenericUdpSession; - - - -public class RtpRelayServer implements GenericUdpSession.MessageHandler { - private final static Logger mLog = Logger.getLogger(RtpRelayServer.class); - private final DatagramSocket mSocket; - - - class RoutingTable { - class GarbageCollectorTask extends TimerTask { - - public void run() { - synchronized (RtpRelayServer.RoutingTable.this) { - for (RoutingElement lElement :new HashMap (mSessionIdTable).values()) { - if (System.currentTimeMillis() - lElement.getLastAccess() > mMaxSilenceDuration) { - mLog.info("removing element ["+lElement+"]"); - mSessionIdTable.remove(lElement.mSessionId); - mSsrcElementTable.remove(lElement.mSsrcA); - mSsrcElementTable.remove(lElement.mSsrcB); - } - } - } - } - } - class RoutingElement { - //private final String mSessionId; - private SocketAddress mPeerARtp; - private SocketAddress mPeerARtcp; - private long mSsrcA; - private SocketAddress mPeerBRtp; - private SocketAddress mPeerBRtcp; - private long mSsrcB; - private long mLastDestAddressAccess = System.currentTimeMillis(); - private final String mSessionId; - RoutingElement(long aSsrc, String aSessionId) { - mSsrcA = aSsrc; - mSessionId = aSessionId; - } - void setPeerAddress(SocketAddress aReceivedAddress,long aSsrc,boolean isRtcp) { - if (aSsrc == mSsrcA ) { - if (isRtcp) { - mPeerARtcp = aReceivedAddress; - } else { - mPeerARtp = aReceivedAddress; - } - } else if (aSsrc == mSsrcB) { - if (isRtcp) { - mPeerBRtcp = aReceivedAddress; - } else { - mPeerBRtp = aReceivedAddress; - } - } else { - mLog.warn("ssrc ["+aSsrc+" not found for ["+aReceivedAddress+"]"); - } - } - void setPeerBSsrc(long aSsrc) { - mSsrcB = aSsrc; - } - public SocketAddress getDestAddr(long aSourceSsrc,boolean isRtcp) throws P2pProxyException{ - mLastDestAddressAccess = System.currentTimeMillis(); - if (aSourceSsrc == mSsrcA && isRtcp) { - if ( mPeerBRtcp != null) { - return mPeerBRtcp ; - } else { - throw new P2pProxyException("PeerBRtcp not found for ssrc ["+aSourceSsrc+"]"); - } - } else if (aSourceSsrc == mSsrcA && !isRtcp) { - - if ( mPeerBRtp != null) { - return mPeerBRtp ; - } else { - throw new P2pProxyException("PeerBRtp not found for ssrc ["+aSourceSsrc+" "); - } - } else if (aSourceSsrc == mSsrcB && isRtcp) { - - if ( mPeerARtcp != null) { - return mPeerARtcp ; - } else { - throw new P2pProxyException("PeerARtcp not found for ssrc ["+aSourceSsrc+" "); - } - } else if (aSourceSsrc == mSsrcB && !isRtcp) { - - if ( mPeerARtp != null) { - return mPeerARtp ; - } else { - throw new P2pProxyException("PeerARtp not found for ssrc ["+aSourceSsrc+" "); - } - }else { - throw new P2pProxyException("ssrc ["+aSourceSsrc+" not found"); - } - - } - public long getLastAccess() { - return mLastDestAddressAccess; - } - public String toString() { - return "Session id ["+mSessionId+"] ssrc a ["+mSsrcA+"] rtp source ["+mPeerARtp+"] rtcp source ["+mPeerARtcp+"]" - +"ssrc b ["+mSsrcB+"] rtp source ["+mPeerBRtp+"] rtcp source ["+mPeerBRtcp+"]"; - } - } - private final Map mSessionIdTable = new HashMap (); - private final Map mSsrcElementTable = new HashMap (); - private final long mMaxSilenceDuration ; - private final long mGCPeriod; - Timer mTimer = new Timer("Routing Elements GC"); - - public RoutingTable (long aMaxSilenceDuration, long aGCPeriod) { - mMaxSilenceDuration = aMaxSilenceDuration; - mGCPeriod = aGCPeriod; - mTimer.scheduleAtFixedRate(new GarbageCollectorTask(), 0, mGCPeriod); - } - public synchronized boolean containsSessionId(String aSessionId) { - return mSessionIdTable.containsKey(aSessionId); - } - - public synchronized void addRoutingElement(String aSessionId, long aSsrc) { - if (mLog.isInfoEnabled()) mLog.info("add routing element for session id ["+aSessionId+"] with ssrc ["+aSsrc+"]"); - RoutingElement lRoutingElement = new RoutingElement(aSsrc,aSessionId); - mSessionIdTable.put(aSessionId, lRoutingElement); - mSsrcElementTable.put(aSsrc, lRoutingElement); - } - - public synchronized void UpdateRoutingElement(String aSessionId, long aSsrc) { - if (mLog.isInfoEnabled()) mLog.info("update routing element session id ["+aSessionId+"] with ssrc ["+aSsrc+"]"); - RoutingElement lRoutingElement = mSessionIdTable.get(aSessionId); - lRoutingElement.setPeerBSsrc(aSsrc); - mSsrcElementTable.put(aSsrc, lRoutingElement); - - } - - public synchronized void updateSourceAddress(long aSsrc, SocketAddress aSocketAddress,boolean isRtcp) throws P2pProxyException{ - if (mSsrcElementTable.containsKey(aSsrc) == false) { - throw new P2pProxyException("No routing element present for ssrc["+aSsrc+"]"); - } - if (mLog.isInfoEnabled()) mLog.info("update routing element for ssrc ["+aSsrc+"] with address ["+aSocketAddress+"]" ); - RoutingElement lRoutineElement = mSsrcElementTable.get(aSsrc); - lRoutineElement.setPeerAddress(aSocketAddress, aSsrc, isRtcp); - } - public synchronized SocketAddress getDestAddress(long aSsrc,boolean isRtcp) throws P2pProxyException{ - //1 check if element exist for this ssrc - if (mSsrcElementTable.containsKey(aSsrc) == false) { - throw new P2pProxyException("No routing element present for ssrc["+aSsrc+"]"); - } - RoutingElement lRoutingElement = mSsrcElementTable.get(aSsrc); - return lRoutingElement.getDestAddr(aSsrc, isRtcp); - } - public synchronized int getSize() { - return mSessionIdTable.size(); - } - } - - - - private static final String SESSIONID_NAME="RSID"; //Relay session Id - private final RoutingTable mRoutingTable; - public RtpRelayServer(DatagramSocket aListeningSocket) throws SocketException, UnknownHostException { - this(aListeningSocket,3600000,60000); - } - public RtpRelayServer(DatagramSocket aListeningSocket,long aMaxSilenceDuration, long aGCPeriod) throws SocketException, UnknownHostException { - mRoutingTable = new RoutingTable(aMaxSilenceDuration,aGCPeriod); - mSocket = aListeningSocket; - - } - public void onMessage(DatagramPacket aMessage) { - try { - if (mLog.isInfoEnabled()) mLog.info("new incoming message from ["+aMessage.getSocketAddress()+"]"); - if (isRtpRtcpPacket(aMessage) == false) { - if (mLog.isInfoEnabled()) mLog.info("not rtp/rtcp packet skip"); - return; - } - long lSsrc = getSsrc(aMessage); - if (isSessionIdPresent(aMessage)) { - String lSessionId = getSessionId(aMessage); - //1 check if already exist - if (mRoutingTable.containsSessionId(lSessionId)) { - //second call, update ssrc - mRoutingTable.UpdateRoutingElement(lSessionId,lSsrc); - - } else { - //first call - mRoutingTable.addRoutingElement(lSessionId,lSsrc); - } - } - mRoutingTable.updateSourceAddress(lSsrc, aMessage.getSocketAddress(),isRtcp(aMessage)); - - SocketAddress lDestAddress = mRoutingTable.getDestAddress(lSsrc,isRtcp(aMessage)); - //does not forward session id msg - if (!isSessionIdPresent(aMessage)) { - // ok forwarding - if (mLog.isInfoEnabled()) mLog.info("forwarding ["+aMessage.getLength()+"] bytes from ["+aMessage.getSocketAddress()+"] to ["+lDestAddress+"]"); - aMessage.setSocketAddress(lDestAddress); - mSocket.send(aMessage); - } - } catch (IOException e) { - mLog.error("cannot forward ["+aMessage+"]", e); - } catch (Exception e) { - mLog.warn("unknown destination for message from ["+aMessage.getSocketAddress()+"] discarding",e); - - } - } - public InetSocketAddress getInetSocketAddress() { - return (InetSocketAddress) mSocket.getLocalSocketAddress(); - } - - private long getSsrc(DatagramPacket aMessage) { -// The RTP header has the following format: -// -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// |V=2|P|X| CC |M| PT | sequence number | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | timestamp | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | synchronization source (SSRC) identifier | -// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ -// | contributing source (CSRC) identifiers | -// | .... | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - if (isRtcp(aMessage)) { - //rtcp packet - return b2UB(aMessage.getData()[7]) - + (b2UB(aMessage.getData()[6]) << 8) - + (b2UB(aMessage.getData()[5]) << 16) - + (b2UB(aMessage.getData()[4]) << 24); - } else { - //rtp packet - return b2UB(aMessage.getData()[11]) - + (b2UB(aMessage.getData()[10]) << 8) - + (b2UB(aMessage.getData()[9]) << 16) - + (b2UB(aMessage.getData()[8]) << 24); - } - - } - private boolean isSessionIdPresent(DatagramPacket aMessage) { -// APP: Application-Defined RTCP Packet -// -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// |V=2|P| subtype | PT=APP=204 | length | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | SSRC/CSRC | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | name (ASCII) | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | application-dependent data ... -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - if (b2UB(aMessage.getData()[1]) != 204) return false; - String aName = String.valueOf((char)b2UB(aMessage.getData()[8])) - + String.valueOf((char)b2UB(aMessage.getData()[9])) - + String.valueOf((char)b2UB(aMessage.getData()[10])) - + String.valueOf((char)b2UB(aMessage.getData()[11])); - return SESSIONID_NAME.equalsIgnoreCase(aName); - } - - private String getSessionId(DatagramPacket aMessage) throws P2pProxyException{ -// APP: Application-Defined RTCP Packet -// -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// |V=2|P| subtype | PT=APP=204 | length | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | SSRC/CSRC | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | name (ASCII) | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | application-dependent data ... -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - - if (isSessionIdPresent(aMessage) == false) { - throw new P2pProxyException("Cannot find SessionId"); - } - long lPacketLenght = 1 + b2UB(aMessage.getData()[3]) + (b2UB(aMessage.getData()[2]) << 8) ; - StringBuffer lSessionId = new StringBuffer(); - for (int i = 12 ; i< lPacketLenght; i++) { - lSessionId.append(b2UB(aMessage.getData()[i])); - } - return lSessionId.toString(); - - } - private boolean isRtcp(DatagramPacket aMessage) { - return b2UB(aMessage.getData()[1]) >= 200 ; - } - public static int b2UB(byte b) { - return b >= 0 ? b : 256 + b; - } - - //stats - public int getRoutingtableSize() { - return mRoutingTable.getSize(); - } - boolean isRtpRtcpPacket(DatagramPacket aMessage) { - return (aMessage.getData()[0] >> 6) != 0; - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RtpRelayServerConfig.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RtpRelayServerConfig.java deleted file mode 100644 index 9f49887a..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RtpRelayServerConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.linphone.p2pproxy.core.media.rtprelay; - -import java.net.InetSocketAddress; - -/** - */ -public class RtpRelayServerConfig { - private final InetSocketAddress mAudioVideoPublicSocketAddress; - private final InetSocketAddress mVideovideoPrivateSocketAddress; - - public RtpRelayServerConfig(InetSocketAddress anAudioVideoPublicSocketAddress,InetSocketAddress anAudioVideoPrivateSocketAddress) { - mAudioVideoPublicSocketAddress = anAudioVideoPublicSocketAddress; - mVideovideoPrivateSocketAddress = anAudioVideoPrivateSocketAddress; - } - - /** - * @return Returns the mAudioPublicSocketAddress. - */ - public InetSocketAddress getAudioVideoPublicSocketAddress() { - return mAudioVideoPublicSocketAddress; - } - /** - * @return Returns the mVideoPublicSocketAddress. - */ - public InetSocketAddress getAudioVideoPrivateSocketAddress() { - return mVideovideoPrivateSocketAddress; - } -} \ No newline at end of file diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RtpRoutingRules.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RtpRoutingRules.java deleted file mode 100644 index 0660a778..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/RtpRoutingRules.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -RtpRoutingRules.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.media.rtprelay; - -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -import org.linphone.p2pproxy.api.P2pProxyException; - -public interface RtpRoutingRules { - - /** - * add route for a given ssrc - * @param aSource - */ - public void addRoute(int anSsrc, InetSocketAddress aSource); - - /** - * remove route - * @param aSource - */ - public void removeRoute(int anSsrc); - - /** - * return dest address - * @param aSource - * @return the destination address - * @throws P2pProxyException - */ - public SocketAddress getRoute(int anSsrc) throws P2pProxyException; -} \ No newline at end of file diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/SdpProcessorImpl.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/SdpProcessorImpl.java deleted file mode 100644 index 0618b45d..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/SdpProcessorImpl.java +++ /dev/null @@ -1,90 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -SdpProcessorImpl.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.rtprelay; - -import java.net.InetSocketAddress; -import java.util.Map; -import net.jxta.pipe.OutputPipe; -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyRtpRelayManagement; -import org.linphone.p2pproxy.core.sipproxy.SdpProcessor; -import org.zoolu.sdp.AttributeField; -import org.zoolu.sdp.MediaDescriptor; -import org.zoolu.sdp.SessionDescriptor; -import org.zoolu.sip.message.Message; - -/** - * rewrite SDP to insert a=relay-add - * - * - */ -public class SdpProcessorImpl implements SdpProcessor { - private final String RELAY_ADDR_NAME="relay-addr"; - - - private final static Logger mLog = Logger.getLogger(SdpProcessorImpl.class); - private final P2pProxyRtpRelayManagement mP2pProxyRtpRelayManagement; - public SdpProcessorImpl(P2pProxyRtpRelayManagement aP2pProxyRtpRelayManagement) { - mP2pProxyRtpRelayManagement = aP2pProxyRtpRelayManagement; - - } - public void processSdpAfterSentToPipe(Message message, OutputPipe outputPipe) - throws P2pProxyException { - //nop - - } - - public void processSdpBeforeSendingToSipUA(Message aMessage) throws P2pProxyException { - //nop - } - - public void processSdpBeforeSendingToPipe(Message aMessage) throws P2pProxyException { - if (aMessage.isInvite() || aMessage.isAck()) { - //check if sdp present - if (aMessage.hasBody() && "application/sdp".equals(aMessage.getBodyType())) { - SessionDescriptor lOrigSessionDescriptor = new SessionDescriptor(aMessage.getBody()); - //check if already have relay-session-id - Map lRelayAddresses = null; - for (Object lMediaDescriptorObject :lOrigSessionDescriptor.getMediaDescriptors()) { - MediaDescriptor lMediaDescriptor = (MediaDescriptor)lMediaDescriptorObject; - MediaType lMediaType = MediaType.parseString(lMediaDescriptor.getMedia().getMedia()); - AttributeField lSessionID = lMediaDescriptor.getAttribute("relay-session-id"); - AttributeField lRelayAddr = lMediaDescriptor.getAttribute(RELAY_ADDR_NAME); - if (lSessionID != null && lRelayAddr == null) { - //need to find a relay - if (lRelayAddresses == null) lRelayAddresses = mP2pProxyRtpRelayManagement.getAddresses(); - if (lRelayAddresses.get(lMediaType) != null) { - lRelayAddr = new AttributeField(RELAY_ADDR_NAME, lRelayAddresses.get(lMediaType).toString().substring(1)); - lMediaDescriptor.addAttribute(lRelayAddr); - mLog.info("adding relay ["+lRelayAddr+ "to mline ["+lMediaType+"]"); - } else { - mLog.warn("no relay for this media type ["+lMediaType+"]"); - - } - } - - } - } else { - mLog.info("strange, sdp in message ["+aMessage+"]"); - } - } - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/SingleAddressResponse.java b/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/SingleAddressResponse.java deleted file mode 100644 index 5907c1ea..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/media/rtprelay/SingleAddressResponse.java +++ /dev/null @@ -1,43 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -SingleAddressResponse.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.media.rtprelay; - -import java.io.Serializable; -import java.net.InetSocketAddress; - - -public class SingleAddressResponse implements Serializable { - private static final long serialVersionUID = 1L; - private final InetSocketAddress mAddress; - public SingleAddressResponse(InetSocketAddress anAddress) { - mAddress = anAddress; - } - /** - * @return Returns the relay adress. - */ - public InetSocketAddress getAddress() { - return mAddress; - } - - public String toString() { - - return mAddress.toString(); - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/AutoConfigService.java b/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/AutoConfigService.java deleted file mode 100644 index f30cf888..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/AutoConfigService.java +++ /dev/null @@ -1,147 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -AutoConfigService.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.rdvautoconfig; - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.util.Enumeration; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.XMLDocument; -import net.jxta.document.XMLElement; -import net.jxta.impl.protocol.HTTPAdv; -import net.jxta.impl.protocol.TCPAdv; -import net.jxta.peergroup.PeerGroup; -import net.jxta.protocol.TransportAdvertisement; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyNetworkProbe; -import org.linphone.p2pproxy.core.Configurator; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.ServiceProvider; -import org.linphone.p2pproxy.core.media.MediaResourceService; - - -public class AutoConfigService implements ServiceProvider { - private final static Logger mLog = Logger.getLogger(AutoConfigService.class); - private final JxtaNetworkManager mJxtaNetworkManager; - private final Configurator mProperties; - private final int mRelayCapacity; - private final P2pProxyNetworkProbe mP2pProxyManagement; - private InetAddress mPubliAddress; - public AutoConfigService(Configurator lProperties,JxtaNetworkManager aJxtaNetworkManager,P2pProxyNetworkProbe aServiceProvider) { - mJxtaNetworkManager = aJxtaNetworkManager; - mProperties = lProperties; - mP2pProxyManagement = aServiceProvider; - mRelayCapacity = Integer.parseInt(lProperties.getProperty(JxtaNetworkManager.RELAY_CAPACITY, "100")); - } - public void start(long aTimeOut) throws P2pProxyException { - try { - if(!mJxtaNetworkManager.isConnectedToRendezVous(aTimeOut)) - throw new P2pProxyException("Cannot start peer info service because not connected to any rdv"); - //check if capable - - mLog.info("AutoConfigService started"); - } - catch(Exception e) { - throw new P2pProxyException(e); - } - - } - - public void stop() { - mLog.info("AutoConfigService stopped"); - } - private HTTPAdv getHttpAdv() throws P2pProxyException { - - XMLDocument lHttpDoc = (XMLDocument) mJxtaNetworkManager.getPeerGroup().getConfigAdvertisement().getServiceParam(PeerGroup.httpProtoClassID); - if (lHttpDoc == null) { - throw new P2pProxyException("cannot find HTTPAdv"); - } - Enumeration lHttpChilds = lHttpDoc.getChildren( TransportAdvertisement.getAdvertisementType()); - // get the HTTPAdv from TransportAdv - if( lHttpChilds.hasMoreElements() ) { - return (HTTPAdv) AdvertisementFactory.newAdvertisement( (XMLElement) lHttpChilds.nextElement() ); - } else { - throw new P2pProxyException("cannot find HTTPAdv from transport"); - } - } - private TCPAdv getTcpAdv() throws P2pProxyException { - XMLDocument lTcpDoc = (XMLDocument) mJxtaNetworkManager.getPeerGroup().getConfigAdvertisement().getServiceParam(PeerGroup.tcpProtoClassID); - if (lTcpDoc == null) { - throw new P2pProxyException("cannot find TCPAdv"); - } - Enumeration lHttpChilds = lTcpDoc.getChildren( TransportAdvertisement.getAdvertisementType()); - // get the HTTPAdv from TransportAdv - if( lHttpChilds.hasMoreElements() ) { - return (TCPAdv) AdvertisementFactory.newAdvertisement( (XMLElement) lHttpChilds.nextElement() ); - } else { - throw new P2pProxyException("cannot find TCPAdv from transport"); - } - } - - /** - * test if the peer is capable to behave as a superpeer - * @return - */ - public boolean canIBehaveAsASuperPeer() { - boolean lHttpServerOk=false; - boolean lTcpServerOk=false; - - try { -// 1 check local ip - mPubliAddress = mP2pProxyManagement.getPublicIpAddress(); - //2 probe the http socket - InetSocketAddress lSocketAddress = new InetSocketAddress(mPubliAddress,getHttpAdv().getPort()); - lHttpServerOk = mP2pProxyManagement.probeSocket(lSocketAddress, P2pProxyNetworkProbe.Protocol.tcp); - - // 3 probe tcp socket - lSocketAddress = new InetSocketAddress(mPubliAddress,getTcpAdv().getPort()); - lTcpServerOk = mP2pProxyManagement.probeSocket(lSocketAddress, P2pProxyNetworkProbe.Protocol.tcp); - - if (lTcpServerOk || lHttpServerOk) { - mLog.info("can behave as a super peer :-)"); - return true; - } else { - mLog.info("cannot behave as a super peer :-("); - return false; - } - } catch (P2pProxyException e) { - mLog.info("cannot behave as a super peer", e); - return false; - } - } - public boolean startUdpProxyIfPossible() { - int lAudioVideoPort = Integer.parseInt(mProperties.getProperty(MediaResourceService.AUDIO_VIDEO_LOCAL_PORT,"16000")); - InetSocketAddress lSocketAddress=null; - try { - lSocketAddress = new InetSocketAddress(mPubliAddress,lAudioVideoPort); - mP2pProxyManagement.probeSocket(lSocketAddress, P2pProxyNetworkProbe.Protocol.udp); - return true; - }catch (P2pProxyException e) { - mLog.info("cannot open audio server on ["+lSocketAddress+"]", e); - } - return false; - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/P2pproxyRdvListener.java b/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/P2pproxyRdvListener.java deleted file mode 100644 index 444c265f..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/P2pproxyRdvListener.java +++ /dev/null @@ -1,33 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pproxyRdvListener.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.rdvautoconfig; - -import net.jxta.rendezvous.RendezvousEvent; -import net.jxta.rendezvous.RendezvousListener; - -public class P2pproxyRdvListener implements RendezvousListener { - - public void rendezvousEvent(RendezvousEvent event) { - // TODO Auto-generated method stub - - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PeerInfoProvider.java b/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PeerInfoProvider.java deleted file mode 100644 index 93c55ebd..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PeerInfoProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -PeerInfoProvider.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.rdvautoconfig; - -import java.net.InetAddress; - -public interface PeerInfoProvider { - /** - * get the public address as found in the http header during the ping procedure. - * @param aPeerAddress jxta address - * @return an IP address or null - */ - public InetAddress getPublicAddress(String aPeerAddress); - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PeerInfoProviderService.java b/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PeerInfoProviderService.java deleted file mode 100644 index 2e7f1d40..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PeerInfoProviderService.java +++ /dev/null @@ -1,239 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -PeerInfoProviderService.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.rdvautoconfig; - - - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.Socket; -import java.net.SocketTimeoutException; -import java.net.URI; - -import net.jxta.document.AdvertisementFactory; -import net.jxta.id.IDFactory; -import net.jxta.platform.ModuleClassID; -import net.jxta.platform.ModuleSpecID; -import net.jxta.protocol.ModuleClassAdvertisement; -import net.jxta.protocol.ModuleSpecAdvertisement; -import net.jxta.protocol.PipeAdvertisement; -import net.jxta.socket.JxtaServerSocket; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.Configurator; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.ServiceProvider; -import org.linphone.p2pproxy.core.jxtaext.EndpointRegistry; - - - -public class PeerInfoProviderService implements Runnable,PeerInfoProvider,ServiceProvider{ - private final JxtaNetworkManager mJxtaNetworkManager; - private final Configurator mProperties; - public final static String PEER_INFO_SERVICE_PIPE_ID="org.linphone.p2pproxy.PeerInfoProviderService.bidi-pipe.id"; - private final static Logger mLog = Logger.getLogger(PeerInfoProviderService.class); - private JxtaServerSocket mJxtaServerSocket; - private Thread mSocketServerThread = new Thread(this,"PeerInfoProviderService server thread"); - public final static String ADV_NAME = "JXTASPEC:LINPHONE-PEERINFO"; - private final static int SO_TIMOUT=3000; - public final static String PEERINFO_MODULE_CLASS_ID="org.linphone.p2pproxy.PeerInfoProviderService.module-class.id"; - public final static String PEERINFO_MODULE_SPEC_ID="org.linphone.p2pproxy.PeerInfoProviderService.module-spec.id"; - private boolean mExist = false; - - public PeerInfoProviderService(Configurator lProperties,JxtaNetworkManager aJxtaNetworkManager) { - mJxtaNetworkManager = aJxtaNetworkManager; - mProperties = lProperties; - } - - public void start(long l) throws P2pProxyException { - try { - mLog.info("Start the PeerInfoProviderService daemon"); - ModuleClassAdvertisement lModuleAdvertisement = (ModuleClassAdvertisement) AdvertisementFactory.newAdvertisement(ModuleClassAdvertisement.getAdvertisementType()); - - lModuleAdvertisement.setName("JXTAMOD:LINPHONE-PEERINFO"); - lModuleAdvertisement.setDescription("Service to provide peer with data like its public ip,etc"); - - ModuleClassID lModuleClassID; - // to avoid ID creation at each start - if (mProperties.getProperty(PEERINFO_MODULE_CLASS_ID) == null) { - lModuleClassID = IDFactory.newModuleClassID(); - mProperties.setProperty(PEERINFO_MODULE_CLASS_ID, lModuleClassID.toURI().toString()); - } else { - lModuleClassID = (ModuleClassID) IDFactory.fromURI(URI.create(mProperties.getProperty(PEERINFO_MODULE_CLASS_ID))); - } - lModuleAdvertisement.setModuleClassID(lModuleClassID); - - // publish local only - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().publish(lModuleAdvertisement); - - ModuleSpecAdvertisement lModuleSpecAdvertisement = (ModuleSpecAdvertisement)AdvertisementFactory.newAdvertisement(ModuleSpecAdvertisement.getAdvertisementType()); - lModuleSpecAdvertisement.setName(ADV_NAME); - lModuleSpecAdvertisement.setVersion("Version 1.0"); - lModuleSpecAdvertisement.setCreator("linphone.org"); - // to avoid ID creation at each start - ModuleSpecID lModuleSpecId; - if (mProperties.getProperty(PEERINFO_MODULE_SPEC_ID) == null) { - lModuleSpecId = IDFactory.newModuleSpecID(lModuleClassID); - mProperties.setProperty(PEERINFO_MODULE_SPEC_ID, lModuleSpecId.toURI().toString()); - } else { - lModuleSpecId = (ModuleSpecID) IDFactory.fromURI(URI.create(mProperties.getProperty(PEERINFO_MODULE_SPEC_ID))); - } - lModuleSpecAdvertisement.setModuleSpecID(lModuleSpecId); - lModuleSpecAdvertisement.setSpecURI("http://www.linphone.org/peerinfo"); - - PipeAdvertisement lSocketAdvertisement = mJxtaNetworkManager.createPipeAdvertisement(PEER_INFO_SERVICE_PIPE_ID, "peer-info-service"); - - lModuleSpecAdvertisement.setPipeAdvertisement(lSocketAdvertisement); - mJxtaServerSocket = new JxtaServerSocket(mJxtaNetworkManager.getPeerGroup(), lSocketAdvertisement, 10); - mJxtaServerSocket.setSoTimeout(0); - mSocketServerThread.start(); - //publish local only - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().publish(lModuleSpecAdvertisement); - mLog.info("Adv ["+lModuleSpecAdvertisement+"] published"); - } - catch(Exception e) - { - PeerInfoProviderService.mLog.error("socket instance error", e); - } - } - public void stop() { - try { - mJxtaServerSocket.close(); - } catch (IOException e) { - //nop - } - mExist = true; - mLog.info("PeerInfoProviderService stopped"); - } - - public void run() { - while (mExist) { - try { - mLog.info("Waiting for connection on ["+ADV_NAME+"]"); - Socket lSocket = mJxtaServerSocket.accept(); - // set reliable - if (lSocket != null) { - mLog.info("socket created"); - Thread thread = new Thread(new PeerInfoProviderServiceHandler(lSocket), "Connection Handler Thread"); - thread.start(); - } - } catch (Exception e) { - mLog.error("Server socket error",e); - } - } - - } - class PeerInfoProviderServiceHandler implements Runnable { - Socket mSocket = null; - - PeerInfoProviderServiceHandler(Socket aSocket) { - mSocket = aSocket; - } - - public void run() { - try { - ObjectOutputStream lOut = new ObjectOutputStream(mSocket.getOutputStream()); - //work around to unlock the socket - lOut.writeBoolean(true); - lOut.flush(); - ObjectInputStream lIn = new ObjectInputStream(mSocket.getInputStream()); - Object lInputObj; - Object lOutputObj; - while (mExist == false) { - lInputObj = lIn.readObject(); - mLog.info("request message ["+lInputObj+"] received"); - - if (lInputObj instanceof PublicIpAddressRequest) { -// PublicIpAddressRequest - PublicIpAddressRequest lPublicIpAddressRequest = (PublicIpAddressRequest) lInputObj; - InetAddress lInetAddress = getPeerInfoProvider().getPublicAddress(lPublicIpAddressRequest.getPeerId()); - PublicIpAddressResponse lPublicIpAddressResponse; - if (lInetAddress == null) { - lPublicIpAddressResponse = new PublicIpAddressResponse("address not found for["+lPublicIpAddressRequest.getPeerId()+"]"); - } else { - lPublicIpAddressResponse = new PublicIpAddressResponse(lInetAddress); - } - lOutputObj = lPublicIpAddressResponse; - lOut.writeObject(lOutputObj); - lOut.flush(); - mLog.info("request reponse ["+lOutputObj+"] sent"); - } else if (lInputObj instanceof SocketProbeRequest) { -// SocketProbeRequest - SocketProbeRequest lSocketProbeRequest = (SocketProbeRequest)lInputObj; - switch (lSocketProbeRequest.getProtocol()) { - case tcp: { - Socket lSocket = new Socket(); - lSocket.setSoTimeout(SO_TIMOUT); - - try { - lSocket.connect(lSocketProbeRequest.getSocketAddress()); - mLog.info("socket ["+lSocketProbeRequest+"] is reachable"); - }catch (Exception e) { - mLog.info("cannot reach ["+lSocketProbeRequest+"] in mode ["+lSocketProbeRequest.getProtocol()+"] for"+SO_TIMOUT+""); - } - lSocket.close(); - break; - } - case udp: { - DatagramSocket lSocket = new DatagramSocket(); - String lPing = "ping"; - DatagramPacket lDatagramPacket = new DatagramPacket(lPing.getBytes(),lPing.getBytes().length); - lDatagramPacket.setSocketAddress(lSocketProbeRequest.getSocketAddress()); - lSocket.send(lDatagramPacket); - mLog.info("ping sent to socket ["+lSocketProbeRequest+"] in mode ["+lSocketProbeRequest.getProtocol()+"]"); - lSocket.close(); - break; - } - default: throw new P2pProxyException("unsupported protocol ["+lSocketProbeRequest.getProtocol()+"]"); - } - - }else { - mLog.error("unknown request ["+lInputObj+"]"); - lOutputObj = null; - } - - - } - } catch (Exception e) { - mLog.error("socket instance error",e); - } - finally { - try { - mSocket.close(); - } catch (IOException e) { - mLog.error("cannot close socket ",e); - } - } - } - } - public PeerInfoProvider getPeerInfoProvider() { - return this; - } - public InetAddress getPublicAddress(String aPeerAddress) { - return EndpointRegistry.getInstance().get(aPeerAddress); - } - -} \ No newline at end of file diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PeerInfoServiceClient.java b/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PeerInfoServiceClient.java deleted file mode 100644 index d83526fb..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PeerInfoServiceClient.java +++ /dev/null @@ -1,150 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -PeerInfoServiceClient.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.rdvautoconfig; - - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.SocketAddress; -import java.net.SocketTimeoutException; -import java.util.List; - -import net.jxta.document.Advertisement; -import net.jxta.id.ID; -import net.jxta.protocol.ModuleSpecAdvertisement; -import net.jxta.socket.JxtaSocket; -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyNetworkProbe; -import org.linphone.p2pproxy.core.Configurator; -import org.linphone.p2pproxy.core.GenericServiceClient; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.ServiceProvider; -import org.linphone.p2pproxy.core.JxtaNetworkManager.Mode; - - -public class PeerInfoServiceClient extends GenericServiceClient implements P2pProxyNetworkProbe, ServiceProvider{ - private final static Logger mLog = Logger.getLogger(PeerInfoServiceClient.class); - - public PeerInfoServiceClient(Configurator lProperties,JxtaNetworkManager aJxtaNetworkManager) { - super(lProperties,aJxtaNetworkManager,PeerInfoProviderService.ADV_NAME); - } - - - public InetAddress getPublicIpAddress() throws P2pProxyException { - checkObject(); - try { - checkSocketConnection(); - PublicIpAddressRequest lPublicIpAddressRequest = new PublicIpAddressRequest(mJxtaNetworkManager.getPeerGroup().getPeerID().toString()); - mOut.writeObject(lPublicIpAddressRequest); - mOut.flush(); - mLog.info("request message ["+lPublicIpAddressRequest+"] sent"); - Object lInputObj = mIn.readObject(); - mLog.info("response message ["+lInputObj+"] received"); - if(lInputObj instanceof PublicIpAddressResponse) { - PublicIpAddressResponse lPublicIpAddressResponse = (PublicIpAddressResponse)lInputObj; - InetAddress lInetAddress = lPublicIpAddressResponse.getPublicAddress(); - mLog.info("public IP ["+lInetAddress+"] received"); - return lInetAddress; - } else { - throw new P2pProxyException("unknown response ["+lInputObj+"]"); - } - } - catch(Exception e) { - throw new P2pProxyException(e); - } - - } - - - - - public boolean probeSocket(InetSocketAddress aSocketAddress, Protocol aProtocol) throws P2pProxyException { - checkObject(); - boolean lResult = false; - try { - checkSocketConnection(); - switch(aProtocol) { - case tcp: { - // open the socket on 0.0.0.0:port for NAT - - ServerSocket lSocketServer = new ServerSocket(aSocketAddress.getPort()); - lSocketServer.setSoTimeout(mSoTimout); - - // send request to server - sendRequest(aSocketAddress,aProtocol); - try { - lSocketServer.accept(); - - lResult = true; - }catch (SocketTimeoutException e) { - // - } - lSocketServer.close(); - break; - } - case udp: { - // open the socket on 0.0.0.0:port for NAT - DatagramSocket lLocalSocket = new DatagramSocket(aSocketAddress.getPort()); - byte[] lBuff = new byte[1500]; - DatagramPacket lDatagramPacket = new DatagramPacket(lBuff,lBuff.length); - lLocalSocket.setSoTimeout(mSoTimout); - - // send request to server - SocketProbeRequest lSocketProbeRequest = new SocketProbeRequest(aSocketAddress,aProtocol); - mOut.writeObject(lSocketProbeRequest); - mOut.flush(); - mLog.info("request message ["+lSocketProbeRequest+"] sent"); - try { - lLocalSocket.receive(lDatagramPacket); - lResult = true; - }catch (SocketTimeoutException e) { - // nop - } - lLocalSocket.close(); - break; - } - default: throw new P2pProxyException("unsupported protocol ["+aProtocol+"]"); - } - if (lResult) { - mLog.info("socket ["+aSocketAddress+"] is reachable with protocol ["+aProtocol+"]"); - } else { - mLog.info("cannot reach ["+aSocketAddress+"] with protocol ["+aProtocol+"] for ["+mSoTimout+"] ms"); - } - return lResult; - } - catch(Exception e) { - throw new P2pProxyException(e); - } - } - private void sendRequest(SocketAddress aSocketAddress, Protocol aProtocol) throws IOException { - SocketProbeRequest lSocketProbeRequest = new SocketProbeRequest(aSocketAddress,aProtocol); - mOut.writeObject(lSocketProbeRequest); - mOut.flush(); - mLog.info("request message ["+lSocketProbeRequest+"] sent"); - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PublicIpAddressRequest.java b/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PublicIpAddressRequest.java deleted file mode 100644 index 86904dd8..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PublicIpAddressRequest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -PublicIpAddressRequest.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.rdvautoconfig; - -import java.io.Serializable; - -public class PublicIpAddressRequest implements Serializable{ - /** - * - */ - private static final long serialVersionUID = 1L; - final private String mPeerId; - PublicIpAddressRequest(String aPeerId) { - mPeerId = aPeerId; - } - public String getPeerId() { - return mPeerId; - } - public String toString() { - return "PublicIpAddressRequest for ["+mPeerId+"]"; - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PublicIpAddressResponse.java b/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PublicIpAddressResponse.java deleted file mode 100644 index 7d246d0a..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/PublicIpAddressResponse.java +++ /dev/null @@ -1,58 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -PublicIpAddressResponse.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.rdvautoconfig; - -import java.io.Serializable; -import java.net.InetAddress; - -public class PublicIpAddressResponse implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - final private InetAddress mPublicAddress; - final private boolean mIsError; - final private String mErrorText; - public PublicIpAddressResponse(InetAddress aPublicAdress) { - mPublicAddress = aPublicAdress; - mIsError = false; - mErrorText =""; - } - public PublicIpAddressResponse(String anErroText) { - mPublicAddress = null; - mIsError = true; - mErrorText =anErroText; - - } - public InetAddress getPublicAddress() { - return mPublicAddress; - } - public boolean isError() { - return mIsError; - } - public String getErrorText() { - return mErrorText; - } - public String toString() { - return "PublicIpAddressResponse ip ["+mPublicAddress+"] error ["+mErrorText+"]"; - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/SocketProbeRequest.java b/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/SocketProbeRequest.java deleted file mode 100644 index adcfc0e8..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/rdvautoconfig/SocketProbeRequest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -SocketProbeRequest.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.rdvautoconfig; - -import java.io.Serializable; -import java.net.SocketAddress; - -import org.linphone.p2pproxy.api.P2pProxyNetworkProbe.Protocol; - -public class SocketProbeRequest implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - final private SocketAddress mSocketAddress; - final private Protocol mProtocol; - public SocketProbeRequest(SocketAddress aSocketAddress, Protocol aProtocol) { - mSocketAddress = aSocketAddress; - mProtocol = aProtocol; - } - /** - * @return Returns the mProtocol. - */ - public Protocol getProtocol() { - return mProtocol; - } - /** - * @return Returns the mSocketAddress. - */ - public SocketAddress getSocketAddress() { - return mSocketAddress; - } - - public String toString() { - return "SocketProbeRequest for ["+mSocketAddress+"] protocol ["+mProtocol+"]"; - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/NetworkResourceAdvertisement.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/NetworkResourceAdvertisement.java deleted file mode 100644 index f03c3973..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/NetworkResourceAdvertisement.java +++ /dev/null @@ -1,267 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pUserRegistrationAdvertisement.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.sipproxy; - - -import java.io.Serializable; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - -import org.apache.log4j.Logger; - - - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attributable; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.TextElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; - -/** - * derivated from jxta Advertisement tutorial - *
            - * <?xml version="1.0"?>
            - * <!DOCTYPE jxta:System>
            - * <jxta:System xmlns:jxta="http://jxta.org">
            - *   <id> </id>
            - *   <Name> </Name>
            - *   <address>address where a sip endpoint can join</registrar-address>
            - * </jxta:System>
            - * 
            - */ -public class NetworkResourceAdvertisement extends ExtendableAdvertisement implements Comparable, Cloneable, Serializable { - /** - * Instantiator - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public String getAdvertisementType() { - return NetworkResourceAdvertisement.getAdvertisementType(); - } - - /** - * Constructs an instance of Advertisement matching the - * type specified by the advertisementType parameter. - * - * @return The instance of Advertisement or null if it - * could not be created. - */ - public Advertisement newInstance() { - return new NetworkResourceAdvertisement(); - } - - /** - * Constructs an instance of Advertisement matching the - * type specified by the advertisementType parameter. - * - * @param root Specifies a portion of a StructuredDocument which will - * be converted into an Advertisement. - * @return The instance of Advertisement or null if it - * could not be created. - */ - public Advertisement newInstance(net.jxta.document.Element root) { - return new NetworkResourceAdvertisement(root); - } - } - private ID mId ;; - private String mAddress; - private String mName; - public final static String ADDRESS_TAG = "address"; - private final static String ID_TAG = "ID"; - final static String NAME_TAG = "Name"; - //public final static String NAME = "p2p-proxy-proxyregistrar"; - private final static String[] mIndexs = {NAME_TAG}; - private final static Logger mLog = Logger.getLogger(NetworkResourceAdvertisement.class); - /** - * - */ - public NetworkResourceAdvertisement(Element root) { - - TextElement doc = (TextElement) root; - - if (!getAdvertisementType().equals(doc.getName())) { - throw new IllegalArgumentException("Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - initialize(doc); - - } - public NetworkResourceAdvertisement() { - - // TODO Auto-generated constructor stub - } - /* (non-Javadoc) - * @see net.jxta.document.ExtendableAdvertisement#getDocument(net.jxta.document.MimeMediaType) - */ - @Override - public Document getDocument(MimeMediaType asMimeType) { - - StructuredDocument adv = StructuredDocumentFactory.newStructuredDocument(asMimeType, - getAdvertisementType()); - if (adv instanceof Attributable) { - ((Attributable) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - } - Element e; - e = adv.createElement(ID_TAG, getID().toString()); - adv.appendChild(e); - e = adv.createElement(NAME_TAG, getName().toString()); - adv.appendChild(e); - e = adv.createElement(ADDRESS_TAG, getAddress().trim()); - adv.appendChild(e); - return adv; - } - - public String getName() { - return mName; - } - @Override - public ID getID() { - return mId; - } - - @Override - public String[] getIndexFields() { - return mIndexs; - } - public static String getAdvertisementType() { - return "jxta:p2p-proxy-networkresource"; - } - /* (non-Javadoc) - * @see net.jxta.document.Advertisement#toString() - */ - @Override - public String toString() { - // TODO Auto-generated method stub - return super.toString(); - } - public int compareTo(Object other) { - return getID().toString().compareTo(other.toString()); - } - /** - * Intialize a System advertisement from a portion of a structured document. - * - * @param root document root - */ - protected void initialize(Element root) { - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + - " only supports TextElement"); - } - TextElement doc = (TextElement) root; - if (!doc.getName().equals(getAdvertisementType())) { - throw new IllegalArgumentException("Could not construct : " - + getClass().getName() + "from doc containing a " + - doc.getName()); - } - Enumeration elements = doc.getChildren(); - while (elements.hasMoreElements()) { - TextElement elem = (TextElement) elements.nextElement(); - if (!handleElement(elem)) { - mLog.warn("Unhandleded element \'" + elem.getName() + "\' in " + doc.getName()); - } - } - } - /** - * Process an individual element from the document. - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - */ - protected boolean handleElement(TextElement elem) { - if (elem.getName().equals(ID_TAG)) { - try { - URI id = new URI(elem.getTextValue()); - setID(IDFactory.fromURI(id)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("unknown ID format in advertisement: " + - elem.getTextValue()); - } - catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a known id type: " + - elem.getTextValue()); - } - return true; - } else if (elem.getName().equals(ADDRESS_TAG)) { - setAddress(elem.getTextValue()); - return true; - } else if (elem.getName().equals(NAME_TAG)) { - setName(elem.getTextValue()); - return true; - } else { - return false; - } - } - public void setID(ID id) { - mId = id; - } - @Override - public String getBaseAdvType() { - // TODO Auto-generated method stub - return null; - } - /** - * @return Returns the address as a sip uri. - */ - public String getAddress() { - return mAddress; - } - /** - * @param name The mName to set. - */ - public void setAddress(String anAddress) { - mAddress = anAddress; - } - public void setName(String aName) { - mName = aName; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - if (obj instanceof NetworkResourceAdvertisement) { - NetworkResourceAdvertisement adv = (NetworkResourceAdvertisement) obj; - return getID().equals(adv.getID()); - } - - return false; - - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/RegistrationHandler.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/RegistrationHandler.java deleted file mode 100644 index 9a86b8a9..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/RegistrationHandler.java +++ /dev/null @@ -1,29 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -RegistrationHandler.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.sipproxy; - - -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar.Registration; -import org.zoolu.sip.message.Message; - -public interface RegistrationHandler { - public void updateRegistration(Registration aRegistration, Message aRegistrationMessage) throws P2pProxyException; -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SdpProcessor.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SdpProcessor.java deleted file mode 100644 index ca553b18..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SdpProcessor.java +++ /dev/null @@ -1,39 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -SdpProcessor.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.sipproxy; - - - -import net.jxta.pipe.OutputPipe; - -import org.linphone.p2pproxy.api.P2pProxyException; -import org.zoolu.sip.message.Message; - -public interface SdpProcessor { - /** - * process SDP in mode relay - * rewrite sdp. - */ - public void processSdpBeforeSendingToSipUA( Message aMessage) throws P2pProxyException; - - public void processSdpBeforeSendingToPipe( Message aMessage) throws P2pProxyException; - - public void processSdpAfterSentToPipe( Message aMessage,OutputPipe lOutputPipe) throws P2pProxyException; -} \ No newline at end of file diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipProxy.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipProxy.java deleted file mode 100644 index fcc16ce3..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipProxy.java +++ /dev/null @@ -1,29 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -SipProxy.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.sipproxy; - -import org.linphone.p2pproxy.api.P2pProxyException; -import org.zoolu.sip.message.Message; -import org.zoolu.sip.provider.SipProvider; - -public interface SipProxy { - public void proxyRequest(SipProvider aProvider, Message aMessage) throws P2pProxyException; - public void proxyResponse(SipProvider aProvider, Message aMessage) throws P2pProxyException; -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipProxyRegistrar.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipProxyRegistrar.java deleted file mode 100644 index 0efaacb3..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipProxyRegistrar.java +++ /dev/null @@ -1,404 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -SipListener.java - sip proxy. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ - -package org.linphone.p2pproxy.core.sipproxy; - - -import java.io.File; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.Callable; -import java.util.concurrent.Executors; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import net.jxta.document.AdvertisementFactory; -import net.jxta.id.IDFactory; -import org.apache.log4j.Logger; -import org.apache.log4j.NDC; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyUserNotFoundException; - -import org.linphone.p2pproxy.core.Configurator; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.P2pProxyAccountManagementMBean; -import org.linphone.p2pproxy.core.media.rtprelay.MediaType; -import org.linphone.p2pproxy.core.sipproxy.superpeers.SuperPeerProxy; -import org.zoolu.sip.header.ExpiresHeader; -import org.zoolu.sip.header.MultipleHeader; -import org.zoolu.sip.message.Message; -import org.zoolu.sip.message.MessageFactory; -import org.zoolu.sip.provider.SipProvider; -import org.zoolu.sip.provider.SipProviderListener; -import org.zoolu.sip.provider.SipStack; -import org.zoolu.sip.transaction.TransactionServer; -import java.util.Collections; - -public class SipProxyRegistrar implements SipProviderListener,SipProxyRegistrarMBean { - private final static Logger mLog = Logger.getLogger(SipProxyRegistrar.class); - public final static String REGISTRAR_PORT="org.linphone.p2pproxy.SipListener.registrar.port"; - public final static String REGISTRAR_PUBLIC_ADDRESS="org.linphone.p2pproxy.SipListener.registrar.public.address"; - public final static String ADV_NAME = "p2p-proxy-proxyregistrar"; - private final int ADV_LIFE_TIME=6000000; - // - private final SipProvider mProvider; - private final JxtaNetworkManager mJxtaNetworkManager; - private final ExecutorService mPool; - - private final Map mRegistrationTab = Collections.synchronizedMap(new HashMap()); - private final Map mCancalableTaskTab = Collections.synchronizedMap(new HashMap()); - - private final P2pProxyAccountManagementMBean mP2pProxyAccountManagement; - private final Configurator mProperties; - private final SuperPeerProxy mSuperPeerProxy; - private NetworkResourceAdvertisement mProxyRegistrationAdvertisement; - private final Timer mTimer = new Timer ("Proxy registrar adv publisher"); - - //private long mNumberOfEstablishedCall; - private long mNumberOfRefusedRegistration; - private long mNumberOfSuccessfullRegistration; - private long mNumberOfUSerNotFound; - private long mNumberOfUnknownUSers; - private long mNumberOfUnknownUsersForRegistration; - private long mNumberOfUnRegistration; - - - public static class Registration { - long RegistrationDate; - public long Expiration; - //implementation specific context - public Object NetResources; - public Map RtpRelays = new HashMap() ; - public String Contact; - public final String From; - public Registration(String aFrom) {From = aFrom;} - public String toString() { - return "reg date ["+RegistrationDate+"] exp ["+Expiration+"] contact ["+Contact+"] from ["+From+"]"; - } - } - - class SipMessageTask implements Callable { - private final SipProvider mProvider; - private final Message mMessage; - private Future mFuture; - - /** - * @return Returns the mMessage. - */ - public Message getMessage() { - return mMessage; - } - SipMessageTask(SipProvider aProvider, Message aMessage) { - mProvider = aProvider; - mMessage = aMessage; - } - public Boolean call() throws Exception { - NDC.push(mMessage.getFirstLine() + mMessage.getCallIdHeader().getCallId() +":"); - try { - if (mMessage.isRequest()) { - if (mMessage.isRegister()) { - processRegister(mProvider, mMessage); - } else { - proxyRequest(mProvider, mMessage); - } - } else { - //1 remove via header - SipUtils.removeVia(mProvider,mMessage); - //2 process response - proxyResponse(mProvider, mMessage); - } - if (mMessage.isInvite() && mCancalableTaskTab.containsKey(mMessage.getCallIdHeader().getCallId()) ) { - mCancalableTaskTab.remove(mMessage.getCallIdHeader().getCallId()); - } - } catch (InterruptedException eInter) { - mLog.info("request interrupted",eInter); - //nop - } - catch (Exception e) { - mLog.error("unexpected behavior",e); - if (mMessage.isRequest()) { - Message lResp= null; - lResp = MessageFactory.createResponse(mMessage,500,e.getMessage(),null); - TransactionServer lTransactionServer = new TransactionServer(mProvider,mMessage,null); - lTransactionServer.respondWith(lResp); - synchronized (SipProxyRegistrar.this) { - if (mMessage.isInvite() && mCancalableTaskTab.containsKey(mMessage.getCallIdHeader().getCallId()) ) { - mCancalableTaskTab.remove(mMessage.getCallIdHeader().getCallId()); - } - } - } - } finally { - NDC.pop(); - } - return true; - } - /** - * @return Returns the mFuture. - */ - public Future getFuture() { - return mFuture; - } - /** - * @param future The mFuture to set. - */ - public void setFuture(Future future) { - mFuture = future; - } - - } - - public SipProxyRegistrar(Configurator lProperties,JxtaNetworkManager aJxtaNetworkManager,P2pProxyAccountManagementMBean aP2pProxyAccountManagement) throws IOException { - mJxtaNetworkManager = aJxtaNetworkManager; - mP2pProxyAccountManagement = aP2pProxyAccountManagement; - mProperties = lProperties; - File lFile = new File(SipStack.log_path); - if (lFile.exists() == false) lFile.mkdir(); - String lViaAddress = lProperties.getProperty(REGISTRAR_PUBLIC_ADDRESS); - int lPort = Integer.parseInt(lProperties.getProperty(REGISTRAR_PORT, "5060")); - String[] lProto = {SipProvider.PROTO_UDP}; - mProvider=new SipProvider(lViaAddress,lPort,lProto,SipProvider.ALL_INTERFACES); - mProvider.addSipProviderListener(SipProvider.PROMISQUE,this); - mPool = Executors.newCachedThreadPool(); - mSuperPeerProxy = new SuperPeerProxy(aJxtaNetworkManager, "sip:"+mProvider.getViaAddress()+":"+mProvider.getPort(),mRegistrationTab); - TimerTask lPublisherTask = new TimerTask() { - - @Override - public void run() { - try { - SipProxyRegistrar.this.publishAdvertisement(); - } catch (IOException e) { - mLog.error("cannot publish proxy registar adv", e); - } - - } - - }; - mTimer.scheduleAtFixedRate(lPublisherTask, 0, ADV_LIFE_TIME-ADV_LIFE_TIME/10); - TimerTask lRegistrationTableGC = new TimerTask() { - - @Override - public void run() { - // copy list - Collection lCurrentRegistrations = mRegistrationTab.values(); - long lCurrentDate = System.currentTimeMillis(); - for (Registration lRegistration : lCurrentRegistrations) { - if ((lCurrentDate - lRegistration.RegistrationDate - lRegistration.Expiration) > 0) { - if (mLog.isInfoEnabled()) mLog.info("registration entry ["+lRegistration+"] has expired"); - mRegistrationTab.remove(lRegistration.From); - } - } - } - - }; - mTimer.scheduleAtFixedRate(lRegistrationTableGC, 0, 60000); - - } - public void onReceivedMessage(SipProvider aProvider, Message aMessage) { - if (aProvider.getListeners().containsKey(aMessage.getTransactionId())) { - if (mLog.isDebugEnabled()) mLog.debug ("nothing to do, transaction already handled for ["+aMessage+"]"); - return; - } - if (mLog.isInfoEnabled()) mLog.info("receiving message ["+aMessage+"]"); - String lCallId = aMessage.getCallIdHeader().getCallId(); - SipMessageTask lPendingSipMessageTask = mCancalableTaskTab.get(lCallId); - - if (aMessage.isCancel() && lPendingSipMessageTask != null ) { - // search for pending transaction - - lPendingSipMessageTask.getFuture().cancel(true); - mCancalableTaskTab.remove(lCallId); - - SipUtils.removeVia(mProvider,lPendingSipMessageTask.getMessage()); - // accept cancel - Message lCancelResp = MessageFactory.createResponse(aMessage,200,"ok",null); - TransactionServer lCancelTransactionServer = new TransactionServer(mProvider,aMessage,null); - lCancelTransactionServer.respondWith(lCancelResp); - - // cancel invite - Message lInviteResp = MessageFactory.createResponse(lPendingSipMessageTask.getMessage(),487,"Request Terminated",null); - TransactionServer lInviteTransactionServer = new TransactionServer(mProvider,lPendingSipMessageTask.getMessage(),null); - lInviteTransactionServer.respondWith(lInviteResp); - } else { - // normal behavior - SipMessageTask lSipMessageTask = new SipMessageTask(aProvider,aMessage); - lSipMessageTask.setFuture(mPool.submit(lSipMessageTask)); - if (aMessage.isInvite()) { - mCancalableTaskTab.put(aMessage.getCallIdHeader().getCallId(),lSipMessageTask); - } - - } - - } -////////////////////////////////////////////////////////////////////// -////Proxy methods -///////////////////////////////////////////////////////////////////// - private void proxyResponse(SipProvider aProvider, Message aMessage) throws NumberFormatException, InterruptedException, P2pProxyException, IOException { - mSuperPeerProxy.proxyResponse(aProvider, aMessage); - } - private void proxyRequest(SipProvider aProvider, Message aMessage) throws Exception { - if (aMessage.isAck() && aMessage.getToHeader().getTag() == null) { - // just terminate the Invite transaction - return; - } - - if (aMessage.isInvite() == true) { - // 100 trying - TransactionServer lTransactionServer = new TransactionServer(aProvider,aMessage,null); - Message l100Trying = MessageFactory.createResponse(aMessage,100,"trying",null); - lTransactionServer.respondWith(l100Trying); - lTransactionServer.terminate(); - } - //remove route - MultipleHeader lMultipleRoute = aMessage.getRoutes(); - if (lMultipleRoute != null) { - lMultipleRoute.removeTop(); - aMessage.setRoutes(lMultipleRoute); - } - // add Via only udp - SipUtils.addVia(aProvider,aMessage); - try { - mSuperPeerProxy.proxyRequest(aProvider, aMessage); - }catch (P2pProxyUserNotFoundException e) { - //remove via - SipUtils.removeVia(aProvider, aMessage); - if (aMessage.isInvite()) { - Message lresp = MessageFactory.createResponse(aMessage,404,e.getMessage(),null); - TransactionServer lTransactionServer = new TransactionServer(aProvider,aMessage,null); - lTransactionServer.respondWith(lresp); - lTransactionServer.terminate(); - } else { - throw e; - } - } - } - - -////////////////////////////////////////////////////////////////////// -////Registrar methods -///////////////////////////////////////////////////////////////////// - - private void processRegister(SipProvider aProvider, Message aMessage) throws IOException, P2pProxyException { - TransactionServer lTransactionServer = new TransactionServer(aProvider,aMessage,null); - Message l100Trying = MessageFactory.createResponse(aMessage,100,"trying",null); - lTransactionServer.respondWith(l100Trying); - Registration lRegistration=null; - - //check if already registered - - String lFromName = aMessage.getFromHeader().getNameAddress().getAddress().toString(); - if ((lRegistration = mRegistrationTab.get(lFromName)) != null) { - - updateRegistration(lRegistration,aMessage); - - if (aMessage.getExpiresHeader().getDeltaSeconds() == 0) { - mRegistrationTab.remove(lFromName); - } - - } else { - // new registration - // test if account already created - - if (mP2pProxyAccountManagement.isValidAccount(lFromName)) { - lRegistration = new Registration(lFromName); - // forgot contact, use rport lRegistration.Contact = aMessage.getContactHeader().getNameAddress().getAddress().toString();; - - updateRegistration(lRegistration,aMessage); - mRegistrationTab.put(lFromName, lRegistration); - } else { - // create negative answers - mLog.info("account for user ["+lFromName+"] not created yet"); - Message lresp = MessageFactory.createResponse(aMessage,404,"Not found",null); - lTransactionServer.respondWith(lresp); - return; - } - } - // ok, create answers - Message lresp = MessageFactory.createResponse(aMessage,200,"Ok",null); - lresp.addContactHeader(aMessage.getContactHeader(), false); - ExpiresHeader lExpireHeader = new ExpiresHeader((int) (lRegistration.Expiration/1000)); - lresp.addHeader(lExpireHeader, false); - lTransactionServer.respondWith(lresp); - - } - private void updateRegistration(Registration aRegistration, Message aRegistrationMessage) throws P2pProxyException { - aRegistration.RegistrationDate = System.currentTimeMillis(); - // default registration period - aRegistration.Expiration = 3600000; - if (aRegistrationMessage.getExpiresHeader() != null ) { - aRegistration.Expiration = aRegistrationMessage.getExpiresHeader().getDeltaSeconds()*1000; - } - aRegistration.Contact = "sip:"+aRegistrationMessage.getRemoteAddress()+":"+aRegistrationMessage.getRemotePort(); - mSuperPeerProxy.updateRegistration(aRegistration, aRegistrationMessage); - } - - -public void stop() { - try { - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().flushAdvertisement(mProxyRegistrationAdvertisement); - } catch (IOException e) { - mLog.warn("cannot flush registrar adv",e ); - } - mProvider.halt(); -} - - // public long getNumberOfEstablishedCall() { -// return mNumberOfEstablishedCall; -// } - public long getNumberOfRefusedRegistration() { - return mNumberOfRefusedRegistration; - } - public long getNumberOfSuccessfullRegistration() { - return mNumberOfSuccessfullRegistration; - } - public long getNumberOfUSerNotFound() { - return mNumberOfUSerNotFound; - } - public long getNumberOfUnknownUSers() { - return mNumberOfUnknownUSers; - } - public long getNumberOfUnknownUsersForRegistration() { - return mNumberOfUnknownUsersForRegistration; - } - public String[] getRegisteredList() { - String[] lRegisteredList = new String[mRegistrationTab.size()] ; - int i=0; - for (String lRegistrationKey : mRegistrationTab.keySet()) { - lRegisteredList[i++] = lRegistrationKey; - } - return lRegisteredList; - } - public long getNumberOfUnRegistration() { - return mNumberOfUnRegistration; - } - private void publishAdvertisement() throws IOException { - if (mProxyRegistrationAdvertisement == null) { - mProxyRegistrationAdvertisement = (NetworkResourceAdvertisement) AdvertisementFactory.newAdvertisement(NetworkResourceAdvertisement.getAdvertisementType()); - mProxyRegistrationAdvertisement.setID(IDFactory.newCodatID(mJxtaNetworkManager.getPeerGroup().getPeerGroupID(), Integer.toHexString(mSuperPeerProxy.getSipProxyRegistrarAddress().hashCode()).getBytes("US-ASCII"))); - mProxyRegistrationAdvertisement.setAddress(mSuperPeerProxy.getSipProxyRegistrarAddress()); - mProxyRegistrationAdvertisement.setName(ADV_NAME); - } - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().publish(mProxyRegistrationAdvertisement,ADV_LIFE_TIME,ADV_LIFE_TIME/2); - mLog.info(mProxyRegistrationAdvertisement + "published"); - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipProxyRegistrarMBean.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipProxyRegistrarMBean.java deleted file mode 100644 index 882d185b..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipProxyRegistrarMBean.java +++ /dev/null @@ -1,34 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -SipProxyRegistrarMBean.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.sipproxy; - -public interface SipProxyRegistrarMBean { - // registrar - public long getNumberOfSuccessfullRegistration(); - public long getNumberOfUnRegistration(); - public long getNumberOfRefusedRegistration(); - public long getNumberOfUnknownUsersForRegistration(); - public String[] getRegisteredList(); - //proxy - //public long getNumberOfEstablishedCall(); - public long getNumberOfUSerNotFound(); - public long getNumberOfUnknownUSers(); -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipUtils.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipUtils.java deleted file mode 100644 index 66661223..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/SipUtils.java +++ /dev/null @@ -1,52 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -SipUtils.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.sipproxy; - -import org.zoolu.sip.address.NameAddress; -import org.zoolu.sip.address.SipURL; -import org.zoolu.sip.header.Header; -import org.zoolu.sip.header.RecordRouteHeader; -import org.zoolu.sip.header.ViaHeader; -import org.zoolu.sip.message.Message; -import org.zoolu.sip.provider.SipProvider; - -public class SipUtils { - public static void addVia(SipProvider aProvider, Message aMessage) { - ViaHeader via=new ViaHeader("udp",aProvider.getViaAddress(),aProvider.getPort()); - String branch=aProvider.pickBranch(aMessage); - via.setBranch(branch); - aMessage.addViaHeader(via); - } - public static void addRecordRoute(SipProvider aProvider, Message aMessage) { - SipURL lRecordRoute; - lRecordRoute=new SipURL(aProvider.getViaAddress(),aProvider.getPort()); - lRecordRoute.addLr(); - RecordRouteHeader lRecordRouteHeader=new RecordRouteHeader(new NameAddress(lRecordRoute)); - aMessage.addRecordRouteHeader(lRecordRouteHeader); - } - public static void removeVia(SipProvider aProvider, Message aMessage) { - synchronized (aMessage) { - ViaHeader lViaHeader =new ViaHeader((Header)aMessage.getVias().getHeaders().elementAt(0)); - if (lViaHeader.getHost().equals(aProvider.getViaAddress()) && lViaHeader.getPort() == aProvider.getPort() ) { - aMessage.removeViaHeader(); - } - } - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/peers/JxtaSipProxy.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/peers/JxtaSipProxy.java deleted file mode 100644 index 0dd6ba3d..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/peers/JxtaSipProxy.java +++ /dev/null @@ -1,203 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -JxtaSipProxy.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.sipproxy.peers; - -import java.io.IOException; -import java.util.Map; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.endpoint.MessageElement; -import net.jxta.endpoint.StringMessageElement; -import net.jxta.pipe.OutputPipe; -import net.jxta.pipe.PipeMsgEvent; -import net.jxta.pipe.PipeMsgListener; -import net.jxta.protocol.PipeAdvertisement; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyRtpRelayManagement; -import org.linphone.p2pproxy.api.P2pProxyUserNotFoundException; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.P2pProxyAdvertisementNotFoundException; -import org.linphone.p2pproxy.core.media.rtprelay.SdpProcessorImpl; -import org.linphone.p2pproxy.core.sipproxy.RegistrationHandler; -import org.linphone.p2pproxy.core.sipproxy.SdpProcessor; -import org.linphone.p2pproxy.core.sipproxy.SipProxy; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar; -import org.linphone.p2pproxy.core.sipproxy.SipUtils; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar.Registration; -import org.zoolu.sip.address.NameAddress; -import org.zoolu.sip.address.SipURL; -import org.zoolu.sip.header.MultipleHeader; -import org.zoolu.sip.header.RouteHeader; -import org.zoolu.sip.message.Message; -import org.zoolu.sip.message.MessageFactory; -import org.zoolu.sip.provider.SipProvider; -import org.zoolu.sip.transaction.TransactionServer; - -public class JxtaSipProxy implements SipProxy, PipeMsgListener,RegistrationHandler { - private final JxtaNetworkManager mJxtaNetworkManager; - private final Map mRegistrationTab; - private final SdpProcessor mSdpProcessor; - private final SipProvider mProvider; - - private final static Logger mLog = Logger.getLogger(JxtaSipProxy.class); - - public JxtaSipProxy(SipProvider aProvider,JxtaNetworkManager aJxtaNetworkManager, Map aRegistrationTab,P2pProxyRtpRelayManagement aP2pProxyRtpRelayManagement) { - mJxtaNetworkManager = aJxtaNetworkManager; - mSdpProcessor = new SdpProcessorImpl(aP2pProxyRtpRelayManagement); - mRegistrationTab = aRegistrationTab; - mProvider = aProvider; - } - public void proxyRequest(SipProvider aProvider, Message aMessage) throws P2pProxyException { - String lTo = aMessage.getToHeader().getNameAddress().getAddress().toString(); - try { - mSdpProcessor.processSdpBeforeSendingToPipe(aMessage); - // proxy message to pipe - OutputPipe lOutputPipe = sendMessageToPipe(lTo,aMessage.toString()); - mSdpProcessor.processSdpAfterSentToPipe( aMessage,lOutputPipe); - } catch (Exception e2) { - //remove via - SipUtils.removeVia(aProvider, aMessage); - throw new P2pProxyException(e2); - - } - - - } - - public void proxyResponse(SipProvider aProvider, Message aMessage) throws P2pProxyException { - try { - String lFrom = aMessage.getFromHeader().getNameAddress().getAddress().toString(); - mSdpProcessor.processSdpBeforeSendingToPipe(aMessage); - OutputPipe lOutputPipe = sendMessageToPipe(lFrom,aMessage.toString()); - mSdpProcessor.processSdpAfterSentToPipe( aMessage,lOutputPipe); - } catch(Exception e) { - throw new P2pProxyException(e); - } - - } - private Advertisement getPipeAdv(String aUser,long aDiscoveryTimout,boolean isTryFromLocal) throws InterruptedException, P2pProxyUserNotFoundException, IOException { - // search on all peers - try { - return mJxtaNetworkManager.getAdvertisement(null,aUser, isTryFromLocal); - } catch (P2pProxyAdvertisementNotFoundException e) { - throw new P2pProxyUserNotFoundException(e); - } - } - private OutputPipe sendMessageToPipe(String aDestination,String lContent) throws NumberFormatException, InterruptedException, P2pProxyException, IOException { - - //1 search for pipe - long lTimeout = JxtaNetworkManager.ADV_DISCOVERY_TIMEOUT_INT; - PipeAdvertisement lPipeAdvertisement = (PipeAdvertisement)getPipeAdv(aDestination,lTimeout,true); - OutputPipe lOutputPipe=null; - try { - // create output pipe - lOutputPipe = mJxtaNetworkManager.getPeerGroup().getPipeService().createOutputPipe(lPipeAdvertisement, lTimeout); - //create the message - } catch (IOException e) { - //second try from remote only to avoid wrong cached value - mJxtaNetworkManager.getPeerGroup().getDiscoveryService().flushAdvertisement(lPipeAdvertisement); - mLog.warn("cannot create output pipe, trying to ask from rdv ",e); - lPipeAdvertisement = (PipeAdvertisement)getPipeAdv(aDestination,lTimeout,false); - lOutputPipe = mJxtaNetworkManager.getPeerGroup().getPipeService().createOutputPipe(lPipeAdvertisement, lTimeout); - } - net.jxta.endpoint.Message lMessage = new net.jxta.endpoint.Message(); - StringMessageElement lStringMessageElement = new StringMessageElement("SIP", lContent, null); - lMessage.addMessageElement("SIP", lStringMessageElement); - //send the message - lOutputPipe.send(lMessage); - mLog.debug("message sent to ["+aDestination+"]"); - return lOutputPipe; - - } -////////////////////////////////////////////////////////////////////// -////jxta service methods -///////////////////////////////////////////////////////////////////// - - - public void pipeMsgEvent(PipeMsgEvent anEvent) { - MessageElement lMessageElement = anEvent.getMessage().getMessageElement("SIP"); - if (lMessageElement == null) { - //nop, this is not for me - return; - } - String lMesssage = lMessageElement.toString(); - mLog.info("pipe event sip message["+lMesssage+"]"); - Message lSipMessage = new Message(lMesssage); - // process request - if (lSipMessage.isRequest()) { - SipURL lNextHope ; - // get next hope from registrar - String lToName = lSipMessage.getToHeader().getNameAddress().getAddress().toString(); - if (mRegistrationTab.containsKey(lToName)) { - lNextHope = new SipURL(mRegistrationTab.get(lToName).Contact); - } else { - mLog.error("user ["+lToName+"] not found"); - return; - } - //RequestLine lRequestLine = new RequestLine(lSipMessage.getRequestLine().getMethod(),lNextHope); - //lSipMessage.setRequestLine(lRequestLine); - MultipleHeader lMultipleRoute = lSipMessage.getRoutes(); - RouteHeader lRouteHeader = new RouteHeader(new NameAddress(lNextHope+";lr")); - //lRouteHeader.setParameter("lr", null); - if (lMultipleRoute != null) { - lMultipleRoute.addTop(lRouteHeader); - lSipMessage.setRoutes(lMultipleRoute); - } else { - lSipMessage.addRouteHeader(lRouteHeader); - } - // add Via only udp - SipUtils.addVia(mProvider,lSipMessage); - // add recordRoute - SipUtils.addRecordRoute(mProvider,lSipMessage); - - } else { - //response - //1 remove via header - SipUtils.removeVia(mProvider,lSipMessage); - } - try { - mSdpProcessor.processSdpBeforeSendingToSipUA( lSipMessage); - } catch (P2pProxyException e) { - mLog.error("enable to re-write sdp",e); - } - - mProvider.sendMessage(lSipMessage); - // - } -public void updateRegistration(Registration aRegistration, Message aRegistrationMessage) throws P2pProxyException { - try { - if (aRegistration.NetResources == null) { - // new registration, create pipe - NetworkResources lRegistration = new NetworkResources(aRegistration.From,mJxtaNetworkManager); - aRegistration.NetResources = lRegistration; - lRegistration.addPipeMsgListener(this); - } - - ((NetworkResources) aRegistration.NetResources).publish(aRegistration.Expiration); - } catch (Exception e) { - throw new P2pProxyException(e); - } - -} - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/peers/NetworkResources.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/peers/NetworkResources.java deleted file mode 100644 index 328ff389..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/peers/NetworkResources.java +++ /dev/null @@ -1,93 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -NetworkResources.java -- connection to a jxta network. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.sipproxy.peers; - -import java.io.IOException; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.log4j.Logger; - -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.MessageDispatcher; -import org.linphone.p2pproxy.core.media.jxtaudpproxy.RtpSessionImpl; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.pipe.InputPipe; - -import net.jxta.pipe.PipeMsgListener; - -/** - * @author jehan - * - */ -public class NetworkResources { - public enum State {idle,offering,answering,ready} - private static String PIPE_ID="org.linphone.p2pproxy.bidi-pipe.id"; - private final InputPipe mInputPipe; - private MessageDispatcher mMessageDispatcher = new MessageDispatcher(); - private Map mRtpSessionTab = new HashMap(); - private final JxtaNetworkManager mJxtaNetworkManager; - private final static Logger mLog = Logger.getLogger(NetworkResources.class); - private State mState = State.idle; - public NetworkResources(String aUserName, JxtaNetworkManager aJxtaNetworkManager) throws IOException { - mJxtaNetworkManager = aJxtaNetworkManager; - mInputPipe = mJxtaNetworkManager.createPipe(PIPE_ID+"-"+aUserName, aUserName, mMessageDispatcher); - } - public void release(){ - ; - } - public void putRtpSession(String key,RtpSessionImpl value) { - mRtpSessionTab.put(key, value); - addPipeMsgListener(value); - } - public RtpSessionImpl getRtpSession(String key) { - return mRtpSessionTab.get(key); - } - public boolean hasRtpSession(String key) { - return mRtpSessionTab.containsKey(key); - } - public void addPipeMsgListener(PipeMsgListener aPipeMsgListener) { - mMessageDispatcher.addPipeMsgListener( aPipeMsgListener); - } - public void publish(long anExpiration) throws IOException { - DiscoveryService lDiscoveryService = mJxtaNetworkManager.getPeerGroup().getDiscoveryService(); - - if (anExpiration > 0) { - //publish sip pipe - lDiscoveryService.publish(mInputPipe.getAdvertisement(), anExpiration, anExpiration); - } else { - //first flush in any cases - lDiscoveryService.flushAdvertisement(mInputPipe.getAdvertisement()); - mInputPipe.close(); - } - - mLog.info("adv ["+mInputPipe.getAdvertisement().getName()+"] published expire ["+anExpiration+"]"); - } - - public State getState() { - return mState; - } - public void setState(State state) { - mState = state; - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/superpeers/JxtaNetworkResources.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/superpeers/JxtaNetworkResources.java deleted file mode 100644 index 04a4d8da..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/superpeers/JxtaNetworkResources.java +++ /dev/null @@ -1,64 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -JxtaNetworkResources.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.sipproxy.superpeers; - -import java.io.IOException; - -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.AdvertisementFactory; -import net.jxta.id.IDFactory; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.P2pUserProfileAdvertisement; - - -public class JxtaNetworkResources { - private final JxtaNetworkManager mJxtaNetworkManager; - private final static Logger mLog = Logger.getLogger(JxtaNetworkResources.class); - private final P2pUserRegistrationAdvertisement mP2pUserRegistrationAdvertisement; - private final static long EXPIRATION= 120000; - - JxtaNetworkResources (String aUserName, JxtaNetworkManager aJxtaNetworkManager,String aRegistrarAddress) { - mJxtaNetworkManager = aJxtaNetworkManager; - mP2pUserRegistrationAdvertisement = (P2pUserRegistrationAdvertisement) AdvertisementFactory.newAdvertisement(P2pUserRegistrationAdvertisement.getAdvertisementType()); - mP2pUserRegistrationAdvertisement.setID(IDFactory.newCodatID(mJxtaNetworkManager.getPeerGroup().getPeerGroupID(), aUserName.toString().getBytes())); - mP2pUserRegistrationAdvertisement.setUserName(aUserName.toString()); - mP2pUserRegistrationAdvertisement.setRegistrarAddress(aRegistrarAddress.toString()); - mLog.info("creating network resource for user ["+aUserName+"] on registrar ["+aRegistrarAddress+"]"); - } - - void publish(long aLiveTime) throws P2pProxyException { - try { - DiscoveryService lDiscoveryService = mJxtaNetworkManager.getPeerGroup().getDiscoveryService(); - if (aLiveTime > 0) { - lDiscoveryService.publish(mP2pUserRegistrationAdvertisement,aLiveTime,EXPIRATION); - } else { - //first flush in any cases - lDiscoveryService.flushAdvertisement(mP2pUserRegistrationAdvertisement); - } - } catch (IOException e1) { - throw new P2pProxyException(e1); - } - mLog.info("publishing P2pUserRegistration Advertisement ["+mP2pUserRegistrationAdvertisement+"]published expire ["+aLiveTime+"]"); - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/superpeers/P2pUserRegistrationAdvertisement.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/superpeers/P2pUserRegistrationAdvertisement.java deleted file mode 100644 index 4e682197..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/superpeers/P2pUserRegistrationAdvertisement.java +++ /dev/null @@ -1,271 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pUserRegistrationAdvertisement.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.sipproxy.superpeers; - - -import java.io.Serializable; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Enumeration; - -import org.apache.log4j.Logger; - - - - -import net.jxta.document.Advertisement; -import net.jxta.document.AdvertisementFactory; -import net.jxta.document.Attributable; -import net.jxta.document.Document; -import net.jxta.document.Element; -import net.jxta.document.ExtendableAdvertisement; -import net.jxta.document.MimeMediaType; -import net.jxta.document.StructuredDocument; -import net.jxta.document.StructuredDocumentFactory; -import net.jxta.document.TextElement; -import net.jxta.id.ID; -import net.jxta.id.IDFactory; - -/** - * derivated from jxta Advertisement tutorial - *
            - * <?xml version="1.0"?>
            - * <!DOCTYPE jxta:System>
            - * <jxta:System xmlns:jxta="http://jxta.org">
            - *   <id>NULL </id>
            - *   <user-name>address where the sip endpoint is currently registered</user-name>
            - *   <registrar-address>address where the sip endpoint is currently registered</registrar-address>
            - * </jxta:System>
            - * 
            - */ -public class P2pUserRegistrationAdvertisement extends ExtendableAdvertisement implements Comparable, Cloneable, Serializable { - /** - * Instantiator - */ - public static class Instantiator implements AdvertisementFactory.Instantiator { - - /** - * Returns the identifying type of this Advertisement. - * - * @return String the type of advertisement - */ - public String getAdvertisementType() { - return P2pUserRegistrationAdvertisement.getAdvertisementType(); - } - - /** - * Constructs an instance of Advertisement matching the - * type specified by the advertisementType parameter. - * - * @return The instance of Advertisement or null if it - * could not be created. - */ - public Advertisement newInstance() { - return new P2pUserRegistrationAdvertisement(); - } - - /** - * Constructs an instance of Advertisement matching the - * type specified by the advertisementType parameter. - * - * @param root Specifies a portion of a StructuredDocument which will - * be converted into an Advertisement. - * @return The instance of Advertisement or null if it - * could not be created. - */ - public Advertisement newInstance(net.jxta.document.Element root) { - return new P2pUserRegistrationAdvertisement(root); - } - } - private ID mId ;; - private String mRegistrarAddress; - private String mUserUri; - public final static String REGISTRAR_ADDRESS_TAG = "registrar-address"; - public final static String USER_NAME_TAG = "registration-user-name"; - private final static String ID_TAG = "ID"; - private final static String[] mIndexs = {USER_NAME_TAG}; - private final static Logger mLog = Logger.getLogger(P2pUserRegistrationAdvertisement.class); - /** - * - */ - public P2pUserRegistrationAdvertisement(Element root) { - - TextElement doc = (TextElement) root; - - if (!getAdvertisementType().equals(doc.getName())) { - throw new IllegalArgumentException("Could not construct : " + getClass().getName() + "from doc containing a " + doc.getName()); - } - initialize(doc); - - } - public P2pUserRegistrationAdvertisement() { - - // TODO Auto-generated constructor stub - } - /* (non-Javadoc) - * @see net.jxta.document.ExtendableAdvertisement#getDocument(net.jxta.document.MimeMediaType) - */ - @Override - public Document getDocument(MimeMediaType asMimeType) { - - StructuredDocument adv = StructuredDocumentFactory.newStructuredDocument(asMimeType, - getAdvertisementType()); - if (adv instanceof Attributable) { - ((Attributable) adv).addAttribute("xmlns:jxta", "http://jxta.org"); - } - Element e; - e = adv.createElement(ID_TAG, getID().toString()); - adv.appendChild(e); - e = adv.createElement(USER_NAME_TAG, getUserName().trim()); - adv.appendChild(e); - e = adv.createElement(REGISTRAR_ADDRESS_TAG, getRegistrarAddress().trim()); - adv.appendChild(e); - return adv; - } - - @Override - public ID getID() { - return mId; - } - - @Override - public String[] getIndexFields() { - return mIndexs; - } - public static String getAdvertisementType() { - return "jxta:p2p-proxy-user-registration"; - } - /* (non-Javadoc) - * @see net.jxta.document.Advertisement#toString() - */ - @Override - public String toString() { - // TODO Auto-generated method stub - return super.toString(); - } - public int compareTo(Object other) { - return getID().toString().compareTo(other.toString()); - } - /** - * Intialize a System advertisement from a portion of a structured document. - * - * @param root document root - */ - protected void initialize(Element root) { - if (!TextElement.class.isInstance(root)) { - throw new IllegalArgumentException(getClass().getName() + - " only supports TextElement"); - } - TextElement doc = (TextElement) root; - if (!doc.getName().equals(getAdvertisementType())) { - throw new IllegalArgumentException("Could not construct : " - + getClass().getName() + "from doc containing a " + - doc.getName()); - } - Enumeration elements = doc.getChildren(); - while (elements.hasMoreElements()) { - TextElement elem = (TextElement) elements.nextElement(); - if (!handleElement(elem)) { - mLog.warn("Unhandleded element \'" + elem.getName() + "\' in " + doc.getName()); - } - } - } - /** - * Process an individual element from the document. - * - * @param elem the element to be processed. - * @return true if the element was recognized, otherwise false. - */ - protected boolean handleElement(TextElement elem) { - if (elem.getName().equals(ID_TAG)) { - try { - URI id = new URI(elem.getTextValue()); - setID(IDFactory.fromURI(id)); - } catch (URISyntaxException badID) { - throw new IllegalArgumentException("unknown ID format in advertisement: " + - elem.getTextValue()); - } - catch (ClassCastException badID) { - throw new IllegalArgumentException("Id is not a known id type: " + - elem.getTextValue()); - } - return true; - } else if (elem.getName().equals(USER_NAME_TAG)) { - setUserName(elem.getTextValue()); - return true; - } else if (elem.getName().equals(REGISTRAR_ADDRESS_TAG)) { - setRegistrarAddress(elem.getTextValue()); - return true; - } else { - return false; - } - } - public void setID(ID id) { - mId = id; - } - @Override - public String getBaseAdvType() { - // TODO Auto-generated method stub - return null; - } - /** - * @return Returns the mName. - */ - public String getRegistrarAddress() { - return mRegistrarAddress; - } - /** - * @param name The mName to set. - */ - public void setRegistrarAddress(String anAddress) { - mRegistrarAddress = anAddress; - } - /** - * @return Returns the mName. - */ - public String getUserName() { - return mUserUri; - } - /** - * @param name The mName to set. - */ - public void setUserName(String anName) { - mUserUri = anName; - } - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - if (obj instanceof P2pUserRegistrationAdvertisement) { - P2pUserRegistrationAdvertisement adv = (P2pUserRegistrationAdvertisement) obj; - return getID().equals(adv.getID()); - } - - return false; - - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/superpeers/SuperPeerProxy.java b/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/superpeers/SuperPeerProxy.java deleted file mode 100644 index fd68158c..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/sipproxy/superpeers/SuperPeerProxy.java +++ /dev/null @@ -1,133 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -SuperPeerProxy.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.sipproxy.superpeers; - -import java.io.IOException; -import java.util.List; -import java.util.Map; - - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyUserNotFoundException; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.P2pProxyAdvertisementNotFoundException; -import org.linphone.p2pproxy.core.sipproxy.RegistrationHandler; -import org.linphone.p2pproxy.core.sipproxy.SipProxy; -import org.linphone.p2pproxy.core.sipproxy.SipUtils; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar.Registration; - -import org.zoolu.sip.address.NameAddress; -import org.zoolu.sip.address.SipURL; -import org.zoolu.sip.header.Header; -import org.zoolu.sip.header.MultipleHeader; -import org.zoolu.sip.header.RecordRouteHeader; -import org.zoolu.sip.header.RequestLine; -import org.zoolu.sip.header.RouteHeader; -import org.zoolu.sip.message.Message; -import org.zoolu.sip.provider.SipProvider; - -public class SuperPeerProxy implements SipProxy, RegistrationHandler { - private final JxtaNetworkManager mJxtaNetworkManager; - private final String mRegistrarAddress; - private final Map mRegistrationTab; - private static Logger mLog = Logger.getLogger(SuperPeerProxy.class); - - public SuperPeerProxy(JxtaNetworkManager aJxtaNetworkManager, String aRegistrarAddress, Map aRegistrationTab ) { - mJxtaNetworkManager = aJxtaNetworkManager; - mRegistrarAddress = aRegistrarAddress; - mRegistrationTab = aRegistrationTab; - } - public void proxyRequest(SipProvider aProvider, Message aMessage) throws P2pProxyException { - // 1 check if user is a local user - - if (mLog.isDebugEnabled()) mLog.debug("processing request " +aMessage); - String lTo = aMessage.getToHeader().getNameAddress().getAddress().toString(); - SipURL lNextHope = null; - - //ok need to find the root - //is local ? - synchronized (mRegistrationTab) { - if (mRegistrationTab.containsKey(lTo)) { - //great, just need to get it - lNextHope = new SipURL(mRegistrationTab.get(lTo).Contact); - } else { - if (aMessage.isInvite() || aMessage.isCancel()) { - //need to found the right proxy - try { - List lAdvList = (List) mJxtaNetworkManager.getAdvertisementList(null, P2pUserRegistrationAdvertisement.USER_NAME_TAG,lTo, true); - lNextHope = new SipURL(lAdvList.get(0).getRegistrarAddress()); - } catch (Exception e) { - throw new P2pProxyUserNotFoundException("user ["+lTo+"] not found",e); - } - - } else { - //nop - } - } - } - if (aMessage.isInvite() || aMessage.isCancel()) { - //check if invite - // add recordRoute - SipUtils.addRecordRoute(aProvider,aMessage); - } - - if (lNextHope == null) { - // not for us - //just look at route set - MultipleHeader lMultipleRoute = aMessage.getRoutes(); - - if (lMultipleRoute != null && lMultipleRoute.isEmpty()== false) { - RouteHeader lRouteHeader = new RouteHeader(lMultipleRoute.getTop()); - lNextHope = lRouteHeader.getNameAddress().getAddress(); - } else { - // last proxy, get route from request uri - //check if we know the user - lNextHope = aMessage.getRequestLine().getAddress(); - } - - } - - aMessage.setRequestLine(new RequestLine(aMessage.getRequestLine().getMethod(), lNextHope)); - aProvider.sendMessage(aMessage); - - } - - public void proxyResponse(SipProvider aProvider, Message aMessage) throws P2pProxyException { - if (mLog.isInfoEnabled()) mLog.info("processing response " +aMessage); - //1 remove via header - SipUtils.removeVia(aProvider,aMessage); - aProvider.sendMessage(aMessage); - - } - - public void updateRegistration(Registration aRegistration, Message aRegistrationMessage) throws P2pProxyException { - if (aRegistration.NetResources == null) { - // new registration, create adv - JxtaNetworkResources lRegistration = new JxtaNetworkResources(aRegistration.From, mJxtaNetworkManager,mRegistrarAddress); - aRegistration.NetResources = lRegistration; - } - - ((JxtaNetworkResources) aRegistration.NetResources).publish(aRegistration.Expiration); - } - public String getSipProxyRegistrarAddress() { - return mRegistrarAddress; - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/stun/AddressInfo.java b/p2pproxy/src/org/linphone/p2pproxy/core/stun/AddressInfo.java deleted file mode 100644 index 910da9b6..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/stun/AddressInfo.java +++ /dev/null @@ -1,67 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -AddressInfo.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.stun; - -import java.net.InetSocketAddress; - -public class AddressInfo { - enum Mode { - open - , blockedUDP - , fullCone - , restrictedCone - , portRestrictedCone - , symmetric - , symmetricUDPFirewall - , unknown - } - private final InetSocketAddress mPrivateAddress; - private InetSocketAddress mPublicAddress; - private Mode mMode = Mode.unknown; - - public AddressInfo(InetSocketAddress aPrivateAddress) { - mPrivateAddress = aPrivateAddress; - } - public Mode getMode() { - return mMode; - } - public void setMode(Mode aMode) { - mMode = aMode; - } - public InetSocketAddress getPrivateAddress() { - return mPrivateAddress; - } - public InetSocketAddress getPublicAddress() { - return mPublicAddress; - } - public void setPublicAddress(InetSocketAddress aPublicAddress) { - mPublicAddress = aPublicAddress; - } - public boolean isNated() { - if (mPublicAddress != null) { - return mPublicAddress.equals(mPrivateAddress); - } else { - return false; - } - } - public String toString() { - return "private ["+mPrivateAddress+"] public ["+mPublicAddress+"] mode ["+mMode+"]"; - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/stun/DiscoveryInfo.java b/p2pproxy/src/org/linphone/p2pproxy/core/stun/DiscoveryInfo.java deleted file mode 100644 index 07e2e261..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/stun/DiscoveryInfo.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package org.linphone.p2pproxy.core.stun; - -import java.net.*; - -public class DiscoveryInfo { - private boolean error = false; - private int errorResponseCode = 0; - private String errorReason; - private boolean blockedUDP = false; - private boolean fullCone = false; - private boolean symmetric = false; - private InetSocketAddress mTestSocketAddress; - private InetSocketAddress mPublicSocketAddress; - - public DiscoveryInfo(InetSocketAddress aTestSocketAddress) { - mTestSocketAddress = aTestSocketAddress; - } - - public boolean isError() { - return error; - } - - public void setError(int responseCode, String reason) { - this.error = true; - this.errorResponseCode = responseCode; - this.errorReason = reason; - } - - - - public boolean isBlockedUDP() { - if (error) return false; - return blockedUDP; - } - - public void setBlockedUDP() { - this.blockedUDP = true; - } - - public boolean isFullCone() { - if (error) return false; - return fullCone; - } - - public void setFullCone() { - this.fullCone = true; - } - - public boolean isSymmetric() { - if (error) return false; - return symmetric; - } - - public void setSymmetric() { - this.symmetric = true; - } - - public InetSocketAddress getLocalSocketAddress() { - return mTestSocketAddress; - } - - public InetSocketAddress getPublicSocketAddress() { - return mPublicSocketAddress; - } - public void setPublicSocketAddress(InetSocketAddress address) { - mPublicSocketAddress = address; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("Network interface: "); - try { - sb.append(NetworkInterface.getByInetAddress(mTestSocketAddress.getAddress()).getName()); - } catch (SocketException se) { - sb.append("unknown"); - } - sb.append("\n"); - sb.append("Local Socket address: "); - sb.append(mTestSocketAddress); - sb.append("\n"); - if (error) { - sb.append(errorReason + " - Responsecode: " + errorResponseCode); - return sb.toString(); - } - sb.append("Result: "); - if (blockedUDP) sb.append("Firewall blocks UDP.\n"); - if (fullCone) sb.append("Full Cone NAT handles connections.\n"); - if (symmetric) sb.append("Symmetric Cone NAT handles connections.\n"); - sb.append("Public IP address: "); - if (mPublicSocketAddress != null) { - sb.append(mPublicSocketAddress.toString()); - } else { - sb.append("unknown"); - } - sb.append("\n"); - return sb.toString(); - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/stun/StunClient.java b/p2pproxy/src/org/linphone/p2pproxy/core/stun/StunClient.java deleted file mode 100644 index 2892902d..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/stun/StunClient.java +++ /dev/null @@ -1,200 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -StunClient.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - */ -package org.linphone.p2pproxy.core.stun; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetSocketAddress; -import java.net.PortUnreachableException; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.URI; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.P2pProxyAdvertisementNotFoundException; -import org.linphone.p2pproxy.core.media.MediaResourceService; -import org.linphone.p2pproxy.core.media.MediaResoureUnreachableException; -import org.linphone.p2pproxy.core.sipproxy.NetworkResourceAdvertisement; -import de.javawi.jstun.attribute.ChangeRequest; -import de.javawi.jstun.attribute.ErrorCode; -import de.javawi.jstun.attribute.MappedAddress; -import de.javawi.jstun.attribute.MessageAttribute; -import de.javawi.jstun.attribute.MessageAttributeException; -import de.javawi.jstun.attribute.MessageAttributeParsingException; -import de.javawi.jstun.attribute.ResponseAddress; -import de.javawi.jstun.header.MessageHeader; -import de.javawi.jstun.header.MessageHeaderParsingException; -import de.javawi.jstun.util.Address; -import de.javawi.jstun.util.UtilityException; - -public class StunClient { - private static Logger mLog = Logger.getLogger(StunClient.class); - private List mStunServerList; - JxtaNetworkManager mJxtaNetworkManager; - - private int SO_TIME_OUT = 300; - - public StunClient(String[] aStunServerList) { - List lAddressList = new ArrayList(); - for (String lStunInstance:aStunServerList) { - URI lUri = URI.create(lStunInstance); - InetSocketAddress lInetSocketAddress = new InetSocketAddress(lUri.getHost(),lUri.getPort()); - lAddressList.add(lInetSocketAddress); - } - mStunServerList = lAddressList; - } - StunClient(List aStunServerList) { - mStunServerList = aStunServerList; - } - public StunClient(JxtaNetworkManager aJxtaNetworkManager) throws P2pProxyException { - //need to acquire stun server address() - mJxtaNetworkManager = aJxtaNetworkManager; - try { - mStunServerList = acquireStunServerAddress(); - } catch (Exception e) { - throw new P2pProxyException(e); - } - } - public List getStrunServerList() { - return mStunServerList; - } - private List acquireStunServerAddress() throws P2pProxyAdvertisementNotFoundException, InterruptedException, IOException { - List lStunServerAdv = (List) mJxtaNetworkManager.getAdvertisementList(null, MediaResourceService.ADV_NAME, true); - List lSocketAddressList = new ArrayList(lStunServerAdv.size()); - for (NetworkResourceAdvertisement lNetworkResourceAdvertisement: lStunServerAdv) { - URI lServerUri = URI.create(lNetworkResourceAdvertisement.getAddress()); - lSocketAddressList.add(new InetSocketAddress(lServerUri.getHost(),lServerUri.getPort())); - } - return lSocketAddressList; - } - - public AddressInfo computeAddressInfo(DatagramSocket lLocalSocket) throws PortUnreachableException, P2pProxyException { - AddressInfo lAddressInfo = new AddressInfo((InetSocketAddress) lLocalSocket.getLocalSocketAddress()); - InetSocketAddress lCurrentMediaServerAddress = null; - try { - DiscoveryInfo lDiscoveryInfo = new DiscoveryInfo((InetSocketAddress) lLocalSocket.getLocalSocketAddress()); - //1 bind request - bindRequest(lDiscoveryInfo,lLocalSocket,lLocalSocket,null,lCurrentMediaServerAddress = mStunServerList.get(0)); - //2 bind request - if (mStunServerList.size() > 1) { - //open new socket - DatagramSocket lDatagramSocket = new DatagramSocket(); - bindRequest(lDiscoveryInfo,lDatagramSocket, lLocalSocket, lDiscoveryInfo.getPublicSocketAddress(),lCurrentMediaServerAddress = mStunServerList.get(1)); - lDatagramSocket.close(); - } - //analyse - - lAddressInfo.setPublicAddress(lDiscoveryInfo.getPublicSocketAddress()); - - } catch (PortUnreachableException pex) { - MediaResoureUnreachableException lExeption = new MediaResoureUnreachableException(pex); - lExeption.setRourceAddress(lCurrentMediaServerAddress.getAddress().getHostAddress()+":"+lCurrentMediaServerAddress.getPort()); - throw lExeption; - } catch (Exception e) { - throw new P2pProxyException(e); - } - return lAddressInfo; - } - private void bindRequest(DiscoveryInfo aDiscoveryInfo,DatagramSocket aLocalSocket, DatagramSocket aResponseSocket,InetSocketAddress aResponseAddress, InetSocketAddress aStunAddress) throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageHeaderParsingException, P2pProxyException { - int timeSinceFirstTransmission = 0; - int lSoTimeOut = SO_TIME_OUT; - while (true) { - try { - aLocalSocket.setReuseAddress(true); - aLocalSocket.connect(aStunAddress); - aLocalSocket.setSoTimeout(lSoTimeOut); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - - ChangeRequest changeRequest = new ChangeRequest(); - sendMH.addMessageAttribute(changeRequest); - if (!((InetSocketAddress)aLocalSocket.getLocalSocketAddress()).equals((InetSocketAddress)aResponseSocket.getLocalSocketAddress()) && aResponseAddress != null) { - // add response address - ResponseAddress lResponseAddress = new ResponseAddress(); - lResponseAddress.setAddress(new Address(aResponseAddress.getAddress().getHostAddress())); - try { - lResponseAddress.setPort(aResponseAddress.getPort()); - sendMH.addMessageAttribute(lResponseAddress); - } catch (MessageAttributeException e) { - mLog.info("Cannot set Response address ["+lResponseAddress+"]"); - } - } - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - aLocalSocket.send(send); - - MessageHeader receiveMH = new MessageHeader(); - while (!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - aResponseSocket.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - - MappedAddress lMappedAddress = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress); - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - aDiscoveryInfo.setError(ec.getResponseCode(), ec.getReason()); - throw new P2pProxyException("Message header contains an Errorcode message attribute. ["+ec+"]"); - } - if ((lMappedAddress == null)) { - throw new P2pProxyException("Response does not contain a Mapped Address message attribute."); - - } else { - if (aLocalSocket.getLocalSocketAddress().equals(aResponseSocket.getLocalSocketAddress())) { - aDiscoveryInfo.setPublicSocketAddress(new InetSocketAddress(lMappedAddress.getAddress().getInetAddress(),lMappedAddress.getPort())); - } else { - aDiscoveryInfo.setFullCone(); - } - } - return; - - } catch (PortUnreachableException pex ) { - throw pex; - } - catch (SocketTimeoutException ste) { - if (timeSinceFirstTransmission < 7900) { - if (mLog.isInfoEnabled()) mLog.info("Socket timeout while receiving the response."); - timeSinceFirstTransmission += lSoTimeOut; - int timeoutAddValue = (timeSinceFirstTransmission * 2); - if (timeoutAddValue > 1600) timeoutAddValue = 1600; - lSoTimeOut = timeoutAddValue; - } else { - // node is not capable of udp communication - if (mLog.isInfoEnabled()) mLog.info("Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); - if (aLocalSocket.getLocalSocketAddress().equals(aResponseSocket.getLocalSocketAddress())) { - aDiscoveryInfo.setBlockedUDP(); - } else { - aDiscoveryInfo.setSymmetric(); - } - if (mLog.isInfoEnabled()) mLog.info("Node is not capable of UDP communication."); - return ; - } - } - } - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/stun/StunServer.java b/p2pproxy/src/org/linphone/p2pproxy/core/stun/StunServer.java deleted file mode 100644 index 10261cb2..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/stun/StunServer.java +++ /dev/null @@ -1,148 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -StunServer.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.stun; - - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.SocketException; -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.core.GenericUdpSession; -import org.linphone.p2pproxy.core.ServiceProvider; - -import de.javawi.jstun.attribute.ChangeRequest; -import de.javawi.jstun.attribute.ErrorCode; -import de.javawi.jstun.attribute.MappedAddress; -import de.javawi.jstun.attribute.MessageAttributeException; -import de.javawi.jstun.attribute.ResponseAddress; -import de.javawi.jstun.attribute.SourceAddress; -import de.javawi.jstun.attribute.UnknownAttribute; -import de.javawi.jstun.attribute.UnknownMessageAttributeException; -import de.javawi.jstun.attribute.MessageAttributeInterface.MessageAttributeType; -import de.javawi.jstun.header.MessageHeader; -import de.javawi.jstun.header.MessageHeaderParsingException; -import de.javawi.jstun.header.MessageHeaderInterface.MessageHeaderType; -import de.javawi.jstun.util.Address; - - -/* - * This class implements a STUN server as described in RFC 3489. - * neither change port nor change address are implemented - */ -public class StunServer implements GenericUdpSession.MessageHandler { - private static Logger mLog = Logger.getLogger(StunServer.class); - private final DatagramSocket mSocket; - - public StunServer(DatagramSocket mListeningSocket) throws SocketException { - mSocket = mListeningSocket; - } - - public void onMessage(DatagramPacket lMessage) { - // derivated from JSTUN (Thomas King) - MessageHeader receiveMH = null; - try { - receiveMH = MessageHeader.parseHeader(lMessage.getData()); - } catch (MessageHeaderParsingException e1) { - if (mLog.isInfoEnabled()) mLog.info("not a stun message"); - return; - } - - try { - receiveMH.parseAttributes(lMessage.getData()); - if (receiveMH.getType() == MessageHeaderType.BindingRequest) { - ChangeRequest cr = (ChangeRequest) receiveMH.getMessageAttribute(MessageAttributeType.ChangeRequest); - if (cr == null) throw new MessageAttributeException("Message attribute change request is not set."); - ResponseAddress ra = (ResponseAddress) receiveMH.getMessageAttribute(MessageAttributeType.ResponseAddress); - - MessageHeader sendMH = new MessageHeader(MessageHeaderType.BindingResponse); - sendMH.setTransactionID(receiveMH.getTransactionID()); - - // Mapped address attribute - MappedAddress ma = new MappedAddress(); - ma.setAddress(new Address(lMessage.getAddress().getAddress())); - ma.setPort(lMessage.getPort()); - sendMH.addMessageAttribute(ma); - if ((!cr.isChangePort()) && (!cr.isChangeIP())) { - if (mLog.isInfoEnabled()) mLog.info("Nothing received in Change Request attribute"); - // Source address attribute - SourceAddress sa = new SourceAddress(); - sa.setAddress(new Address(mSocket.getLocalAddress().getAddress())); - sa.setPort(mSocket.getLocalPort()); - sendMH.addMessageAttribute(sa); - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - if (ra != null) { - send.setPort(ra.getPort()); - send.setAddress(ra.getAddress().getInetAddress()); - } else { - send.setPort(lMessage.getPort()); - send.setAddress(lMessage.getAddress()); - } - mSocket.send(send); - if (mLog.isInfoEnabled()) mLog.info(mSocket.getLocalAddress().getHostAddress() + ":" + mSocket.getLocalPort() + " send Binding Response to " + send.getAddress().getHostAddress() + ":" + send.getPort()); - } else { -// Generate Binding error response - sendMH = new MessageHeader(MessageHeaderType.BindingErrorResponse); - sendMH.setTransactionID(receiveMH.getTransactionID()); - ErrorCode lErrorCode = new ErrorCode(); - lErrorCode.setResponseCode(400); //bad request - sendMH.addMessageAttribute(lErrorCode); - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - send.setPort(lMessage.getPort()); - send.setAddress(lMessage.getAddress()); - mSocket.send(send); - if (mLog.isInfoEnabled()) mLog.info("cannot handle cr ["+cr+"] attibute"); - } - } - } catch ( Exception e) { - - try { - // Generate Binding error response - - MessageHeader sendMH = new MessageHeader(MessageHeaderType.BindingErrorResponse); - sendMH.setTransactionID(receiveMH.getTransactionID()); - - if (e instanceof UnknownMessageAttributeException) { - // Unknown attributes - UnknownAttribute ua = new UnknownAttribute(); - ua.addAttribute(((UnknownMessageAttributeException) e).getType()); - sendMH.addMessageAttribute(ua); - } else { - ErrorCode lErrorCode = new ErrorCode(); - lErrorCode.setResponseCode(500); - sendMH.addMessageAttribute(lErrorCode); - } - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - send.setPort(lMessage.getPort()); - send.setAddress(lMessage.getAddress()); - mSocket.send(send); - mLog.error(" send Binding Error Response to " + send.getAddress().getHostAddress() + ":" + send.getPort(),e); - } catch(Exception e1) { - mLog.error("cannot handle error", e1); - } - } - - } - - -} \ No newline at end of file diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/utils/AccountManagerCli.java b/p2pproxy/src/org/linphone/p2pproxy/core/utils/AccountManagerCli.java deleted file mode 100644 index 36951c14..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/utils/AccountManagerCli.java +++ /dev/null @@ -1,129 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -AccountManagerCli.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.utils; - - -import javax.management.MBeanServerConnection; -import javax.management.MBeanServerInvocationHandler; -import javax.management.ObjectName; -import javax.management.remote.JMXConnector; -import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXServiceURL; - -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyUserAlreadyExistException; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.P2pProxyAccountManagementMBean; -import org.linphone.p2pproxy.core.P2pProxyMain; -import org.linphone.p2pproxy.core.P2pProxyMainMBean; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar; - -public class AccountManagerCli { - public final static String USER_ADD = "user-add"; - public final static String RELOAD_TRACE = "reload-trace"; - /** - * @param args - * @throws Exception - */ - public static void main(String[] args) { - try { - // get other params - String lCommand = "null"; - int lCommandArgsIndex=0; - for (int i=0; i < args.length; i=i+2) { - String argument = args[i]; - if (argument.equals("-c")) { - lCommand = args[i + 1]; - //nop - } else { - // no more option, takes args - lCommandArgsIndex = i; - - } - } - // Create an RMI connector client and - // connect it to the RMI connector server - // - JMXServiceURL lJMXServiceURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:6789/jmxrmi"); - JMXConnector lJMXConnector = JMXConnectorFactory.connect(lJMXServiceURL, null); - - // Get an MBeanServerConnection - // - MBeanServerConnection lMBeanServerConnection = lJMXConnector.getMBeanServerConnection(); - - - ObjectName lP2pProxyAccountManagementMBeanName = new ObjectName(P2pProxyMain.ACCOUNT_MGR_MBEAN_NAME); - ObjectName lP2pProxyMainMBeanName = new ObjectName(P2pProxyMain.MAIN_MBEAN_NAME); - - if (USER_ADD.equals(lCommand)) { - P2pProxyAccountManagementMBean lP2pProxyAccountManagementMBean = (P2pProxyAccountManagementMBean) - MBeanServerInvocationHandler.newProxyInstance( lMBeanServerConnection - ,lP2pProxyAccountManagementMBeanName - ,P2pProxyAccountManagementMBean.class - ,true); - - System.out.println("creating user account for "+args[lCommandArgsIndex]); - System.out.println("please wait"); - try { - lP2pProxyAccountManagementMBean.createAccount(args[lCommandArgsIndex]); - } catch (P2pProxyUserAlreadyExistException e) { - System.out.println("cannot create user account for "+args[lCommandArgsIndex]); - System.out.println("already exist"); - - } - System.out.println("done"); - } else if (RELOAD_TRACE.equals(lCommand)) { - P2pProxyMainMBean lP2pProxyMainMBean = (P2pProxyMainMBean) - MBeanServerInvocationHandler.newProxyInstance( lMBeanServerConnection - ,lP2pProxyMainMBeanName - ,P2pProxyMainMBean.class - ,true); - - System.out.println("loading trace config file..."); - try { - lP2pProxyMainMBean.loadTraceConfigFile(); - } catch (P2pProxyException e) { - System.out.println("cannot load trace config file"); - } - System.out.println("done"); - } - else { - - System.out.println("unkwon command ["+lCommand+"]"); - usage(); - System.exit(1); - } - lJMXConnector.close(); - }catch (Exception e) { - e.printStackTrace(); - System.exit(1); - } - - - - } - - private static void usage() { - System.out.println("p2pproxy-cli"); - System.out.println("-c : command to execute {"+USER_ADD+" | "+RELOAD_TRACE+"}"); - System.out.println("-p : client port"); - } -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/utils/DumpLocalCache.java b/p2pproxy/src/org/linphone/p2pproxy/core/utils/DumpLocalCache.java deleted file mode 100644 index 9f6f2d79..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/utils/DumpLocalCache.java +++ /dev/null @@ -1,45 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -DumpLocalCache.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.core.utils; - - - -import net.jxta.impl.util.cm.DumpCm; -import net.jxta.impl.util.cm.DumpCm.DumpCmCallback; - -public class DumpLocalCache { - - /** - * @param args - * @throws Exception - */ - public static void main(String[] args) throws Exception { - DumpCm.dump(args, new DumpCmCallback() { - - public void println(String val) { - System.out.println(val); - } - - }); - - } - -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/utils/Excecutor.java b/p2pproxy/src/org/linphone/p2pproxy/core/utils/Excecutor.java deleted file mode 100644 index 8101fedd..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/utils/Excecutor.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.linphone.p2pproxy.core.utils; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -public class Excecutor { - public final static ExecutorService pool = Executors.newCachedThreadPool();; -} diff --git a/p2pproxy/src/org/linphone/p2pproxy/core/utils/PeerGroupIdGenerator.java b/p2pproxy/src/org/linphone/p2pproxy/core/utils/PeerGroupIdGenerator.java deleted file mode 100644 index e78dbc0c..00000000 --- a/p2pproxy/src/org/linphone/p2pproxy/core/utils/PeerGroupIdGenerator.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.linphone.p2pproxy.core.utils; -import java.security.MessageDigest; - -import net.jxta.id.IDFactory; - -/* - * Created on Sep 14, 2007 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ - -public class PeerGroupIdGenerator { - - /** - * @param args - */ - public static void main(String[] args) { - - System.out.print(createInfrastructurePeerGroupID("p2p.linphone.org","p2pproxy")); - - } - public static final net.jxta.peergroup.PeerGroupID createInfrastructurePeerGroupID(String clearTextID, String function){ - System.out.println("Creating peer group ID = clearText:'"+clearTextID+"' , function:'"+function+"'"); - byte[] digest = generateHash(clearTextID, function); - net.jxta.peergroup.PeerGroupID peerGroupID = IDFactory.newPeerGroupID( digest ); - return peerGroupID; - } - /** - * Generates an SHA-1 digest hash of the string: clearTextID+"-"+function or: clearTextID if function was blank.

            - * - * Note that the SHA-1 used only creates a 20 byte hash.

            - * - * @param clearTextID A string that is to be hashed. This can be any string used for hashing or hiding data. - * @param function A function related to the clearTextID string. This is used to create a hash associated with clearTextID so that it is a uique code. - * - * @return array of bytes containing the hash of the string: clearTextID+"-"+function or clearTextID if function was blank. Can return null if SHA-1 does not exist on platform. - */ - public static final byte[] generateHash(String clearTextID, String function) { - String id; - String functionSeperator = "-"; - if (function == null) { - id = clearTextID; - } else { - ; - id = clearTextID + functionSeperator + function; - } - byte[] buffer = id.getBytes(); - - MessageDigest algorithm = null; - - try { - algorithm = MessageDigest.getInstance("MD5"); - } catch (Exception e) { - System.out.println("Cannot load selected Digest Hash implementation"); - e.printStackTrace(); - return null; - } - - - // Generate the digest. - algorithm.reset(); - algorithm.update(buffer); - - try{ - byte[] digest1 = algorithm.digest(); - return digest1; - }catch(Exception de){ - System.out.println("Failed to creat a digest."); - de.printStackTrace(); - return null; - } - } -} diff --git a/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pAutoConfigTester.java b/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pAutoConfigTester.java deleted file mode 100644 index 3ef51d0b..00000000 --- a/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pAutoConfigTester.java +++ /dev/null @@ -1,110 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pAutoConfigTester.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.test; - - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -import junit.framework.Assert; -import junit.framework.TestCase; -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.linphone.p2pproxy.api.P2pProxyInstance; -import org.linphone.p2pproxy.api.P2pProxyNetworkProbe; -import org.linphone.p2pproxy.api.P2pProxyInstance.Mode; -import org.linphone.p2pproxy.core.P2pProxyInstanceImpl; - -public class P2pAutoConfigTester extends TestCase { - static private P2pProxyInstance mP2pProxyInstance; - private final static Logger mLog = Logger.getLogger(P2pAutoConfigTester.class); - //@BeforeClass - public static void setUpBeforeClass() throws Exception { - // setup logging - PropertyConfigurator.configure("log4j.properties"); - -// // 1 setup relays -// String lRunString = "java -cp eclipsebuild:dependencies/*.jar "; -// //lRunString +=" -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"; -// lRunString +=" org.linphone.p2pproxy.core.P2pProxyMain"; -// lRunString +=" -jxta " +System.getProperty("user.home")+"/P2pAutoConfigTester-seeding"; -// lRunString +=" -sip 5040 -seeding-server "; -// lRunString +=" -seeding-relay http://"+InetAddress.getLocalHost().getHostAddress()+":"+P2pProxyInstance.BASE_HTTP; -// lRunString +=" -seeding-rdv http://"+InetAddress.getLocalHost().getHostAddress()+":"+P2pProxyInstance.BASE_HTTP; -// mLog.info("starting ["+lRunString+"]"); -// Process lProcess = Runtime.getRuntime().exec(lRunString); - - - // setup edge - mP2pProxyInstance = new P2pProxyInstanceImpl(); - mP2pProxyInstance.setMode(Mode.edge); - mP2pProxyInstance.setIndex(1); - mP2pProxyInstance.start(); - while (mP2pProxyInstance.isStarted() == false) Thread.sleep(500); - - } - - //@Before - public void setUp() throws Exception { - if (mP2pProxyInstance == null) { - setUpBeforeClass(); - } - } - /** - * - */ - public void testGetPublicAddress() { - try { - Assert.assertEquals("wrong public ip" ,mP2pProxyInstance.getManager().getPublicIpAddress().getHostAddress(), InetAddress.getLocalHost().getHostAddress()); - mLog.info("testGetPublicAddress ok"); - } catch (Exception e) { - mLog.error("testGetPublicAddress ko",e); - Assert.fail(e.getMessage()); - } - } - /** - * - */ - public void testProbeTcpSocket() { - try { - InetSocketAddress lSocketAddress = new InetSocketAddress(InetAddress.getLocalHost(),9500); - Assert.assertTrue("cannot prob" ,mP2pProxyInstance.getManager().probeSocket(lSocketAddress, P2pProxyNetworkProbe.Protocol.tcp)); - mLog.info("testProbeSocket ok"); - } catch (Exception e) { - mLog.error("testProbeSocket ko",e); - Assert.fail(e.getMessage()); - } - } - /** - * - */ - public void testProbeUdpSocket() { - try { - InetSocketAddress lSocketAddress = new InetSocketAddress(InetAddress.getLocalHost(),9500); - Assert.assertTrue("cannot prob" ,mP2pProxyInstance.getManager().probeSocket(lSocketAddress, P2pProxyNetworkProbe.Protocol.udp)); - mLog.info("testProbeSocket ok"); - } catch (Exception e) { - mLog.error("testProbeSocket ko",e); - Assert.fail(e.getMessage()); - } - } -} diff --git a/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyAccountManagementTester.java b/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyAccountManagementTester.java deleted file mode 100644 index 837845b4..00000000 --- a/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyAccountManagementTester.java +++ /dev/null @@ -1,86 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyAccountManagementTester.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.test; - -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.linphone.p2pproxy.api.P2pProxyException; -import org.linphone.p2pproxy.api.P2pProxyUserAlreadyExistException; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.P2pProxyAccountManagement; -import org.linphone.p2pproxy.core.P2pProxyAccountManagementMBean; -import org.linphone.p2pproxy.test.utils.P2pNetwork; - -import junit.framework.Assert; -import junit.framework.TestCase; - - -public class P2pProxyAccountManagementTester extends TestCase { - private final static Logger mLog = Logger.getLogger(P2pProxyAccountManagementTester.class); - static private P2pNetwork mP2pNetwork=null; - static private P2pProxyAccountManagementMBean mP2pProxyAccountManagementA; - static private final String USER_A = "sip:usera@p2pproxytester.org"; - /* (non-Javadoc) - * @see junit.framework.TestCase#setUp() - */ - @Override - protected void setUp() throws Exception { - if (mP2pNetwork == null) { - // setup logging - PropertyConfigurator.configure("log4j.properties"); - - mP2pNetwork = new P2pNetwork(0,1); - mP2pProxyAccountManagementA = new P2pProxyAccountManagement((JxtaNetworkManager) mP2pNetwork.getSuperPeers().get(0).getOpaqueNetworkManager()); - } - } - - /* (non-Javadoc) - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - // TODO Auto-generated method stub - super.tearDown(); - } - public void testCreateAccount() { - try { - //1 create - mP2pProxyAccountManagementA.createAccount(USER_A); - //2 delete - mP2pProxyAccountManagementA.deleteAccount(USER_A); - } catch (Exception e) { - mLog.error("testCreateAccount ko",e); - Assert.fail(e.getMessage()); - } - } - - public void testDeleteAccount() { - - } - - public void testCreateAlreadyExistingAccount() { - - } - public void testDeleteNotExistingAccount() { - - } - -} diff --git a/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyNatedNetworkTester.java b/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyNatedNetworkTester.java deleted file mode 100644 index 075af0cd..00000000 --- a/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyNatedNetworkTester.java +++ /dev/null @@ -1,48 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pProxyNatedNetworkTester.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.test; - -import java.net.InetAddress; -import java.util.ArrayList; - -import org.linphone.p2pproxy.api.P2pProxyInstance; -import org.linphone.p2pproxy.test.utils.P2pNetwork; -import org.linphone.p2pproxy.test.utils.SipClient; - - -public class P2pProxyNatedNetworkTester extends P2pProxyNetworkingTester { - - /* (non-Javadoc) - * @see org.linphone.p2pproxy.test.P2pProxyNetworkingTester#setUp() - */ - @Override - protected void setUp() throws Exception { - if (mP2pNetwork == null) { - mP2pNetwork = new P2pNetwork(1,1,0,0,10,true,System.getProperty("p2pproxy.publicAddressUser",System.getProperty("user.name")),System.getProperty("p2pproxy.publicAddress",InetAddress.getLocalHost().getHostName())); - mProxyInstanceList = new ArrayList(mP2pNetwork.getAllPeers()); - for (P2pProxyInstance lP2pProxyInstance:mProxyInstanceList) { - SipClient lSipClient = new SipClient(lP2pProxyInstance.getSipClientProvider(),lP2pProxyInstance.getSipClientName(),lP2pProxyInstance.getAdvertisementDiscoveryTimeout()); - lSipClient.register(); - mClientList.add(lSipClient); - } - } - } -} diff --git a/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyNetworkingTester.java b/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyNetworkingTester.java deleted file mode 100644 index e354b737..00000000 --- a/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyNetworkingTester.java +++ /dev/null @@ -1,148 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -P2pProxyNetworkTester.java - junit test for a whole p2pproxy network - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.test; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.linphone.p2pproxy.api.P2pProxyInstance; -import org.linphone.p2pproxy.test.utils.P2pNetwork; -import org.linphone.p2pproxy.test.utils.SipClient; - -import junit.framework.Assert; -import junit.framework.TestCase; - -public class P2pProxyNetworkingTester extends TestCase { - static { - PropertyConfigurator.configure("log4j.properties"); - } - static P2pNetwork mP2pNetwork =null; - static List mClientList = new ArrayList(); - static List mProxyInstanceList; - private final static Logger mLog = Logger.getLogger(P2pProxyNetworkingTester.class); - public P2pProxyNetworkingTester() { - // TODO Auto-generated constructor stub - } - - public P2pProxyNetworkingTester(String arg0) { - super(arg0); - // TODO Auto-generated constructor stub - } - public void testConnectedRdv() { - int lConnectedPeers=0; - for (P2pProxyInstance lSuperPeer:mP2pNetwork.getSuperPeers()) { - lConnectedPeers += lSuperPeer.getNumberOfconnectedPeers(); - } - Assert.assertEquals("all peer are not connected",mP2pNetwork.getEdgesPeers().size(),lConnectedPeers) ; - mLog.info("testConnectedPeers ok"); - } - /** - * test call from all peers - * - */ - public void testBasicCallFromAllPeers() { - try { - - for (int i=0;i(mP2pNetwork.getAllPeers()); - for (P2pProxyInstance lP2pProxyInstance:mProxyInstanceList) { - SipClient lSipClient = new SipClient(lP2pProxyInstance.getSipClientProvider(),lP2pProxyInstance.getSipClientName(),lP2pProxyInstance.getAdvertisementDiscoveryTimeout()); - lSipClient.register(); - mClientList.add(lSipClient); - } - Thread.sleep(10000); - } - } - - /* (non-Javadoc) - * @see junit.framework.TestCase#tearDown() - */ - @Override - protected void tearDown() throws Exception { - // TODO Auto-generated method stub - super.tearDown(); -// for (P2pProxyInstance lP2pProxyInstance:mProxyInstanceList) { -// SipClient lSipClient = new SipClient(lP2pProxyInstance.getSipClientProvider(),lP2pProxyInstance.getSipClientName()); -// lSipClient.unRegister(); -// } - } -} diff --git a/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyTester.java b/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyTester.java deleted file mode 100644 index 0c53f2fa..00000000 --- a/p2pproxy/test-src/org/linphone/p2pproxy/test/P2pProxyTester.java +++ /dev/null @@ -1,487 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -P2pProxyTester.java - junit test for p2pproxy - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.test; - -import java.net.DatagramSocket; -import java.util.Enumeration; -import java.util.List; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - - - -import net.jxta.discovery.DiscoveryEvent; -import net.jxta.discovery.DiscoveryListener; -import net.jxta.discovery.DiscoveryService; -import net.jxta.document.Advertisement; -import net.jxta.protocol.DiscoveryResponseMsg; - -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.linphone.p2pproxy.api.P2pProxyInstance; -import org.linphone.p2pproxy.api.P2pProxyInstance.Mode; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.P2pProxyAccountManagement; -import org.linphone.p2pproxy.core.P2pProxyAccountManagementMBean; -import org.linphone.p2pproxy.core.P2pProxyInstanceImpl; -import org.linphone.p2pproxy.core.P2pProxyMain; -import org.linphone.p2pproxy.core.sipproxy.NetworkResourceAdvertisement; -import org.linphone.p2pproxy.core.sipproxy.SipProxyRegistrar; -import org.linphone.p2pproxy.core.stun.AddressInfo; -import org.linphone.p2pproxy.core.stun.StunClient; -import org.linphone.p2pproxy.test.utils.DefaultCallListener; -import org.linphone.p2pproxy.test.utils.SipClient; -import org.zoolu.sip.address.NameAddress; -import org.zoolu.sip.call.Call; -import org.zoolu.sip.call.CallListener; -import org.zoolu.sip.message.Message; -import org.zoolu.sip.provider.SipProvider; - -import junit.framework.Assert; -import junit.framework.TestCase; - -public class P2pProxyTester extends TestCase { - - - private final static Logger mLog = Logger.getLogger(P2pProxyTester.class); - - static private SipProvider mProvider; - static final String mDefaultSipIdentity = "sip:p2pTester@linphone.org"; - static private SipClient mSipClient; - static private P2pProxyInstance mP2pProxyInstance; - final private String mCallerUri = "sip:caller@linphone.org"; - final private String mCalleeUri = "sip:callee@linphone.org"; - final private int RDV_DISCOVERY_TIMEOUT = 5000; - static private P2pProxyAccountManagementMBean mP2pProxyAccountManagement; - - public P2pProxyTester() { - - } - protected void setUp() throws Exception { - - if (mP2pProxyInstance == null) { - // setup logging - System.setProperty("org.linphone.p2pproxy.home", "."); - P2pProxyMain.staticLoadTraceConfigFile(); - //PropertyConfigurator.configure("log4j.properties"); - setupJxta(); - mProvider = mP2pProxyInstance.getSipClientProvider() ; - mSipClient = new SipClient(mProvider, mDefaultSipIdentity,RDV_DISCOVERY_TIMEOUT*2); - // create account for user mDefaultSipIdentity, mCallerUri, mCalleeUri if not exist - mP2pProxyAccountManagement = new P2pProxyAccountManagement((JxtaNetworkManager)mP2pProxyInstance.getOpaqueNetworkManager()); - - try { - mP2pProxyAccountManagement.createAccount(mDefaultSipIdentity); - } catch (Exception e) { - mLog.warn(e); - } - try { - mP2pProxyAccountManagement.createAccount(mCallerUri); - } catch (Exception e) { - mLog.warn(e); - } - - try { - mP2pProxyAccountManagement.createAccount(mCalleeUri); - } catch (Exception e) { - mLog.warn(e); - } - } - - } - - protected void tearDown() throws Exception { - } - - public void testStunClient() { - try { -// if (mP2pProxyInstance2 == null) { -// try { -// setupJxta2(); -// } catch (Exception e) { -// mLog.error("cannot start peer2"); -// } -// } - DatagramSocket lDatagramSocket = new DatagramSocket(); - StunClient lStunClient = new StunClient((JxtaNetworkManager)mP2pProxyInstance.getOpaqueNetworkManager()); - AddressInfo lAddressInfo = lStunClient.computeAddressInfo(lDatagramSocket); - mLog.info("AddressInfo ["+lAddressInfo+"]"); - }catch (Exception e) { - mLog.error("testStunClient ko",e); - Assert.fail(e.getMessage()); - } - - } - public void testGetRegistrarAdress() { - try { - NetworkResourceAdvertisement lSipProxyRegistrarAdvertisement = (NetworkResourceAdvertisement) (((JxtaNetworkManager)mP2pProxyInstance.getOpaqueNetworkManager()).getAdvertisement(null,SipProxyRegistrar.ADV_NAME, true)); - mLog.info("testGetRegistrarAdress ok ["+lSipProxyRegistrarAdvertisement.getAddress()+"]"); - } catch (Exception e) { - mLog.error("testGetRegistrarAdress ko",e); - Assert.fail(e.getMessage()); - } - - } - public void testSipRegisterUnregister() { - try { - //register - mSipClient.register(); - //unregister - mSipClient.unRegister(); - mLog.info("testSipRegisterUnregister ok"); - } catch (Exception e) { - mLog.error("testSipRegisterUnregister ko",e); - Assert.fail(e.getMessage()); - } - - } - public void testRegisterUnknownUser() { - try { - //register - Assert.assertFalse(mSipClient.register(900,"sip:toto@linphone.org",404)); - mLog.info("testRegisterUnknownUser ok"); - } catch (Exception e) { - mLog.error("testRegisterUnknownUser ko",e); - Assert.fail(e.getMessage()); - } - - } -// public void testPipeDiscovery() { -// try { -// long lDiscoveryTimout = 10000; -// //register -// mSipClient.register(900,mDefaultSipIdentity); -// DiscoveryService lDiscoveryService = ((JxtaNetworkManager)mP2pProxyInstance.getOpaqueNetworkManager()).getPeerGroup().getDiscoveryService(); -// final Semaphore lSemaphore = new Semaphore(0); -// DiscoveryListener lDiscoveryListener = new DiscoveryListener() { -// -// public void discoveryEvent(DiscoveryEvent event) { -// DiscoveryResponseMsg LRes = event.getResponse(); -// Enumeration lAdvertisementLists = LRes.getAdvertisements(); -// Advertisement lAdvertisement = (Advertisement) lAdvertisementLists.nextElement(); -// //Assert.assertEquals("not the good adv name", lContact, lAdvertisement.) -// mLog.info(lAdvertisement.toString()); -// lSemaphore.release(); -// } -// -// }; -// lDiscoveryService.getRemoteAdvertisements(null, DiscoveryService.ADV, "Name",mDefaultSipIdentity, 1,lDiscoveryListener); -// Assert.assertTrue("pipe not found until ["+lDiscoveryTimout+"]", lSemaphore.tryAcquire(lDiscoveryTimout,TimeUnit.MILLISECONDS)); -// lSemaphore.release(); -// -// //unregister -// mSipClient.register(0,mDefaultSipIdentity); -// mLog.info("testPipeDiscovery ok"); -// } catch (Exception e) { -// mLog.error("testPipeDiscovery ko",e); -// Assert.fail(e.getMessage()); -// } -// -// } - public void testCall() { - try { - Call(false); - } catch (Exception e) { - mLog.error("testCall ko",e); - Assert.fail(e.getMessage()); - } - - } - public void testCallWithSdp() { - try { - Call(true); - } catch (Exception e) { - mLog.error("testCallWithSdp ko",e); - Assert.fail(e.getMessage()); - } - - } - - private void Call(boolean useSdp) throws Exception { - //register - mSipClient.register(900,mCallerUri); - mSipClient.register(900,mCalleeUri); - call(mCallerUri,mCalleeUri,useSdp); - // unregister - mSipClient.register(0,mCallerUri); - mSipClient.register(0,mCalleeUri); - - mLog.info("testCall ok"); - - } - public void testUserNotFound() { - try { - long lTimout = (long) (RDV_DISCOVERY_TIMEOUT * 2); - //register - mSipClient.register(900,mCallerUri); - final Semaphore lCallerSemaphoreRefused = new Semaphore(0); - CallListener lCallerListener = new DefaultCallListener() { - public void onCallRefused(Call call, String reason, Message resp) { - lCallerSemaphoreRefused.release(); - Assert.assertEquals("bad reason, must be user not found", 404, resp.getStatusLine().getCode()); - } - }; - Call lCaller = new Call(mProvider, mCallerUri, mSipClient.getContact(mProvider), lCallerListener); - lCaller.call(mCalleeUri); - Assert.assertTrue("caller call not refused until ["+lTimout+"]", lCallerSemaphoreRefused.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - // unregister - mSipClient.register(0,mCallerUri); - - mLog.info("testUserNotFound ok"); - } catch (Exception e) { - mLog.error("testUserNotFound ko",e); - Assert.fail(e.getMessage()); - } - } - public void testUserUnregisterred() { - try { - long lTimout = RDV_DISCOVERY_TIMEOUT * 2; - //register - mSipClient.register(900,mCallerUri); - mSipClient.register(900,mCalleeUri); - //unregister callee - mSipClient.register(0,mCalleeUri); - final Semaphore lCallerSemaphoreRefused = new Semaphore(0); - CallListener lCallerListener = new DefaultCallListener() { - public void onCallRefused(Call call, String reason, Message resp) { - lCallerSemaphoreRefused.release(); - Assert.assertEquals("bad reason, must be user not found", 404, resp.getStatusLine().getCode()); - } - }; - Call lCaller = new Call(mProvider, mCallerUri, mSipClient.getContact(mProvider), lCallerListener); - lCaller.call(mCalleeUri); - Assert.assertTrue("caller call not refused until ["+lTimout+"]", lCallerSemaphoreRefused.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - // unregister caller - mSipClient.register(0,mCallerUri); - - mLog.info("testUserNotFound ok"); - } catch (Exception e) { - mLog.error("testUserNotFound ko",e); - Assert.fail(e.getMessage()); - } - } - public void xxxCallCancelledBeforeDialogEstablishement() { - try { - //Assert.fail("not debugged yet"); - long lTimout = RDV_DISCOVERY_TIMEOUT * 2; - //register - mSipClient.register(900,mCallerUri); - //mSipClient.register(900,mCalleeUri); - final Semaphore lCallerSemaphoreCancel = new Semaphore(0); - CallListener lCallerListener = new DefaultCallListener() { - public void onCallRefused(Call call, String reason, Message resp) { - Assert.assertEquals("bad reason, must be Request Terminated", 487, resp.getStatusLine().getCode()); - lCallerSemaphoreCancel.release(); - } - - }; - Call lCaller = new Call(mProvider, mCallerUri, mSipClient.getContact(mProvider), lCallerListener); - lCaller.call(mCalleeUri); - Thread.sleep(1000); - lCaller.cancel(); - Assert.assertTrue("caller call not canceled until ["+lTimout+"]", lCallerSemaphoreCancel.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - // unregister - mSipClient.register(0,mCallerUri); - - mLog.info("testCallCancelledBeforeDialogEstablishement ok"); - } catch (Exception e) { - mLog.error("testCallCancelledBeforeDialogEstablishement ko",e); - Assert.fail(e.getMessage()); - } - } - - public void testCallCancelledAfterRinging() { - try { - long lTimout = RDV_DISCOVERY_TIMEOUT * 2; - //register - mSipClient.register(900,mCallerUri); - mSipClient.register(900,mCalleeUri); - final Semaphore lCalleeSemaphoreCanceling = new Semaphore(0); - final Semaphore lCallerSemaphoreRinging = new Semaphore(0); - final Semaphore lCallerSemaphoreCanceled = new Semaphore(0); - CallListener lCallerListener = new DefaultCallListener() { - - public void onCallRinging(Call call, Message resp) { - lCallerSemaphoreRinging.release(); - } - public void onCallRefused(Call call, String reason, Message resp) { - Assert.assertEquals("bad reason, must be Request Terminated", 487, resp.getStatusLine().getCode()); - lCallerSemaphoreCanceled.release(); - } - - }; - Call lCaller = new Call(mProvider, mCallerUri, mSipClient.getContact(mProvider), lCallerListener); - final Semaphore lCalleeSemaphoreIncoming = new Semaphore(0); - CallListener lCalleeListener = new DefaultCallListener() { - public void onCallIncoming(Call call, NameAddress callee, NameAddress caller, String sdp, Message invite) { - lCalleeSemaphoreIncoming.release(); - call.ring(); - } - public void onCallCanceling(Call call, Message cancel) { - lCalleeSemaphoreCanceling.release(); - } - - }; - Call lCallee = new Call(mProvider, mCalleeUri, mSipClient.getContact(mProvider), lCalleeListener); - lCallee.listen(); - lCaller.call(mCalleeUri); - - Assert.assertTrue("callee not alerted until ["+lTimout+"]", lCalleeSemaphoreIncoming.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - Assert.assertTrue("callee call not ringing until ["+lTimout+"]", lCallerSemaphoreRinging.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - lCaller.cancel(); - Assert.assertTrue("caller call not canceling until ["+lTimout+"]", lCalleeSemaphoreCanceling.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - Assert.assertTrue("caller call not refused until ["+lTimout+"]", lCallerSemaphoreCanceled.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - - // unregister - mSipClient.register(0,mCallerUri); - mSipClient.register(0,mCalleeUri); - - mLog.info("testCallCancelledAfterRinging ok"); - } catch (Exception e) { - mLog.error("testCallCancelledAfterRinging ko",e); - Assert.fail(e.getMessage()); - } - - } - public void testAlreadyRegister() { - Assert.fail("not implemented yet"); - } - public void testReRegisterAfterExpired() { - try { - //register - mSipClient.register(10,mCallerUri); - mSipClient.register(10,mCalleeUri); - call(mCallerUri,mCalleeUri); - // wait - Thread.sleep(10000); - mSipClient.register(20,mCallerUri); - mSipClient.register(20,mCalleeUri); - - call(mCallerUri,mCalleeUri); - - // unregister - mSipClient.register(0,mCallerUri); - mSipClient.register(0,mCalleeUri); - - mLog.info("testReRegisterAfterExpired ok"); - } catch (Exception e) { - mLog.error("testtestReRegisterAfterExpired ko",e); - Assert.fail(e.getMessage()); - } - - - } - public void testReRegisterBeforeExpired() { - try { - //register - mSipClient.register(900,mCallerUri); - mSipClient.register(900,mCalleeUri); - - call(mCallerUri,mCalleeUri); - //re-register - mSipClient.register(900,mCallerUri); - mSipClient.register(900,mCalleeUri); - - call(mCallerUri,mCalleeUri); - - // unregister - mSipClient.register(0,mCallerUri); - mSipClient.register(0,mCalleeUri); - - mLog.info("testReRegisterBeforeExpired ok"); - } catch (Exception e) { - mLog.error("testReRegisterBeforeExpired ko",e); - Assert.fail(e.getMessage()); - } - - - } - - private void setupJxta() throws Exception { - mP2pProxyInstance = new P2pProxyInstanceImpl(); - mP2pProxyInstance.setMode(Mode.seeding_server); - mP2pProxyInstance.setIndex(1); - mP2pProxyInstance.setProperty(JxtaNetworkManager.ADV_DISCOVERY_TIMEOUT, String.valueOf(RDV_DISCOVERY_TIMEOUT)); - mP2pProxyInstance.start(); - while (mP2pProxyInstance.isStarted() == false) Thread.sleep(500); - } - - private void call(String aCaller,String aCallee) throws Exception { - call(aCaller,aCallee,false); - } - - private void call(String aCaller,String aCallee,boolean useSdp) throws Exception { - long lTimout = 1000; - final Semaphore lCallerSemaphoreAccepted = new Semaphore(0); - final Semaphore lCalleeSemaphoreClosed = new Semaphore(0); - final Semaphore lCallerSemaphoreRinging = new Semaphore(0); - CallListener lCallerListener = new DefaultCallListener() { - public void onCallAccepted(Call call, String sdp, Message resp) { - lCallerSemaphoreAccepted.release(); - call.ackWithAnswer(sdp); - } - public void onCallClosing(Call call, Message bye) { - //nop - } - public void onCallRinging(Call call, Message resp) { - lCallerSemaphoreRinging.release(); - } - }; - Call lCaller = new Call(mProvider, aCaller, mSipClient.getContact(mProvider), lCallerListener); - if (useSdp) { - lCaller.setLocalSessionDescriptor(SipClient.sdp_offer); - } - final Semaphore lCalleeSemaphoreConfirmed = new Semaphore(0); - final Semaphore lCalleeSemaphoreIncoming = new Semaphore(0); - CallListener lCalleeListener = new DefaultCallListener() { - public void onCallConfirmed(Call call, String sdp, Message ack) { - lCalleeSemaphoreConfirmed.release(); - call.bye(); - } - public void onCallIncoming(Call call, NameAddress callee, NameAddress caller, String sdp, Message invite) { - lCalleeSemaphoreIncoming.release(); - call.accept(sdp); - } - public void onCallClosed(Call call, Message resp) { - lCalleeSemaphoreClosed.release(); - } - }; - Call lCallee = new Call(mProvider, aCallee, mSipClient.getContact(mProvider), lCalleeListener); - if (useSdp) { - lCallee.setLocalSessionDescriptor(SipClient.sdp_offer); - } - lCallee.listen(); - lCaller.call(aCallee); - - Assert.assertTrue("callee not alerted until ["+lTimout+"]", lCalleeSemaphoreIncoming.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - Assert.assertTrue("caller call not accepted until ["+lTimout+"]", lCallerSemaphoreAccepted.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - Assert.assertTrue("callee call not confirmed until ["+lTimout+"]", lCalleeSemaphoreConfirmed.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - Assert.assertTrue("caller call not closed until ["+lTimout+"]", lCalleeSemaphoreClosed.tryAcquire(lTimout,TimeUnit.MILLISECONDS)); - - } - public void testBunchOfCall() { - for (int i=0;i<20;i++) { - //testCallCancelledBeforeDialogEstablishement(); - testCall(); - testCallCancelledAfterRinging(); - } - } - -} diff --git a/p2pproxy/test-src/org/linphone/p2pproxy/test/RtpRelayServerTester.java b/p2pproxy/test-src/org/linphone/p2pproxy/test/RtpRelayServerTester.java deleted file mode 100644 index e2347347..00000000 --- a/p2pproxy/test-src/org/linphone/p2pproxy/test/RtpRelayServerTester.java +++ /dev/null @@ -1,202 +0,0 @@ -package org.linphone.p2pproxy.test; - - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; - -import junit.framework.Assert; -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.linphone.p2pproxy.core.GenericUdpSession; -import org.linphone.p2pproxy.core.media.rtprelay.RtpRelayServer; -import org.linphone.p2pproxy.core.stun.StunServer; - -public class RtpRelayServerTester extends TestCase{ - private final static Logger mLog = Logger.getLogger(RtpRelayServerTester.class); - static private RtpRelayServer mRtpRelayServer; - static private int RTP_SERVER_PORT = 16000; - private static GenericUdpSession mGenericUdpSession; - static StunServer mSturServer = null; - private final int SO_TIMEOUT=100; - private final InetSocketAddress mServerSocket; - - public RtpRelayServerTester() throws UnknownHostException { - mServerSocket = new InetSocketAddress(InetAddress.getByName("localhost"), RTP_SERVER_PORT); - } - - public RtpRelayServerTester(InetSocketAddress aServerAddress) { - mServerSocket = aServerAddress; - } - @Before - public void setUp() throws Exception { - if (mRtpRelayServer == null) { - BasicConfigurator.configure(); - mGenericUdpSession = new GenericUdpSession(new InetSocketAddress(RTP_SERVER_PORT)); - mRtpRelayServer = new RtpRelayServer(mGenericUdpSession.getSocket(),1000,1000); - mGenericUdpSession.addMessageHandler(mRtpRelayServer); - mSturServer = new StunServer(mGenericUdpSession.getSocket()); - mGenericUdpSession.addMessageHandler(mSturServer); - } - } - - @After - public void tearDown() throws Exception { - //mRtpRelayServer.close(); - } - public void testRouting() { - _testRouting(1); - } - private void _testRouting(int aSessionId) { - byte lSsrcA = (byte) aSessionId; - byte lSsrcB = (byte) ~aSessionId; - byte[] lRtcpA = {0x55,(byte) 204,0x0,16 - ,0x0,0x01,0x02,lSsrcA //ssrc - ,'R','S','I','D' - ,'S','E','S','S',(byte) aSessionId}; - - byte[] lRtpA = {0x55,(byte) 34,0x0,16 - ,0x55,0x55,0x55,0x55 - ,0x0,0x01,0x02,lSsrcA //ssrc - ,0x55,0x55,0x55,0x55 - ,0x55,0x55,0x55,0x55}; - - - byte[] lRtcpB = {0x55,(byte) 204,0x0,16 - ,0x04,0x05,0x06,lSsrcB - ,'R','S','I','D' - ,'S','E','S','S',(byte) aSessionId}; - - byte[] lRtpB = {0x55,(byte) 34,0x0,16 - ,0x55,0x55,0x55,0x55 - ,0x04,0x05,0x06,lSsrcB //ssrc - ,0x55,0x55,0x55,0x55 - ,0x55,0x55,0x55,0x55}; - - - try { - //1 send rtcp app A - DatagramSocket lRtcpSocketA = new DatagramSocket(); - DatagramPacket lRtcpaPacket = new DatagramPacket(lRtcpA,lRtcpA.length,mServerSocket); - lRtcpSocketA.setSoTimeout(SO_TIMEOUT); - lRtcpSocketA.send(lRtcpaPacket); - - //2 send rtcp app B - DatagramSocket lRtcpSocketB = new DatagramSocket(); - DatagramPacket lRtcpbPacket = new DatagramPacket(lRtcpB,lRtcpB.length,mServerSocket); - lRtcpSocketB.setSoTimeout(SO_TIMEOUT); - lRtcpSocketB.send(lRtcpbPacket); - - - //3 send rtp A - DatagramSocket lRtpSocketA = new DatagramSocket(); - DatagramPacket lRtpaPacket = new DatagramPacket(lRtpA,lRtpA.length,mServerSocket); - lRtpSocketA.setSoTimeout(SO_TIMEOUT); - lRtpSocketA.send(lRtpaPacket); - - //4 send rtp B - DatagramSocket lRtpSocketB = new DatagramSocket(); - DatagramPacket lRtpblPacket = new DatagramPacket(lRtpB,lRtpB.length,mServerSocket); - lRtpSocketB.send(lRtpblPacket); - lRtpSocketB.setSoTimeout(SO_TIMEOUT); - - - - // check RTP B -> A - DatagramPacket lReceivedRtpaPacket = new DatagramPacket(new byte[1500],1500); - - - try { - lRtpSocketA.receive(lReceivedRtpaPacket); - // check ssrc - Assert.assertEquals("Unexpected packet received ",lSsrcB,(byte)RtpRelayServer.b2UB(lReceivedRtpaPacket.getData()[11])); - } catch (SocketTimeoutException e) { - Assert.fail("packet not relayed cause [" + e.getMessage()+"]"); - } - - //check RTP A->B - DatagramPacket lReceivedRtpbPacket = new DatagramPacket(new byte[1500],1500); - lRtpSocketA.setSoTimeout(SO_TIMEOUT); - lRtpSocketA.send(lRtpaPacket); - try { - lRtpSocketB.receive(lReceivedRtpbPacket); - // check ssrc - Assert.assertEquals("Unexpected packet received ",lSsrcA,(byte)RtpRelayServer.b2UB(lReceivedRtpbPacket.getData()[11])); - } catch (SocketTimeoutException e) { - Assert.fail("packet not relayed cause [" + e.getMessage()+"]"); - } - - // check RTCP A->B - byte[] lRtcpASR = {0x55,(byte) 200,0x0,16 - ,0x0,0x01,0x02,lSsrcA //ssrc - ,'B','L','A','B','L','A'}; - - DatagramPacket lRtcpASRPacket = new DatagramPacket(lRtcpASR,lRtcpASR.length,mServerSocket); - lRtcpSocketA.send(lRtcpASRPacket); - try { - lRtcpSocketB.receive(lReceivedRtpbPacket); - // check ssrc - Assert.assertEquals("Unexpected packet received ",lSsrcA,(byte)RtpRelayServer.b2UB(lReceivedRtpbPacket.getData()[7])); - } catch (SocketTimeoutException e) { - Assert.fail("packet not relayed cause [" + e.getMessage()+"]"); - } - - // check RTCP B->A - byte[] lRtcpBSR = {0x55,(byte) 200,0x0,16 - ,0x04,0x05,0x06,lSsrcB //ssrc - ,'B','L','A','B','L','A'}; - - DatagramPacket lRtcpBSRPacket = new DatagramPacket(lRtcpBSR,lRtcpBSR.length,mServerSocket); - lRtcpSocketB.send(lRtcpBSRPacket); - try { - lRtcpSocketA.receive(lReceivedRtpbPacket); - // check ssrc - Assert.assertEquals("Unexpected packet received ",lSsrcB,(byte)RtpRelayServer.b2UB(lReceivedRtpbPacket.getData()[7])); - } catch (SocketTimeoutException e) { - Assert.fail("packet not relayed cause [" + e.getMessage()+"]"); - } - - // check unknown RTCP B->A - byte[] lRtcpSR = {0x55,(byte) 200,0x0,16 - ,0x55,0x55,0x56,0x55 //ssrc - ,'B','L','A','B','L','A'}; - - DatagramPacket lRtcpSRPacket = new DatagramPacket(lRtcpSR,lRtcpSR.length,mServerSocket); - lRtcpSocketB.send(lRtcpSRPacket); - try { - lRtcpSocketA.receive(lReceivedRtpbPacket); - // check ssrc - Assert.fail("Unexpected packet received "); - } catch (SocketTimeoutException e) { - //ok - } - - - } catch (Exception e) { - Assert.fail(e.getMessage()); - } - - } - public void testGC() { - try { - //1 launch traffic - int lOldValue = mRtpRelayServer.getRoutingtableSize(); - _testRouting(2); - Assert.assertEquals("unexpected routing table size", lOldValue+1,mRtpRelayServer.getRoutingtableSize()); - //2 wait 1,5s - Thread.sleep(1500); - Assert.assertTrue("unexpected routing table size ["+mRtpRelayServer.getRoutingtableSize()+"] should be less than or equal to ["+lOldValue+"]", mRtpRelayServer.getRoutingtableSize()<=lOldValue); - } catch (Exception e) { - Assert.fail(e.getMessage()); - } - - } - -} diff --git a/p2pproxy/test-src/org/linphone/p2pproxy/test/StunServerTester.java b/p2pproxy/test-src/org/linphone/p2pproxy/test/StunServerTester.java deleted file mode 100644 index 32c5c447..00000000 --- a/p2pproxy/test-src/org/linphone/p2pproxy/test/StunServerTester.java +++ /dev/null @@ -1,425 +0,0 @@ -/* - * This file is part of JSTUN. - * - * Copyright (c) 2005 Thomas King - All rights - * reserved. - * - * This software is licensed under either the GNU Public License (GPL), - * or the Apache 2.0 license. Copies of both license agreements are - * included in this distribution. - */ - -package org.linphone.p2pproxy.test; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; - -import junit.framework.Assert; -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.core.GenericUdpSession; -import org.linphone.p2pproxy.core.stun.StunServer; - - - -import de.javawi.jstun.attribute.ChangeRequest; -import de.javawi.jstun.attribute.ChangedAddress; -import de.javawi.jstun.attribute.ErrorCode; -import de.javawi.jstun.attribute.MappedAddress; -import de.javawi.jstun.attribute.MessageAttribute; -import de.javawi.jstun.attribute.MessageAttributeException; -import de.javawi.jstun.attribute.MessageAttributeParsingException; -import de.javawi.jstun.header.MessageHeader; -import de.javawi.jstun.header.MessageHeaderParsingException; -import de.javawi.jstun.test.DiscoveryInfo; -import de.javawi.jstun.util.UtilityException; - -public class StunServerTester extends TestCase { - private static Logger logger = Logger.getLogger(StunServerTester.class); - InetAddress iaddress ; - String stunServer = "localhost"; - int port = 16000; - int timeoutInitValue = 300; //ms - MappedAddress ma = null; - ChangedAddress ca = null; - boolean nodeNatted = true; - DatagramSocket socketTest1 = null; - DiscoveryInfo di = null; - static StunServer mSturServer = null; - static GenericUdpSession mGenericUdpSession = null; - - - public void setUp() throws Exception { - - if (mSturServer == null) { - BasicConfigurator.configure(); - mGenericUdpSession = new GenericUdpSession(new InetSocketAddress(port)); - mSturServer = new StunServer(mGenericUdpSession.getSocket()); - mGenericUdpSession.addMessageHandler(mSturServer); - iaddress = InetAddress.getLocalHost(); - } - di = new DiscoveryInfo(iaddress); - } - - public DiscoveryInfo xxxtest() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException{ - ma = null; - ca = null; - nodeNatted = true; - socketTest1 = null; - di = new DiscoveryInfo(iaddress); - -// if (test1()) { -// if (test2()) { -// if (test1Redo()) { -// test3(); -// } -// } -// } - - socketTest1.close(); - - return di; - } - - public void testBindRequest() { - try { - bindRequest(); - } catch (Exception e) { - logger.error("testBindRequest ko",e); - Assert.fail(e.getMessage()); - } - - } - private boolean bindRequest() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageHeaderParsingException { - int timeSinceFirstTransmission = 0; - int timeout = timeoutInitValue; - while (true) { - try { - // Test 1 including response - socketTest1 = new DatagramSocket(new InetSocketAddress(iaddress, 0)); - socketTest1.setReuseAddress(true); - socketTest1.connect(mGenericUdpSession.getSocket().getLocalSocketAddress()); - socketTest1.setSoTimeout(timeout); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - - ChangeRequest changeRequest = new ChangeRequest(); - sendMH.addMessageAttribute(changeRequest); - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - socketTest1.send(send); - logger.info("Test 1: Binding Request sent."); - - MessageHeader receiveMH = new MessageHeader(); - while (!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - socketTest1.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - - ma = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress); - ca = (ChangedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ChangedAddress); - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - di.setError(ec.getResponseCode(), ec.getReason()); - logger.info("Message header contains an Errorcode message attribute."); - return false; - } - if ((ma == null)) { - di.setError(700, "The server is sending an incomplete response (Mapped Address and Changed Address message attributes are missing). The client should not retry."); - logger.info("Response does not contain a Mapped Address or Changed Address message attribute."); - return false; - } else { - di.setPublicIP(ma.getAddress().getInetAddress()); - if ((ma.getPort() == socketTest1.getLocalPort()) && (ma.getAddress().getInetAddress().equals(socketTest1.getLocalAddress()))) { - logger.info("Node is not natted."); - nodeNatted = false; - } else { - logger.info("Node is natted."); - } - return true; - } - } catch (SocketTimeoutException ste) { - if (timeSinceFirstTransmission < 7900) { - logger.info("Test 1: Socket timeout while receiving the response."); - timeSinceFirstTransmission += timeout; - int timeoutAddValue = (timeSinceFirstTransmission * 2); - if (timeoutAddValue > 1600) timeoutAddValue = 1600; - timeout = timeoutAddValue; - } else { - // node is not capable of udp communication - logger.info("Test 1: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); - di.setBlockedUDP(); - logger.info("Node is not capable of UDP communication."); - return false; - } - } - } - } - /** - * Test allocate request - * ALLOCATEREQUEST - * - */ - public void xxxAllocateRequest() { - - int timeSinceFirstTransmission = 0; - int timeout = timeoutInitValue; - try { - // Test 1 including response - socketTest1 = new DatagramSocket(new InetSocketAddress(iaddress, 0)); - socketTest1.setReuseAddress(true); - socketTest1.connect(InetAddress.getByName(stunServer), port); - socketTest1.setSoTimeout(timeout); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.AllocateRequest); - sendMH.generateTransactionID(); - - ChangeRequest changeRequest = new ChangeRequest(); - sendMH.addMessageAttribute(changeRequest); - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - socketTest1.send(send); - logger.info("Allocate Request sent."); - - MessageHeader receiveMH = new MessageHeader(); - while (!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - socketTest1.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - - } catch (Exception ste) { - if (timeSinceFirstTransmission < 7900) { - logger.info("Allocate Rquest: Socket timeout while receiving the response."); - timeSinceFirstTransmission += timeout; - int timeoutAddValue = (timeSinceFirstTransmission * 2); - if (timeoutAddValue > 1600) timeoutAddValue = 1600; - timeout = timeoutAddValue; - } else { - // node is not capable of udp communication - logger.info("Allocate Rquest: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); - di.setBlockedUDP(); - logger.info("Node is not capable of UDP communication."); - } - } - } - - - private boolean xxxtest2() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException { - int timeSinceFirstTransmission = 0; - int timeout = timeoutInitValue; - while (true) { - try { - // Test 2 including response - DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0)); - sendSocket.connect(InetAddress.getByName(stunServer), port); - sendSocket.setSoTimeout(timeout); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - - ChangeRequest changeRequest = new ChangeRequest(); - changeRequest.setChangeIP(); - changeRequest.setChangePort(); - sendMH.addMessageAttribute(changeRequest); - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - sendSocket.send(send); - logger.info("Test 2: Binding Request sent."); - - int localPort = sendSocket.getLocalPort(); - InetAddress localAddress = sendSocket.getLocalAddress(); - - sendSocket.close(); - - DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress); - receiveSocket.connect(ca.getAddress().getInetAddress(), ca.getPort()); - receiveSocket.setSoTimeout(timeout); - - MessageHeader receiveMH = new MessageHeader(); - while(!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - receiveSocket.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - di.setError(ec.getResponseCode(), ec.getReason()); - logger.info("Message header contains an Errorcode message attribute."); - return false; - } - if (!nodeNatted) { - di.setOpenAccess(); - logger.info("Node has open access to the Internet (or, at least the node is behind a full-cone NAT without translation)."); - } else { - di.setFullCone(); - logger.info("Node is behind a full-cone NAT."); - } - return false; - } catch (SocketTimeoutException ste) { - if (timeSinceFirstTransmission < 7900) { - logger.info("Test 2: Socket timeout while receiving the response."); - timeSinceFirstTransmission += timeout; - int timeoutAddValue = (timeSinceFirstTransmission * 2); - if (timeoutAddValue > 1600) timeoutAddValue = 1600; - timeout = timeoutAddValue; - } else { - logger.info("Test 2: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); - if (!nodeNatted) { - di.setSymmetricUDPFirewall(); - logger.info("Node is behind a symmetric UDP firewall."); - return false; - } else { - // not is natted - // redo test 1 with address and port as offered in the changed-address message attribute - return true; - } - } - } - } - } - - private boolean xxxtest1Redo() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageHeaderParsingException{ - int timeSinceFirstTransmission = 0; - int timeout = timeoutInitValue; - while (true) { - // redo test 1 with address and port as offered in the changed-address message attribute - try { - // Test 1 with changed port and address values - socketTest1.connect(ca.getAddress().getInetAddress(), ca.getPort()); - socketTest1.setSoTimeout(timeout); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - - ChangeRequest changeRequest = new ChangeRequest(); - sendMH.addMessageAttribute(changeRequest); - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - socketTest1.send(send); - logger.info("Test 1 redo with changed address: Binding Request sent."); - - MessageHeader receiveMH = new MessageHeader(); - while (!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - socketTest1.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - MappedAddress ma2 = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress); - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - di.setError(ec.getResponseCode(), ec.getReason()); - logger.info("Message header contains an Errorcode message attribute."); - return false; - } - if (ma2 == null) { - di.setError(700, "The server is sending an incomplete response (Mapped Address message attribute is missing). The client should not retry."); - logger.info("Response does not contain a Mapped Address message attribute."); - return false; - } else { - if ((ma.getPort() != ma2.getPort()) || (!(ma.getAddress().getInetAddress().equals(ma2.getAddress().getInetAddress())))) { - di.setSymmetric(); - logger.info("Node is behind a symmetric NAT."); - return false; - } - } - return true; - } catch (SocketTimeoutException ste2) { - if (timeSinceFirstTransmission < 7900) { - logger.info("Test 1 redo with changed address: Socket timeout while receiving the response."); - timeSinceFirstTransmission += timeout; - int timeoutAddValue = (timeSinceFirstTransmission * 2); - if (timeoutAddValue > 1600) timeoutAddValue = 1600; - timeout = timeoutAddValue; - } else { - logger.info("Test 1 redo with changed address: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); - return false; - } - } - } - } - - private void xxxtest3() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException { - int timeSinceFirstTransmission = 0; - int timeout = timeoutInitValue; - while (true) { - try { - // Test 3 including response - DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0)); - sendSocket.connect(InetAddress.getByName(stunServer), port); - sendSocket.setSoTimeout(timeout); - - MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest); - sendMH.generateTransactionID(); - - ChangeRequest changeRequest = new ChangeRequest(); - changeRequest.setChangePort(); - sendMH.addMessageAttribute(changeRequest); - - byte[] data = sendMH.getBytes(); - DatagramPacket send = new DatagramPacket(data, data.length); - sendSocket.send(send); - logger.info("Test 3: Binding Request sent."); - - int localPort = sendSocket.getLocalPort(); - InetAddress localAddress = sendSocket.getLocalAddress(); - - sendSocket.close(); - - DatagramSocket receiveSocket = new DatagramSocket(localPort, localAddress); - receiveSocket.connect(InetAddress.getByName(stunServer), ca.getPort()); - receiveSocket.setSoTimeout(timeout); - - MessageHeader receiveMH = new MessageHeader(); - while (!(receiveMH.equalTransactionID(sendMH))) { - DatagramPacket receive = new DatagramPacket(new byte[200], 200); - receiveSocket.receive(receive); - receiveMH = MessageHeader.parseHeader(receive.getData()); - receiveMH.parseAttributes(receive.getData()); - } - ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode); - if (ec != null) { - di.setError(ec.getResponseCode(), ec.getReason()); - logger.info("Message header contains an Errorcode message attribute."); - return; - } - if (nodeNatted) { - di.setRestrictedCone(); - logger.info("Node is behind a restricted NAT."); - return; - } - } catch (SocketTimeoutException ste) { - if (timeSinceFirstTransmission < 7900) { - logger.info("Test 3: Socket timeout while receiving the response."); - timeSinceFirstTransmission += timeout; - int timeoutAddValue = (timeSinceFirstTransmission * 2); - if (timeoutAddValue > 1600) timeoutAddValue = 1600; - timeout = timeoutAddValue; - } else { - logger.info("Test 3: Socket timeout while receiving the response. Maximum retry limit exceed. Give up."); - di.setPortRestrictedCone(); - logger.info("Node is behind a port restricted NAT."); - return; - } - } - } - } -} diff --git a/p2pproxy/test-src/org/linphone/p2pproxy/test/UdpRelayTester.java b/p2pproxy/test-src/org/linphone/p2pproxy/test/UdpRelayTester.java deleted file mode 100644 index add0cde6..00000000 --- a/p2pproxy/test-src/org/linphone/p2pproxy/test/UdpRelayTester.java +++ /dev/null @@ -1,125 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -P2pAutoConfigTester.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.test; - - -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -import junit.framework.Assert; -import junit.framework.TestCase; -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.linphone.p2pproxy.api.P2pProxyInstance; -import org.linphone.p2pproxy.api.P2pProxyNetworkProbe; -import org.linphone.p2pproxy.api.P2pProxyInstance.Mode; -import org.linphone.p2pproxy.core.JxtaNetworkManager; -import org.linphone.p2pproxy.core.P2pProxyAccountManagement; -import org.linphone.p2pproxy.core.P2pProxyInstanceImpl; -import org.linphone.p2pproxy.core.P2pProxyMain; -import org.linphone.p2pproxy.test.utils.SipClient; - -public class UdpRelayTester extends TestCase { - static private P2pProxyInstance mP2pProxyInstance; - private static P2pProxyAccountManagement mP2pProxyAccountManagement; - static final String mDefaultSipIdentity = "sip:p2pTester@p2p.linphone.org"; - static final private String mCallerUri = "sip:caller@p2p.linphone.org"; - static final private String mCalleeUri = "sip:callee@p2p.linphone.org"; - - private final static Logger mLog = Logger.getLogger(UdpRelayTester.class); - - //@BeforeClass - public static void setUpBeforeClass() throws Exception { - // setup logging - //PropertyConfigurator.configure("log4j.properties"); - -// // 1 setup relays -// String lRunString = "java -cp eclipsebuild:dependencies/*.jar "; -// //lRunString +=" -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"; -// lRunString +=" org.linphone.p2pproxy.core.P2pProxyMain"; -// lRunString +=" -jxta " +System.getProperty("user.home")+"/P2pAutoConfigTester-seeding"; -// lRunString +=" -sip 5040 -seeding-server "; -// lRunString +=" -seeding-relay http://"+InetAddress.getLocalHost().getHostAddress()+":"+P2pProxyInstance.BASE_HTTP; -// lRunString +=" -seeding-rdv http://"+InetAddress.getLocalHost().getHostAddress()+":"+P2pProxyInstance.BASE_HTTP; -// mLog.info("starting ["+lRunString+"]"); -// Process lProcess = Runtime.getRuntime().exec(lRunString); - - System.setProperty("org.linphone.p2pproxy.home", "."); - P2pProxyMain.staticLoadTraceConfigFile(); - // setup edge - mP2pProxyInstance = new P2pProxyInstanceImpl(); - mP2pProxyInstance.setMode(Mode.edge); - mP2pProxyInstance.setIndex(1); - mP2pProxyInstance.start(); - while (mP2pProxyInstance.isStarted() == false) Thread.sleep(500); - - mP2pProxyAccountManagement = new P2pProxyAccountManagement((JxtaNetworkManager)mP2pProxyInstance.getOpaqueNetworkManager()); - - try { - mP2pProxyAccountManagement.createAccount(mDefaultSipIdentity); - } catch (Exception e) { - mLog.warn(e); - } - try { - mP2pProxyAccountManagement.createAccount(mCallerUri); - } catch (Exception e) { - mLog.warn(e); - } - - try { - mP2pProxyAccountManagement.createAccount(mCalleeUri); - } catch (Exception e) { - mLog.warn(e); - } - } - - //@Before - public void setUp() throws Exception { - if (mP2pProxyInstance == null) { - setUpBeforeClass(); - } - } - public void testAddressRequest() throws Exception { - try { - - Assert.assertTrue("cannot get relay addresses" ,mP2pProxyInstance.getRtpRelayManager().getAddresses().size()!=0); - mLog.info("testAddressRequest ok"); - } catch (Exception e) { - mLog.error("testAddressRequest ko",e); - Assert.fail(e.getMessage()); - } - } - public void testCallWithRelay() throws Exception { - try { - SipClient lCaller = new SipClient(mP2pProxyInstance.getSipClientProvider(),mCallerUri,mP2pProxyInstance.getAdvertisementDiscoveryTimeout()); - lCaller.register(); - SipClient lCallee = new SipClient(mP2pProxyInstance.getSipClientProvider(),mCalleeUri,mP2pProxyInstance.getAdvertisementDiscoveryTimeout()); - lCallee.register(); - - mLog.info("testCallWithRelay ok"); - } catch (Exception e) { - mLog.error("testCallWithRelay ko",e); - Assert.fail(e.getMessage()); - } - - } -} diff --git a/p2pproxy/test-src/org/linphone/p2pproxy/test/utils/DefaultCallListener.java b/p2pproxy/test-src/org/linphone/p2pproxy/test/utils/DefaultCallListener.java deleted file mode 100644 index fddfbb17..00000000 --- a/p2pproxy/test-src/org/linphone/p2pproxy/test/utils/DefaultCallListener.java +++ /dev/null @@ -1,75 +0,0 @@ -/* -p2pproxy -Copyright (C) 2007 Jehan Monnier () - -DefaultCallListener.java - . - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.test.utils; - -import java.util.Vector; - -import junit.framework.Assert; - -import org.zoolu.sip.address.NameAddress; -import org.zoolu.sip.call.Call; -import org.zoolu.sip.call.CallListener; -import org.zoolu.sip.message.Message; - -public class DefaultCallListener implements CallListener { - public void onCallAccepted(Call call, String sdp, Message resp) { - Assert.fail("call accepted"); - } - public void onCallCanceling(Call call, Message cancel) { - Assert.fail("call canceled"); - } - public void onCallClosed(Call call, Message resp) { - Assert.fail("call closed"); } - - public void onCallClosing(Call call, Message bye) { - Assert.fail("call closing"); - } - public void onCallConfirmed(Call call, String sdp, Message ack) { - Assert.fail("call Confirmed"); - } - public void onCallIncoming(Call call, NameAddress callee, NameAddress caller, String sdp, Message invite) { - Assert.fail("call Incoming"); - } - public void onCallModifying(Call call, String sdp, Message invite) { - Assert.fail("call Modifying"); - } - public void onCallReInviteAccepted(Call call, String sdp, Message resp) { - Assert.fail("call ReInviteAccepted"); - } - public void onCallReInviteRefused(Call call, String reason, Message resp) { - Assert.fail("call ReInviteRefused"); - } - public void onCallReInviteTimeout(Call call) { - Assert.fail("call ReInviteTimeout"); - } - public void onCallRedirection(Call call, String reason, Vector contact_list, Message resp) { - Assert.fail("call Redirection"); - } - public void onCallRefused(Call call, String reason, Message resp) { - Assert.fail("call Refused reason ["+resp.getStatusLine()+"]"); - } - public void onCallRinging(Call call, Message resp) { - Assert.fail("call Ringing"); - } - public void onCallTimeout(Call call) { - Assert.fail("call Timeout"); - } -} diff --git a/p2pproxy/test-src/org/linphone/p2pproxy/test/utils/P2pNetwork.java b/p2pproxy/test-src/org/linphone/p2pproxy/test/utils/P2pNetwork.java deleted file mode 100644 index eefbe34a..00000000 --- a/p2pproxy/test-src/org/linphone/p2pproxy/test/utils/P2pNetwork.java +++ /dev/null @@ -1,224 +0,0 @@ -/* -p2pproxy Copyright (C) 2007 Jehan Monnier () - -P2pNetwork.java -- create a jxta network. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -package org.linphone.p2pproxy.test.utils; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.InetAddress; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLClassLoader; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.InvalidPropertiesFormatException; -import java.util.List; - -import javax.security.cert.CertificateException; - -import org.apache.log4j.Logger; -import org.linphone.p2pproxy.api.P2pProxyInstance; -import org.linphone.p2pproxy.api.P2pProxyInstance.Mode; - -import net.jxta.exception.JxtaException; - -//import org.linphone.p2pproxy.Configurator; -//import org.linphone.p2pproxy.JxtaNetworkManager; -//import org.linphone.p2pproxy.P2pProxyException; - - -public class P2pNetwork { - private List mEdges = new ArrayList(); - private List mSuperPeers = new ArrayList(); - private final static Logger mLog = Logger.getLogger(P2pNetwork.class); - Process mSshProcess; - //String mPrivateAdress = "192.168.145.1"; - String mPrivateAdress = "127.0.0.1"; - - String mPublicAdress ; - String mPublicAdressUser ; - /** - * create a p2p network with super peers and edges - * @param nEdgees number of edge peer - * @param mRdv number of super peer - * @throws IOException - * @throws FileNotFoundException - * @throws InvalidPropertiesFormatException - * @throws CertificateException - * @throws URISyntaxException - * @throws P2pProxyException - * @throws InterruptedException - * @throws JxtaException - */ - public P2pNetwork(int nEdge,int mRdv) throws Exception { - this(nEdge,mRdv,0,0,100,false,System.getProperty("user.name"),"127.0.0.1"); - } - public P2pNetwork(int nEdge,int mRdv,int pAuto,int aBaseIndex,int aRelayCapacity, boolean isNated, String aUser,String aRemoteHost) throws Exception { - mPublicAdress = aRemoteHost; - mPublicAdressUser=aUser; - try { - - if (isNated == true) { - - //1 - setupDummySocks(aBaseIndex,nEdge+mRdv+pAuto); - //2 - - System.setProperty("socksProxyHost", mPrivateAdress); - System.setProperty("socksProxyPort", "1080"); - } - String [] lClassPath = { - "./antbuild/p2pproxy" - ,"./dependencies/bcprov-jdk14.jar" - ,"./dependencies/javax.servlet.jar" - ,"./dependencies/org.mortbay.jetty.jar" - }; - URL[] lUrlTab = new URL[lClassPath.length]; - for (int i=0;i(mEdges)) { - if (lP2pProxyInstance.isStarted() == false) { - lstarted = false; - } else { - if (lP2pProxyInstance.getMode() == Mode.relay) { - // move from edge list to relay - mEdges.remove(lP2pProxyInstance); - mSuperPeers.add(lP2pProxyInstance); - mLog.info("peer [ "+lP2pProxyInstance+"] moved from edge to relay" ); - } - } - } - Thread.sleep(1000); - }while (lstarted == false); - mLog.info("P2pNetwork started with ["+getEdgesPeers().size()+"] egdges and ["+getSuperPeers().size()+"]super peers"); - - } catch (Exception e) { - mLog.fatal("cannot create network",e); - } - - } - /** - * @return Returns the mEdges. - */ - public List getEdgesPeers() { - return mEdges; - } - /** - * @return Returns the mSuperPeers. - */ - public List getSuperPeers() { - return mSuperPeers; - } - public List getAllPeers() { - List lP2pProxyInstanceList = new ArrayList (); - lP2pProxyInstanceList.addAll(mSuperPeers); - lP2pProxyInstanceList.addAll(mEdges); - return lP2pProxyInstanceList; - } - public void stop() { - for (P2pProxyInstance lP2pProxyInstance:getAllPeers()) { - try { - lP2pProxyInstance.stop(); - } catch (Exception e) { - mLog.error("stop error", e); - //nop - } - } - mSshProcess.destroy(); - - } - private void setupDummySocks(int aBaseIndex, int numberOfPeers) throws InterruptedException, IOException { - StringBuffer lCommand =new StringBuffer("ssh -D "+mPrivateAdress+":1080 "); - for (int i=aBaseIndex; i 0) { - mRtpRelayServerTester = new RtpRelayServerTester(mStunClient.getStrunServerList().get(0)); - } - mIsRegistered = true; - } - catch(Exception e) { - mLog.error("cannot register user["+userName+"]",e); - } finally { - mTimer.schedule(new RegistrarTimerTask(), 1000 *(REGISTRATION_PERIOD-REGISTRATION_PERIOD/10)); - } - } - - }; - mTimer.schedule(new RegistrarTimerTask(), 0); - mSipClient.listen(); - } catch (Exception e) { - throw new P2pProxyException("cannot start client",e); - } -} -public void call(String aTo, int duration) { - mSipClient.call(aTo, true, duration); - if (mRtpRelayServerTester != null) { - mRtpRelayServerTester.testRouting(); - mLog.info("rtp relay ok"); - } -} -public static void main(String[] args) throws P2pProxyException { - String lFrom=null, lTo=null, lPreferedProxyUri=null; - int lDuration = 10000, lLoop=0; - for (int i=0; i < args.length; i=i+2) { - String argument = args[i]; - if (argument.equals("-from")) { - lFrom = args[i + 1]; - System.out.println("from [" + lFrom + "]"); - //nop - } else if (argument.equals("-to")) { - lTo = args[i + 1]; - System.out.println("to [" + lTo + "]"); - - } else if (argument.equals("-duration")) { - lDuration = Integer.parseInt(args[i + 1]); - System.out.println("duration [" + lDuration + "]"); - - } else if (argument.equals("-nb-call")) { - lLoop = Integer.parseInt(args[i + 1]); - System.out.println("nb-call [" + lLoop + "]"); - } else if (argument.equals("-prefered-proxy")) { - lPreferedProxyUri = args[i + 1]; - System.out.println("prefered-proxy [" + lLoop + "]"); - } - else { - System.out.println("Invalid option: " + args[i]); - usage(); - System.exit(1); - } - } - - if (lFrom == null) { - System.out.println("missing -from "); - usage(); - System.exit(1); - } - if (lLoop != 0 && lTo == null) { - System.out.println("missing -to "); - usage(); - System.exit(1); - } - - UserInstance lUserInstance= new UserInstance(lFrom,lPreferedProxyUri); - while (mIsRegistered == false) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - //nop; - } - } - for (int i=0;i